![]() |
|
[Tut] Matplotlib Legend – A Helpful Illustrated Guide - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Matplotlib Legend – A Helpful Illustrated Guide (/thread-94086.html) |
[Tut] Matplotlib Legend – A Helpful Illustrated Guide - xSicKxBot - 03-17-2020 Matplotlib Legend – A Helpful Illustrated Guide You’ve plotted some data in Matplotlibbut you don’t know which data shows what? It’s time for a legend! How to add a legend in Python’s Matplotlib library?
Here’s the minimal example: Code: import matplotlib.pyplot as plt plt.plot([1, 2, 3], [1, 4, 9], label='squares')
plt.plot([1, 2, 3], [1, 8, 27], label='cubes') plt.legend()
plt.show()In the following video, I’ll lead you through the article, step by step. Prettier Example Code: # Import necessary modules
import matplotlib.pyplot as plt
import numpy as np # Optional: Use seaborn style as it looks nicer than matplotlib's default
import seaborn as sns; sns.set() # Generate data
vals = np.array([0, 1, 2, 3, 4]) # Plot and label
plt.plot(vals, label='vals') plt.legend()
plt.show()![]() If you plot and label multiple lines, the legend will contain multiple entries. Code: plt.plot(vals, label='Linear')
plt.plot(vals**2, label='Squared')
plt.plot(vals**0.5, label='Square Root') plt.legend()
plt.show()![]() You can combine different types of plot – scatter, line, histogram etc. – but you may have to specify the colors manually if you do. Code: import random # Set seed to reproduce results
random.seed(1) # Generate random data
x = [random.random() for _ in range(100)]
y = [random.random() for _ in range(100)] # Scatter plot
plt.scatter(x, y, label='Data') # Red line plot acting as the 'line of best fit'
plt.plot([0, 1], label='Best Fit', c='r')
plt.legend()
plt.show()![]() In this example, I first generated some random data before making a scatter plot from it. Then, I drew a line plot on top of it to act as the line of best fit (note that this is just an example and isn’t actually the line of best fit for this dataset!). Unfortunately, matplotlib does not automatically change the color of each plot if you plot a line and a scatter plot on top of each other. So, I manually changed it to red with the Code: cTo learn more about Python’s random module, check out my article. Let’s dive into a more detailed example of how legends work in matplotlib. Matplotlib Legend Example To display a legend on any plot, you must call Code: plt.legend()Code: plt.show()There are 3 ways you can call it:
The first option – Code: plt.legend()Code: labelCode: vals = np.array([0, 1, 2, 3, 4]) # Plot vals first
plt.plot(vals, label='vals') # Plot vals/2 second
plt.plot(vals/2, label='vals/2') # Call plt.legend() without arguments
plt.legend()
plt.show()![]() First I plotted Code: valsCode: vals/2Code: valsCode: # Plot vals/2 first
plt.plot(vals/2, label='vals/2') # Plot vals second
plt.plot(vals, label='vals') # Call plt.legend() without arguments
plt.legend()
plt.show()![]() Now Code: vals/2Note: you can manually control the colors using the Code: cThe second option – Code: plt.legend(labels)The argument Code: labelsCode: plt.plot(x_1, label='plot_1')
plt.plot(x_2, label='plot_2')
plt.legend()
plt.show()You do not label any of the lines explicitly and instead label them based on the order they appear: Code: plt.plot(x_1)
plt.plot(x_2)
plt.legend(['plot_1', 'plot_2'])
plt.show()This method does work but can cause you a lot of headaches. For example, the iterable Code: labelsCode: labelsIt is much easier for everyone if you explicitly label each of the plots rather than implicitly doing so like this. Thus, both the matplotlib docs and I do not recommend you use this method. The final method – Code: plt.legend(handles, labels)Both Code: handlesCode: labelsCode: handlesCode: labelsCode: # Save plots with descriptive variable names
linear, = plt.plot(vals)
sqrt, = plt.plot(vals**0.5) # Create iterables handles and labels
handles = [linear, sqrt]
labels = ['Linear', 'Square Root'] # Pass handles and lables to plt.legend()
plt.legend(handles, labels)
plt.show()![]() First, you must save the output of each line in a variable. The function Code: plt.plot()Code: listCode: matplotlib.lines.Line2DCode: # linear_wrong is a list of length 1
linear_wrong = plt.plot(val) # linear_correct is a Line2D object - what you want
linear_correct, = plt.plot(val)For ease of reading, I created the lists Code: handlesCode: labelsCode: plt.legend()The biggest advantage of this method is that you have total control of the order in which the legend’s items appear: the order you pass Code: handlesSo, to make Code: Square RootCode: linear, = plt.plot(vals)
sqrt, = plt.plot(vals**0.5) # Swap order of sqrt and linear
handles_ = [sqrt, linear]
labels_ = ['Square Root', 'Linear'] plt.legend(handles_, labels_)
plt.show()![]() In this plot, the color of the lines has not changed but the order in the legend has changed because I changed the lists Code: handlesCode: labelsFinally, one thing many Python programmers don’t know is that if your label starts with an underscore, it will not be displayed in the legend. This may be useful if you have many plots and want to be able to easily scan the code but not display the names in the plots. Code: # No legend displayed because of underscore
plt.plot(vals, label='_I will not be displayed')
plt.legend()
plt.show()Code: No handles with labels found to put in legend.![]() Matplotlib Legend Location To change the location of a legend in matplotlib, use the Code: locCode: plt.legend()By default, matplotlib draws the legend in the ‘best’ location i.e. the place that overlaps the least with the lines drawn. This can be slow if you plot a lot of data, so manually setting a location can speed up the process. To manually set it, use the Code: loc
Here are some examples of putting the legend in different locations. If you are unsure how to plot subplots in matplotlib, check out my article. Code: fig, axes = plt.subplots(nrows=1, ncols=3, figsize=plt.figaspect(1/3)) # Differnet legend locations
locations = ['best', 'upper center', 'lower left'] for ax, loc in zip(axes.flat, locations): ax.plot(vals, label='vals') ax.set_title(f"Legend loc='{loc}") # Set legend location ax.legend(loc=loc)
plt.show()![]() You can change the default location for all plots by setting Code: plt.rcParams['legend.loc']Code: locFinally, you can choose any coordinate points by passing a 2-tuple to Code: locCode: loc=(0.5, 0.5)Code: plt.plot(vals, label='vals') # Set location of legend
plt.legend(loc=(0.5, 0.5)) plt.title('Legend loc=(0.5, 0.5)')
plt.show()![]() If you input Code: loc=(2, 2)Code: plt.plot(vals, label='vals') # Set location of legend
plt.legend(loc=(2, 2)) plt.title('Legend loc=(2, 2)')
plt.show()![]() Of course, it is possible to place the legend at any coordinate point you want. Just remember to scale it by the maximum x- and y-axis values (both Code: 4Code: (2, 3)Code: loc=(2/4, 3/4)Code: plt.plot(vals, label='vals') # Set location of legend
plt.legend(loc=(2/4, 3/4)) plt.title('Legend at coordiante points (2, 3)')
plt.show()![]() Matplotlib Legend Font Size To change the fontsize of a legend, use the Code: fontsizeYou can also pass one of several strings: Code: ['xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large']These are all relative to the current default font size. Let’s look at some examples. Code: fig, axes = plt.subplots(nrows=1, ncols=3, figsize=plt.figaspect(1/3)) # Different font sizes to try
fonts = ['xx-small', 'medium', 'x-large'] for ax, font in zip(axes.flat, fonts): ax.plot(vals, label='vals') ax.set_title(f"Legend fontsize='{font}'") # Set fontsize in legend ax.legend(fontsize=font) plt.show()![]() Matplotlib Legend Title To add a title to a legend use the Code: titleCode: plt.plot(vals, label='vals') # Add title to legend
plt.legend(title='My Awesome Legend')
plt.show()![]() Matplotlib Legend Title Font Size To change the font size of the title for a legend in matplotlib use the Code: title_fontsizeCode: fontsizeThe matplotlib docs are actually incorrect because they say that Code: title_fontsizeCode: NoneCode: fig, axes = plt.subplots(nrows=1, ncols=3, figsize=plt.figaspect(1/3)) # Differnet fontsizes to try
title_size = ['large', 5, None] for ax, size in zip(axes.flat, title_size): ax.plot(vals, label='vals') ax.set_title(f"Legend title_fontsize={size}") # Set title_fontsize of the legend ax.legend(title='My Awesome Legend', title_fontsize=size)
plt.show()![]() Matplotlib Legend Color You can change both the Code: facecolorCode: edgecolorThe Code: facecolorCode: edgecolorCode: fig, axes = plt.subplots(nrows=2, ncols=2) # facecolors to choose
colors = ['red', 'blue', 'green', 'yellow'] for ax, color in zip(axes.flat, colors): ax.plot(vals, label=color) # Set facecolor of the legend ax.legend(facecolor=color)
plt.show()![]() Let’s do the same now but just change the edge color. Code: fig, axes = plt.subplots(nrows=2, ncols=2) # Edgecolors to choose
colors = ['red', 'blue', 'green', 'yellow'] for ax, color in zip(axes.flat, colors): ax.plot(vals, label=color) # Choose edgecolor of legend ax.legend(edgecolor=color)
plt.show()![]() Of course, you can mix and match the face and edge colors to your heart’s content. Code: fig, axes = plt.subplots(nrows=2, ncols=2) # Colors to use
colors = ['red', 'blue', 'green', 'yellow'] # Same as colors but reversed
edges = colors[::-1] for ax, color, edge in zip(axes.flat, colors, edges): ax.plot([0, 1, 2, 3, 4], label=color) # Choose both the facecolor and edgecolor ax.legend(facecolor=color, edgecolor=edge)
plt.show()![]() Matplotlib Legend Order To learn how to order elements in a legend, check out the Matplotlib Legend Example section. Matplotlib Legend Background Color To learn how to change the background color of a legend, check out the Matplotlib Legend Color section. Conclusion That’s it, you now know all the basics of working with legends in matplotlib. You know the three different ways to call the function – Code: plt.legend()Code: plt.legend(labels)Code: plt.legend(handles, labels)Where To Go From Here? Do you wish you could be a programmer full-time but don’t know how to start? Check out the pure value-packed webinar where Chris – creator of Finxter.com – teaches you to become a Python freelancer in 60 days or your money back! https://tinyurl.com/become-a-python-freelancer It doesn’t matter if you’re a Python novice or Python pro. If you are not making six figures/year with Python right now, you will learn something from this webinar. These are proven, no-BS methods that get you results fast. This webinar won’t be online forever. Click the link below before the seats fill up and learn how to become a Python freelancer, guaranteed. https://tinyurl.com/become-a-python-freelancer |