How to display a legend with matplotlib











up vote
-1
down vote

favorite












I am trying to get a legend to appear in matplotlib in order to display an r^2 value but the legend will not display. Any help would be much appreciated.



import matplotlib.pyplot as plt
import numpy as np
from scipy import stats

# Filling in the values obtained in the real image experiment
object_distance = np.array(range(15, 66, 5))
object_distance_error = 0.1
real_image_distance = np.array([29.5, 21.0, 17.4, 15.4, 14.3, 13.7, 13.1, 13.0, 12.6, 12.3, 12.3])
real_image_distance_error = 0.1
real_image_size = np.array([3.6, 2.0, 1.4, 1.0, 0.8, 0.7, 0.5, 0.45, 0.4, 0.4, 0.35])
real_image_size_error = 0.1
real_focus = 10

inverse_obj = 1.0/object_distance
inverse_rl_img = 1.0/real_image_distance
rl_slope, rl_intercept, rl_r_value, rl_p_value, rl_std_err = stats.linregress(inverse_obj, inverse_rl_img)
rl_line = inverse_obj*rl_slope + rl_intercept
r_squared = str(round(rl_r_value**2, 4))


fig1 = plt.figure()
fig1.set_size_inches(10, 10)
plt.plot(inverse_obj, inverse_rl_img, 'o', markersize=3)
plt.plot(inverse_obj, rl_line)

plt.xlabel('$Object$ ' + r'$Distance^-$'+r'$^1$' + r' (cm' + r'$^-$' +r'$^1$' + r')')
plt.ylabel('$Image$ ' + r'$Distance^-$'+r'$^1$' + r' (cm' + r'$^-$' +r'$^1$' + r')')
plt.legend([rl_line], [r"$r^2$" + r_squared])
plt.title("Graph of 1/s vs 1/s'")
plt.show()









share|improve this question






















  • legend doesn't support an array
    – Dejan Marić
    Nov 8 at 14:13

















up vote
-1
down vote

favorite












I am trying to get a legend to appear in matplotlib in order to display an r^2 value but the legend will not display. Any help would be much appreciated.



import matplotlib.pyplot as plt
import numpy as np
from scipy import stats

# Filling in the values obtained in the real image experiment
object_distance = np.array(range(15, 66, 5))
object_distance_error = 0.1
real_image_distance = np.array([29.5, 21.0, 17.4, 15.4, 14.3, 13.7, 13.1, 13.0, 12.6, 12.3, 12.3])
real_image_distance_error = 0.1
real_image_size = np.array([3.6, 2.0, 1.4, 1.0, 0.8, 0.7, 0.5, 0.45, 0.4, 0.4, 0.35])
real_image_size_error = 0.1
real_focus = 10

inverse_obj = 1.0/object_distance
inverse_rl_img = 1.0/real_image_distance
rl_slope, rl_intercept, rl_r_value, rl_p_value, rl_std_err = stats.linregress(inverse_obj, inverse_rl_img)
rl_line = inverse_obj*rl_slope + rl_intercept
r_squared = str(round(rl_r_value**2, 4))


fig1 = plt.figure()
fig1.set_size_inches(10, 10)
plt.plot(inverse_obj, inverse_rl_img, 'o', markersize=3)
plt.plot(inverse_obj, rl_line)

plt.xlabel('$Object$ ' + r'$Distance^-$'+r'$^1$' + r' (cm' + r'$^-$' +r'$^1$' + r')')
plt.ylabel('$Image$ ' + r'$Distance^-$'+r'$^1$' + r' (cm' + r'$^-$' +r'$^1$' + r')')
plt.legend([rl_line], [r"$r^2$" + r_squared])
plt.title("Graph of 1/s vs 1/s'")
plt.show()









share|improve this question






















  • legend doesn't support an array
    – Dejan Marić
    Nov 8 at 14:13















up vote
-1
down vote

favorite









up vote
-1
down vote

favorite











I am trying to get a legend to appear in matplotlib in order to display an r^2 value but the legend will not display. Any help would be much appreciated.



import matplotlib.pyplot as plt
import numpy as np
from scipy import stats

# Filling in the values obtained in the real image experiment
object_distance = np.array(range(15, 66, 5))
object_distance_error = 0.1
real_image_distance = np.array([29.5, 21.0, 17.4, 15.4, 14.3, 13.7, 13.1, 13.0, 12.6, 12.3, 12.3])
real_image_distance_error = 0.1
real_image_size = np.array([3.6, 2.0, 1.4, 1.0, 0.8, 0.7, 0.5, 0.45, 0.4, 0.4, 0.35])
real_image_size_error = 0.1
real_focus = 10

inverse_obj = 1.0/object_distance
inverse_rl_img = 1.0/real_image_distance
rl_slope, rl_intercept, rl_r_value, rl_p_value, rl_std_err = stats.linregress(inverse_obj, inverse_rl_img)
rl_line = inverse_obj*rl_slope + rl_intercept
r_squared = str(round(rl_r_value**2, 4))


fig1 = plt.figure()
fig1.set_size_inches(10, 10)
plt.plot(inverse_obj, inverse_rl_img, 'o', markersize=3)
plt.plot(inverse_obj, rl_line)

plt.xlabel('$Object$ ' + r'$Distance^-$'+r'$^1$' + r' (cm' + r'$^-$' +r'$^1$' + r')')
plt.ylabel('$Image$ ' + r'$Distance^-$'+r'$^1$' + r' (cm' + r'$^-$' +r'$^1$' + r')')
plt.legend([rl_line], [r"$r^2$" + r_squared])
plt.title("Graph of 1/s vs 1/s'")
plt.show()









share|improve this question













I am trying to get a legend to appear in matplotlib in order to display an r^2 value but the legend will not display. Any help would be much appreciated.



import matplotlib.pyplot as plt
import numpy as np
from scipy import stats

# Filling in the values obtained in the real image experiment
object_distance = np.array(range(15, 66, 5))
object_distance_error = 0.1
real_image_distance = np.array([29.5, 21.0, 17.4, 15.4, 14.3, 13.7, 13.1, 13.0, 12.6, 12.3, 12.3])
real_image_distance_error = 0.1
real_image_size = np.array([3.6, 2.0, 1.4, 1.0, 0.8, 0.7, 0.5, 0.45, 0.4, 0.4, 0.35])
real_image_size_error = 0.1
real_focus = 10

inverse_obj = 1.0/object_distance
inverse_rl_img = 1.0/real_image_distance
rl_slope, rl_intercept, rl_r_value, rl_p_value, rl_std_err = stats.linregress(inverse_obj, inverse_rl_img)
rl_line = inverse_obj*rl_slope + rl_intercept
r_squared = str(round(rl_r_value**2, 4))


fig1 = plt.figure()
fig1.set_size_inches(10, 10)
plt.plot(inverse_obj, inverse_rl_img, 'o', markersize=3)
plt.plot(inverse_obj, rl_line)

plt.xlabel('$Object$ ' + r'$Distance^-$'+r'$^1$' + r' (cm' + r'$^-$' +r'$^1$' + r')')
plt.ylabel('$Image$ ' + r'$Distance^-$'+r'$^1$' + r' (cm' + r'$^-$' +r'$^1$' + r')')
plt.legend([rl_line], [r"$r^2$" + r_squared])
plt.title("Graph of 1/s vs 1/s'")
plt.show()






python python-2.7 matplotlib






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 8 at 14:10









Glum_Mathematician

1




1












  • legend doesn't support an array
    – Dejan Marić
    Nov 8 at 14:13




















  • legend doesn't support an array
    – Dejan Marić
    Nov 8 at 14:13


















legend doesn't support an array
– Dejan Marić
Nov 8 at 14:13






legend doesn't support an array
– Dejan Marić
Nov 8 at 14:13














2 Answers
2






active

oldest

votes

















up vote
0
down vote













You are trying define the text legend and plot in the same command, change for this:



fig1 = plt.figure()
fig1.set_size_inches(10, 10)
plt.plot(inverse_obj, inverse_rl_img, 'o', markersize=3, label='rl_line')
plt.plot(inverse_obj, rl_line, label='$r^2$ + r_squared')
plt.legend()

plt.xlabel('$Object$ ' + r'$Distance^-$'+r'$^1$' + r' (cm' + r'$^-$' +r'$^1$' + r')')
plt.ylabel('$Image$ ' + r'$Distance^-$'+r'$^1$' + r' (cm' + r'$^-$' +r'$^1$' + r')')
plt.title("Graph of 1/s vs 1/s'")
plt.show()


Remember that plt.legend() is just a method which calls a legend inside the graph. To define the legend use plt.plot(label='rl_line') for example.






share|improve this answer




























    up vote
    0
    down vote













    You can also use patches:



    import matplotlib.patches as mpatches


    then define e.g. red_patch:



    red_patch = mpatches.Patch(color='red', label=f'ru00b2={r_squared}')


    and add it in plt.legend(),



    plt.legend(handles=[red_patch], ...)


    you'll get something like this:



    enter image description here






    share|improve this answer





















      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53209472%2fhow-to-display-a-legend-with-matplotlib%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      0
      down vote













      You are trying define the text legend and plot in the same command, change for this:



      fig1 = plt.figure()
      fig1.set_size_inches(10, 10)
      plt.plot(inverse_obj, inverse_rl_img, 'o', markersize=3, label='rl_line')
      plt.plot(inverse_obj, rl_line, label='$r^2$ + r_squared')
      plt.legend()

      plt.xlabel('$Object$ ' + r'$Distance^-$'+r'$^1$' + r' (cm' + r'$^-$' +r'$^1$' + r')')
      plt.ylabel('$Image$ ' + r'$Distance^-$'+r'$^1$' + r' (cm' + r'$^-$' +r'$^1$' + r')')
      plt.title("Graph of 1/s vs 1/s'")
      plt.show()


      Remember that plt.legend() is just a method which calls a legend inside the graph. To define the legend use plt.plot(label='rl_line') for example.






      share|improve this answer

























        up vote
        0
        down vote













        You are trying define the text legend and plot in the same command, change for this:



        fig1 = plt.figure()
        fig1.set_size_inches(10, 10)
        plt.plot(inverse_obj, inverse_rl_img, 'o', markersize=3, label='rl_line')
        plt.plot(inverse_obj, rl_line, label='$r^2$ + r_squared')
        plt.legend()

        plt.xlabel('$Object$ ' + r'$Distance^-$'+r'$^1$' + r' (cm' + r'$^-$' +r'$^1$' + r')')
        plt.ylabel('$Image$ ' + r'$Distance^-$'+r'$^1$' + r' (cm' + r'$^-$' +r'$^1$' + r')')
        plt.title("Graph of 1/s vs 1/s'")
        plt.show()


        Remember that plt.legend() is just a method which calls a legend inside the graph. To define the legend use plt.plot(label='rl_line') for example.






        share|improve this answer























          up vote
          0
          down vote










          up vote
          0
          down vote









          You are trying define the text legend and plot in the same command, change for this:



          fig1 = plt.figure()
          fig1.set_size_inches(10, 10)
          plt.plot(inverse_obj, inverse_rl_img, 'o', markersize=3, label='rl_line')
          plt.plot(inverse_obj, rl_line, label='$r^2$ + r_squared')
          plt.legend()

          plt.xlabel('$Object$ ' + r'$Distance^-$'+r'$^1$' + r' (cm' + r'$^-$' +r'$^1$' + r')')
          plt.ylabel('$Image$ ' + r'$Distance^-$'+r'$^1$' + r' (cm' + r'$^-$' +r'$^1$' + r')')
          plt.title("Graph of 1/s vs 1/s'")
          plt.show()


          Remember that plt.legend() is just a method which calls a legend inside the graph. To define the legend use plt.plot(label='rl_line') for example.






          share|improve this answer












          You are trying define the text legend and plot in the same command, change for this:



          fig1 = plt.figure()
          fig1.set_size_inches(10, 10)
          plt.plot(inverse_obj, inverse_rl_img, 'o', markersize=3, label='rl_line')
          plt.plot(inverse_obj, rl_line, label='$r^2$ + r_squared')
          plt.legend()

          plt.xlabel('$Object$ ' + r'$Distance^-$'+r'$^1$' + r' (cm' + r'$^-$' +r'$^1$' + r')')
          plt.ylabel('$Image$ ' + r'$Distance^-$'+r'$^1$' + r' (cm' + r'$^-$' +r'$^1$' + r')')
          plt.title("Graph of 1/s vs 1/s'")
          plt.show()


          Remember that plt.legend() is just a method which calls a legend inside the graph. To define the legend use plt.plot(label='rl_line') for example.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 8 at 14:21









          Emanuel Fontelles

          18319




          18319
























              up vote
              0
              down vote













              You can also use patches:



              import matplotlib.patches as mpatches


              then define e.g. red_patch:



              red_patch = mpatches.Patch(color='red', label=f'ru00b2={r_squared}')


              and add it in plt.legend(),



              plt.legend(handles=[red_patch], ...)


              you'll get something like this:



              enter image description here






              share|improve this answer

























                up vote
                0
                down vote













                You can also use patches:



                import matplotlib.patches as mpatches


                then define e.g. red_patch:



                red_patch = mpatches.Patch(color='red', label=f'ru00b2={r_squared}')


                and add it in plt.legend(),



                plt.legend(handles=[red_patch], ...)


                you'll get something like this:



                enter image description here






                share|improve this answer























                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  You can also use patches:



                  import matplotlib.patches as mpatches


                  then define e.g. red_patch:



                  red_patch = mpatches.Patch(color='red', label=f'ru00b2={r_squared}')


                  and add it in plt.legend(),



                  plt.legend(handles=[red_patch], ...)


                  you'll get something like this:



                  enter image description here






                  share|improve this answer












                  You can also use patches:



                  import matplotlib.patches as mpatches


                  then define e.g. red_patch:



                  red_patch = mpatches.Patch(color='red', label=f'ru00b2={r_squared}')


                  and add it in plt.legend(),



                  plt.legend(handles=[red_patch], ...)


                  you'll get something like this:



                  enter image description here







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 8 at 14:27









                  Dejan Marić

                  436212




                  436212






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53209472%2fhow-to-display-a-legend-with-matplotlib%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      這個網誌中的熱門文章

                      Hercules Kyvelos

                      Tangent Lines Diagram Along Smooth Curve

                      Yusuf al-Mu'taman ibn Hud