Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python.
legend display legend
1 legend basics
Function prototype legend(*args, **kwargs)
When len(args) == 2
args is a collection of [artist] and [label]
When len(args) == 0
args will automatically call get_legend_handles_labels() to generate
Equivalent to
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles, labels)
The purpose of ax.get_legend_handles_labels() is to return all objects of ax.lines, ax.patch and LineCollection or RegularPolyCollection objects in ax.collection
Note: Only limited support is provided here, not all artists can be used as legends, such as errorbar support is not perfect
1.1 Adjustment sequence
ax = subplot(1,1,1)
p1, = ax.plot([1,2,3], label="line 1")
p2, = ax.plot([3,2,1], label="line 2")
p3, = ax.plot([2,3,1], label="line 3")
handles, labels = ax.get_legend_handles_labels()
# reverse the order
ax.legend(handles[::-1], labels[::-1])
# or sort them by labels
import operator
hl = sorted(zip(handles, labels), key=operator.itemgetter(1))
handles2, labels2 = zip(*hl)
ax.legend(handles2, labels2)
1.2 Using agent
When you need to use an artist that is not supported by the legend, you can use another artist supported by the legend as a proxy
For example, the following example uses an artist who is not on axe
p = Rectangle((0, 0), 1, 1, fc="r")
legend([p], ["Red Rectangle"])
2 Multi-column legend
ax1 = plt.subplot(3,1,1)
ax1.plot([1], label="multinline")
ax1.plot([1], label="$2^{2^2}$")
ax1.plot([1], label=r"$frac{1}{2}pi$")
ax1.legend(loc=1, ncol=3, shadow=True)
ax2 = plt.subplot(3,1,2)
myplot(ax2)
ax2.legend(loc="center left", bbox_to_anchor=[0.5, 0.5],
ncol=2, shadow=True, title="Legend")
ax2.get_legend().get_title().set_color("red")
3 Legend location
ax.legend(…., loc=3)
4 multiple legends
If no measures are taken, calling two legends in succession will cause the later legend to overwrite the previous one
from matplotlib.pyplot import * p1, = plot([1,2,3], label="test1")
p2, = plot([3,2,1], label="test2")
l1 = legend([p1], ["Label 1"], loc=1)
l2 = legend([p2], ["Label 2"], loc=4) # this removes l1 from the axes.
gca().add_artist(l1) # add l1 as a separate artist to the axes
5. API
class matplotlib.legend.Legend(parent, handles, labels,**args)
The three most important necessary parameters
parent --- the legend's parent artist, contains the object of legend
For example, after calling with ax.legend()
>>> print ax.get_legend().parent
Axes(0.125,0.1;0.775x0.8)
handles --- each artist (lines, patches) drawn on the legend
labels --- artist corresponding labels
Other parameters
Keyword
Description
loc
a location code
prop
the font property (matplotlib.font_manager.FontProperties object)
eg
song_font = matplotlib.font_manager.FontProperties(fname='simsun.ttc', size=8)
fontsize
the font size (mutually exclusive with prop, cannot be used at the same time)
markerscale
the relative size of legend markers vs. original
numpoints
the number of points in the legend for line
scatterpoints
the number of points in the legend for scatter plot
scatteryoffsets
a list of yoffsets for scatter symbols in legend
frameon
if True, draw a frame around the legend. If None, use rc
fancybox
if True, draw a frame with a round fancybox. If None, use rc
shadow
if True, draw a shadow behind legend
ncol
number of columns
borderpad
the fractional whitespace inside the legend border
labelspacing
the vertical space between the legend entries
handlelength
the length of the legend handles
handleheight
the length of the legend handles
handletextpad
the pad between the legend handle and text
borderaxespad
the pad between the axes and legend border
columnspacing
the spacing between columns
title
the legend title
bbox_to_anchor
the bbox that the legend will be anchored.
bbox_transform
the transform for the bbox. transAxes if None.
Main function
get_frame() --- returns the square object where the legend is located
get_lines()
get_patches()
get_texts()
get_title() --- The above are relatively simple, no explanation
set_bbox_to_anchor(bbox, transform=None)
(…This function is to be continued… I will add it later when I write axes. At present, I do not understand the relationship between his length and width and figure and axes.)
6. Sample
leg = ax.legend(('Model length','Data length','Total message length'),
'upper center', shadow=True)
# the matplotlib.patches.Rectangle instance surrounding the legend
frame = leg.get_frame()
frame.set_facecolor('0.80') # set the frame face color to light gray
# matplotlib.text.Text instances is the text in the legend
for t in leg.get_texts():
t.set_fontsize('small') # the legend text fontsize
# matplotlib.lines.Line2D instances is the artist represented in the legend
for l in leg.get_lines():
l.set_linewidth(1.5) # the legend line width
fig = plt.figure()
ax1 = fig.add_axes([0.1, 0.1, 0.4, 0.7])
ax2 = fig.add_axes([0.55, 0.1, 0.4, 0.7])
x = np.arange(0.0, 2.0, 0.02)
y1 = np.sin(2*np.pi*x)
y2 = np.exp(-x)
l1, l2 = ax1.plot(x, y1,'rs-', x, y2,'go')
y3 = np.sin(4*np.pi*x)
y4 = np.exp(-2*x)
l3, l4 = ax2.plot(x, y3,'yd-', x, y3,'k^')
fig.legend((l1, l2), ('Line 1','Line 2'),'upper left')
fig.legend((l3, l4), ('Line 3','Line 4'),'upper right')