The default legend is:
In this page, all legend options are tried.
The documents of the options are described on the following web page:
- legend and legend_handler, matplotlib.legend - matplotlib -
https://matplotlib.org/api/legend_api.html
In [1]:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
In [2]:
x1 = np.random.normal(loc=0, scale=1, size=100)
y1 = np.random.normal(loc=0, scale=1, size=100)
x2 = np.random.normal(loc=1, scale=1, size=100)
y2 = np.random.normal(loc=1, scale=1, size=100)
x3 = np.random.normal(loc=0, scale=1, size=100)
y3 = np.random.normal(loc=0, scale=1, size=100)
x4 = np.random.normal(loc=1, scale=1, size=100)
y4 = np.random.normal(loc=1, scale=1, size=100)
In [3]:
plt.legend?
Signature: plt.legend(*args, **kwargs) Docstring: Places a legend on the axes. To make a legend for lines which already exist on the axes (via plot for instance), simply call this function with an iterable of strings, one for each legend item. For example:: ax.plot([1, 2, 3]) ax.legend(['A simple line']) However, in order to keep the "label" and the legend element instance together, it is preferable to specify the label either at artist creation, or by calling the :meth:`~matplotlib.artist.Artist.set_label` method on the artist:: line, = ax.plot([1, 2, 3], label='Inline label') # Overwrite the label by calling the method. line.set_label('Label via method') ax.legend() Specific lines can be excluded from the automatic legend element selection by defining a label starting with an underscore. This is default for all artists, so calling :meth:`legend` without any arguments and without setting the labels manually will result in no legend being drawn. For full control of which artists have a legend entry, it is possible to pass an iterable of legend artists followed by an iterable of legend labels respectively:: legend((line1, line2, line3), ('label1', 'label2', 'label3')) Parameters ---------- loc : int or string or pair of floats, default: 'upper right' The location of the legend. Possible codes are: =============== ============= Location String Location Code =============== ============= 'best' 0 'upper right' 1 'upper left' 2 'lower left' 3 'lower right' 4 'right' 5 'center left' 6 'center right' 7 'lower center' 8 'upper center' 9 'center' 10 =============== ============= Alternatively can be a 2-tuple giving ``x, y`` of the lower-left corner of the legend in axes coordinates (in which case ``bbox_to_anchor`` will be ignored). bbox_to_anchor : `~.BboxBase` or pair of floats Specify any arbitrary location for the legend in `bbox_transform` coordinates (default Axes coordinates). For example, to put the legend's upper right hand corner in the center of the axes the following keywords can be used:: loc='upper right', bbox_to_anchor=(0.5, 0.5) ncol : integer The number of columns that the legend has. Default is 1. prop : None or :class:`matplotlib.font_manager.FontProperties` or dict The font properties of the legend. If None (default), the current :data:`matplotlib.rcParams` will be used. fontsize : int or float or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'} Controls the font size of the legend. If the value is numeric the size will be the absolute font size in points. String values are relative to the current default font size. This argument is only used if `prop` is not specified. numpoints : None or int The number of marker points in the legend when creating a legend entry for a line/:class:`matplotlib.lines.Line2D`. Default is ``None`` which will take the value from the ``legend.numpoints`` :data:`rcParam`. scatterpoints : None or int The number of marker points in the legend when creating a legend entry for a scatter plot/ :class:`matplotlib.collections.PathCollection`. Default is ``None`` which will take the value from the ``legend.scatterpoints`` :data:`rcParam `. scatteryoffsets : iterable of floats The vertical offset (relative to the font size) for the markers created for a scatter plot legend entry. 0.0 is at the base the legend text, and 1.0 is at the top. To draw all markers at the same height, set to ``[0.5]``. Default ``[0.375, 0.5, 0.3125]``. markerscale : None or int or float The relative size of legend markers compared with the originally drawn ones. Default is ``None`` which will take the value from the ``legend.markerscale`` :data:`rcParam `. markerfirst : bool If *True*, legend marker is placed to the left of the legend label. If *False*, legend marker is placed to the right of the legend label. Default is *True*. frameon : None or bool Control whether the legend should be drawn on a patch (frame). Default is ``None`` which will take the value from the ``legend.frameon`` :data:`rcParam `. fancybox : None or bool Control whether round edges should be enabled around the :class:`~matplotlib.patches.FancyBboxPatch` which makes up the legend's background. Default is ``None`` which will take the value from the ``legend.fancybox`` :data:`rcParam `. shadow : None or bool Control whether to draw a shadow behind the legend. Default is ``None`` which will take the value from the ``legend.shadow`` :data:`rcParam `. framealpha : None or float Control the alpha transparency of the legend's background. Default is ``None`` which will take the value from the ``legend.framealpha`` :data:`rcParam `. If shadow is activated and framealpha is ``None`` the default value is being ignored. facecolor : None or "inherit" or a color spec Control the legend's background color. Default is ``None`` which will take the value from the ``legend.facecolor`` :data:`rcParam `. If ``"inherit"``, it will take the ``axes.facecolor`` :data:`rcParam `. edgecolor : None or "inherit" or a color spec Control the legend's background patch edge color. Default is ``None`` which will take the value from the ``legend.edgecolor`` :data:`rcParam `. If ``"inherit"``, it will take the ``axes.edgecolor`` :data:`rcParam `. mode : {"expand", None} If `mode` is set to ``"expand"`` the legend will be horizontally expanded to fill the axes area (or `bbox_to_anchor` if defines the legend's size). bbox_transform : None or :class:`matplotlib.transforms.Transform` The transform for the bounding box (`bbox_to_anchor`). For a value of ``None`` (default) the Axes' :data:`~matplotlib.axes.Axes.transAxes` transform will be used. title : str or None The legend's title. Default is no title (``None``). borderpad : float or None The fractional whitespace inside the legend border. Measured in font-size units. Default is ``None`` which will take the value from the ``legend.borderpad`` :data:`rcParam `. labelspacing : float or None The vertical space between the legend entries. Measured in font-size units. Default is ``None`` which will take the value from the ``legend.labelspacing`` :data:`rcParam `. handlelength : float or None The length of the legend handles. Measured in font-size units. Default is ``None`` which will take the value from the ``legend.handlelength`` :data:`rcParam `. handletextpad : float or None The pad between the legend handle and text. Measured in font-size units. Default is ``None`` which will take the value from the ``legend.handletextpad`` :data:`rcParam `. borderaxespad : float or None The pad between the axes and legend border. Measured in font-size units. Default is ``None`` which will take the value from the ``legend.borderaxespad`` :data:`rcParam `. columnspacing : float or None The spacing between columns. Measured in font-size units. Default is ``None`` which will take the value from the ``legend.columnspacing`` :data:`rcParam `. handler_map : dict or None The custom dictionary mapping instances or types to a legend handler. This `handler_map` updates the default handler map found at :func:`matplotlib.legend.Legend.get_legend_handler_map`. Returns ------- :class:`matplotlib.legend.Legend` instance Notes ----- Not all kinds of artist are supported by the legend command. See :ref:`sphx_glr_tutorials_intermediate_legend_guide.py` for details. Examples -------- .. plot:: gallery/api/legend.py File: ****/lib/python3.6/site-packages/matplotlib/pyplot.py Type: function
In [4]:
plt.legend??
Signature: plt.legend(*args, **kwargs) Source: @docstring.copy_dedent(Axes.legend) def legend(*args, **kwargs): ret = gca().legend(*args, **kwargs) return ret File: ****/lib/python3.6/site-packages/matplotlib/pyplot.py Type: function
Default legend in my environment¶
In [5]:
plt.figure(figsize=(4,3))
plt.scatter(x1, y1, label='x1,y1')
plt.scatter(x2, y2, label='x2,y2')
plt.scatter(x3, y3, label='x3,y3')
plt.scatter(x4, y4, label='x4,y4')
plt.legend()
plt.savefig('try_all_legend_options_default.png',dpi=250)
plt.show()
loc¶
loc : int or string or pair of floats, default: 'upper right' The location of the legend. Possible codes are: =============== ============= Location String Location Code =============== ============= 'best' 0 'upper right' 1 'upper left' 2 'lower left' 3 'lower right' 4 'right' 5 'center left' 6 'center right' 7 'lower center' 8 'upper center' 9 'center' 10 =============== ============= Alternatively can be a 2-tuple giving ``x, y`` of the lower-left corner of the legend in axes coordinates (in which case ``bbox_to_anchor`` will be ignored).
In [6]:
plt.figure(figsize=(4,3))
plt.scatter(x1, y1, label='x1,y1')
plt.scatter(x2, y2, label='x2,y2')
plt.scatter(x3, y3, label='x3,y3')
plt.scatter(x4, y4, label='x4,y4')
plt.legend(loc="lower right")
plt.show()
bbox_to_anchor¶
bbox_to_anchor : `~.BboxBase` or pair of floats Specify any arbitrary location for the legend in `bbox_transform` coordinates (default Axes coordinates). For example, to put the legend's upper right hand corner in the center of the axes the following keywords can be used:: loc='upper right', bbox_to_anchor=(0.5, 0.5)
In [7]:
plt.figure(figsize=(4,3))
plt.scatter(x1, y1, label='x1,y1')
plt.scatter(x2, y2, label='x2,y2')
plt.scatter(x3, y3, label='x3,y3')
plt.scatter(x4, y4, label='x4,y4')
plt.legend(bbox_to_anchor=(1.4,1))
plt.show()
prop¶
prop : None or :class:`matplotlib.font_manager.FontProperties` or dict The font properties of the legend. If None (default), the current :data:`matplotlib.rcParams` will be used.
In [8]:
from matplotlib.font_manager import FontProperties
plt.figure(figsize=(4,3))
plt.scatter(x1, y1, label='x1,y1')
plt.scatter(x2, y2, label='x2,y2')
plt.scatter(x3, y3, label='x3,y3')
plt.scatter(x4, y4, label='x4,y4')
plt.legend(prop=FontProperties(family="cursive"))
plt.show()
fontsize¶
fontsize : int or float or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'} Controls the font size of the legend. If the value is numeric the size will be the absolute font size in points. String values are relative to the current default font size. This argument is only used if `prop` is not specified.
In [9]:
plt.figure(figsize=(4,3))
plt.scatter(x1, y1, label='x1,y1')
plt.scatter(x2, y2, label='x2,y2')
plt.scatter(x3, y3, label='x3,y3')
plt.scatter(x4, y4, label='x4,y4')
plt.legend(fontsize=15)
plt.show()
numpoints¶
numpoints : None or int The number of marker points in the legend when creating a legend entry for a line/:class:`matplotlib.lines.Line2D`. Default is ``None`` which will take the value from the ``legend.numpoints`` :data:`rcParam`.
In [10]:
plt.figure(figsize=(4,3))
plt.scatter(x1, y1, label='x1,y1')
plt.scatter(x2, y2, label='x2,y2')
plt.plot(x3, y3, 'o-', label='x3,y3')
plt.plot(x4, y4, 'o-', label='x4,y4')
plt.legend(numpoints=3)
plt.show()
scatterpoints¶
scatterpoints : None or int The number of marker points in the legend when creating a legend entry for a scatter plot/ :class:`matplotlib.collections.PathCollection`. Default is ``None`` which will take the value from the ``legend.scatterpoints`` :data:`rcParam`.
In [11]:
plt.figure(figsize=(4,3))
plt.scatter(x1, y1, label='x1,y1')
plt.scatter(x2, y2, label='x2,y2')
plt.scatter(x3, y3, label='x3,y3')
plt.scatter(x4, y4, label='x4,y4')
plt.legend(scatterpoints=3)
plt.show()
scatteryoffsets¶
scatteryoffsets : iterable of floats The vertical offset (relative to the font size) for the markers created for a scatter plot legend entry. 0.0 is at the base the legend text, and 1.0 is at the top. To draw all markers at the same height, set to ``[0.5]``. Default ``[0.375, 0.5, 0.3125]``.
In [12]:
plt.figure(figsize=(4,3))
plt.scatter(x1, y1, label='x1,y1')
plt.scatter(x2, y2, label='x2,y2')
plt.scatter(x3, y3, label='x3,y3')
plt.scatter(x4, y4, label='x4,y4')
plt.legend(scatterpoints=2, scatteryoffsets=[0.1, 0.9])
plt.show()
markerscale¶
markerscale : None or int or float The relative size of legend markers compared with the originally drawn ones. Default is ``None`` which will take the value from the ``legend.markerscale`` :data:`rcParam `.
In [13]:
plt.figure(figsize=(4,3))
plt.scatter(x1, y1, label='x1,y1')
plt.scatter(x2, y2, label='x2,y2')
plt.scatter(x3, y3, label='x3,y3')
plt.scatter(x4, y4, label='x4,y4')
plt.legend(markerscale=3)
plt.show()
markerfirst¶
markerfirst : bool If *True*, legend marker is placed to the left of the legend label. If *False*, legend marker is placed to the right of the legend label. Default is *True*.
In [14]:
plt.figure(figsize=(4,3))
plt.scatter(x1, y1, label='x1,y1')
plt.scatter(x2, y2, label='x2,y2')
plt.scatter(x3, y3, label='x3,y3')
plt.scatter(x4, y4, label='x4,y4')
plt.legend(markerfirst=False)
plt.show()
frameon¶
frameon : None or bool Control whether the legend should be drawn on a patch (frame). Default is ``None`` which will take the value from the ``legend.frameon`` :data:`rcParam`.
In [15]:
plt.figure(figsize=(4,3))
plt.scatter(x1, y1, label='x1,y1')
plt.scatter(x2, y2, label='x2,y2')
plt.scatter(x3, y3, label='x3,y3')
plt.scatter(x4, y4, label='x4,y4')
plt.legend(frameon=False)
plt.show()
fancybox¶
fancybox : None or bool Control whether round edges should be enabled around the :class:`~matplotlib.patches.FancyBboxPatch` which makes up the legend's background. Default is ``None`` which will take the value from the ``legend.fancybox`` :data:`rcParam`.
In [16]:
plt.figure(figsize=(4,3))
plt.scatter(x1, y1, label='x1,y1')
plt.scatter(x2, y2, label='x2,y2')
plt.scatter(x3, y3, label='x3,y3')
plt.scatter(x4, y4, label='x4,y4')
plt.legend(fancybox=False)
plt.show()
shadow¶
shadow : None or bool Control whether to draw a shadow behind the legend. Default is ``None`` which will take the value from the ``legend.shadow`` :data:`rcParam`.
In [17]:
plt.figure(figsize=(4,3))
plt.scatter(x1, y1, label='x1,y1')
plt.scatter(x2, y2, label='x2,y2')
plt.scatter(x3, y3, label='x3,y3')
plt.scatter(x4, y4, label='x4,y4')
plt.legend(shadow=True)
plt.show()
framealpha¶
framealpha : None or float Control the alpha transparency of the legend's background. Default is ``None`` which will take the value from the ``legend.framealpha`` :data:`rcParam`. If shadow is activated and framealpha is ``None`` the default value is being ignored.
In [18]:
plt.figure(figsize=(4,3))
plt.scatter(x1, y1, label='x1,y1')
plt.scatter(x2, y2, label='x2,y2')
plt.scatter(x3, y3, label='x3,y3')
plt.scatter(x4, y4, label='x4,y4')
plt.legend(framealpha=0.2)
plt.show()
facecolor¶
facecolor : None or "inherit" or a color spec Control the legend's background color. Default is ``None`` which will take the value from the ``legend.facecolor`` :data:`rcParam`. If ``"inherit"``, it will take the ``axes.facecolor`` :data:`rcParam`.
In [19]:
plt.figure(figsize=(4,3))
plt.scatter(x1, y1, label='x1,y1')
plt.scatter(x2, y2, label='x2,y2')
plt.scatter(x3, y3, label='x3,y3')
plt.scatter(x4, y4, label='x4,y4')
plt.legend(facecolor='cyan')
plt.show()
edgecolor¶
edgecolor : None or "inherit" or a color spec Control the legend's background patch edge color. Default is ``None`` which will take the value from the ``legend.edgecolor`` :data:`rcParam`. If ``"inherit"``, it will take the ``axes.edgecolor`` :data:`rcParam`.
In [20]:
plt.figure(figsize=(4,3))
plt.scatter(x1, y1, label='x1,y1')
plt.scatter(x2, y2, label='x2,y2')
plt.scatter(x3, y3, label='x3,y3')
plt.scatter(x4, y4, label='x4,y4')
plt.legend(edgecolor='red')
plt.show()
mode¶
mode : {"expand", None} If `mode` is set to ``"expand"`` the legend will be horizontally expanded to fill the axes area (or `bbox_to_anchor` if defines the legend's size).
In [21]:
plt.figure(figsize=(4,3))
plt.scatter(x1, y1, label='x1,y1')
plt.scatter(x2, y2, label='x2,y2')
plt.scatter(x3, y3, label='x3,y3')
plt.scatter(x4, y4, label='x4,y4')
plt.legend(mode='expand')
plt.show()
bbox_transform¶
bbox_transform : None or :class:`matplotlib.transforms.Transform` The transform for the bounding box (`bbox_to_anchor`). For a value of ``None`` (default) the Axes' :data:`~matplotlib.axes.Axes.transAxes` transform will be used.
In [22]:
plt.figure(figsize=(4,3))
ax1 = plt.subplot(2,1,1)
ax2 = plt.subplot(2,1,2)
ax1.scatter(x1, y1, label='x1,y1')
ax1.scatter(x2, y2, label='x2,y2')
ax2.scatter(x3, y3, label='x3,y3')
ax2.scatter(x4, y4, label='x4,y4')
ax1.legend(bbox_to_anchor=(1,1),bbox_transform=ax1.transAxes)
ax2.legend(bbox_to_anchor=(1,1),bbox_transform=ax1.transAxes)
plt.show()
plt.figure(figsize=(4,3))
ax1 = plt.subplot(2,1,1)
ax2 = plt.subplot(2,1,2)
ax1.scatter(x1, y1, label='x1,y1')
ax1.scatter(x2, y2, label='x2,y2')
ax2.scatter(x3, y3, label='x3,y3')
ax2.scatter(x4, y4, label='x4,y4')
ax1.legend(bbox_to_anchor=(1,1))
ax2.legend(bbox_to_anchor=(1,1))
plt.show()
title¶
title : str or None The legend's title. Default is no title (``None``).
In [23]:
plt.figure(figsize=(4,3))
plt.plot(x1, y1, label='x1,y1')
plt.plot(x2, y2, label='x2,y2')
plt.plot(x3, y3, label='x3,y3')
plt.plot(x4, y4, label='x4,y4')
plt.legend(title='legend title')
plt.show()
borderpad¶
borderpad : float or None The fractional whitespace inside the legend border. Measured in font-size units. Default is ``None`` which will take the value from the ``legend.borderpad`` :data:`rcParam`.
In [24]:
plt.figure(figsize=(4,3))
plt.plot(x1, y1, label='x1,y1')
plt.plot(x2, y2, label='x2,y2')
plt.plot(x3, y3, label='x3,y3')
plt.plot(x4, y4, label='x4,y4')
plt.legend(borderpad=1.5)
plt.show()
labelspacing¶
labelspacing : float or None The vertical space between the legend entries. Measured in font-size units. Default is ``None`` which will take the value from the ``legend.labelspacing`` :data:`rcParam`.
In [25]:
plt.figure(figsize=(4,3))
plt.plot(x1, y1, label='x1,y1')
plt.plot(x2, y2, label='x2,y2')
plt.plot(x3, y3, label='x3,y3')
plt.plot(x4, y4, label='x4,y4')
plt.legend(labelspacing=1.5)
plt.show()
handlelength¶
handlelength : float or None The length of the legend handles. Measured in font-size units. Default is ``None`` which will take the value from the ``legend.handlelength`` :data:`rcParam`.
In [26]:
plt.figure(figsize=(4,3))
plt.plot(x1, y1, label='x1,y1')
plt.plot(x2, y2, label='x2,y2')
plt.plot(x3, y3, label='x3,y3')
plt.plot(x4, y4, label='x4,y4')
plt.legend(handlelength=5)
plt.show()
handletextpad¶
handletextpad : float or None The pad between the legend handle and text. Measured in font-size units. Default is ``None`` which will take the value from the ``legend.handletextpad`` :data:`rcParam`.
In [27]:
plt.figure(figsize=(4,3))
plt.scatter(x1, y1, label='x1,y1')
plt.scatter(x2, y2, label='x2,y2')
plt.scatter(x3, y3, label='x3,y3')
plt.scatter(x4, y4, label='x4,y4')
plt.legend(handletextpad=-0.5)
plt.show()
borderaxespad¶
borderaxespad : float or None The pad between the axes and legend border. Measured in font-size units. Default is ``None`` which will take the value from the ``legend.borderaxespad`` :data:`rcParam`.
In [28]:
plt.figure(figsize=(4,3))
plt.scatter(x1, y1, label='x1,y1')
plt.scatter(x2, y2, label='x2,y2')
plt.scatter(x3, y3, label='x3,y3')
plt.scatter(x4, y4, label='x4,y4')
plt.legend(borderaxespad=0.0)
plt.show()
columnspacing¶
columnspacing : float or None The spacing between columns. Measured in font-size units. Default is ``None`` which will take the value from the ``legend.columnspacing`` :data:`rcParam`.
In [29]:
plt.figure(figsize=(4,3))
plt.scatter(x1, y1, label='x1,y1')
plt.scatter(x2, y2, label='x2,y2')
plt.scatter(x3, y3, label='x3,y3')
plt.scatter(x4, y4, label='x4,y4')
plt.legend(ncol=2, columnspacing=-2)
plt.show()
handler_map¶
handler_map : dict or None The custom dictionary mapping instances or types to a legend handler. This `handler_map` updates the default handler map found at :func:`matplotlib.legend.Legend.get_legend_handler_map`.
In [30]:
from matplotlib import legend_handler
plt.figure(figsize=(4,3))
s1 = plt.scatter(x1, y1, label='x1,y1')
s2 = plt.scatter(x2, y2, label='x2,y2')
l3, = plt.plot(x3, y3, 'o-', label='x3,y3')
l4, = plt.plot(x4, y4, 'o-', label='x4,y4')
plt.legend(
handler_map={s1: legend_handler.HandlerPathCollection(yoffsets=[ 0.7]),
s2: legend_handler.HandlerPathCollection(yoffsets=[-0.7]),
l3: legend_handler.HandlerLine2D(marker_pad=4, numpoints=2),
l4: legend_handler.HandlerLine2D(marker_pad=3, numpoints=3),
})
plt.show()