legend#
- legend(*args, ax=None, handles=None, labels=None, loc=_Unset.UNSET, bbox_to_anchor=_Unset.UNSET, ncols=_Unset.UNSET, fontsize=_Unset.UNSET, labelcolor=_Unset.UNSET, numpoints=_Unset.UNSET, scatterpoints=_Unset.UNSET, markerscale=_Unset.UNSET, markerfirst=_Unset.UNSET, reverse=_Unset.UNSET, frameon=_Unset.UNSET, fancybox=_Unset.UNSET, framealpha=_Unset.UNSET, facecolor=_Unset.UNSET, edgecolor=_Unset.UNSET, mode=_Unset.UNSET, bbox_transform=_Unset.UNSET, linewidth=_Unset.UNSET, title=_Unset.UNSET, title_fontsize=_Unset.UNSET, alignment=_Unset.UNSET, borderpad=_Unset.UNSET, labelspacing=_Unset.UNSET, handlelength=_Unset.UNSET, handleheight=_Unset.UNSET, borderaxespad=_Unset.UNSET, columnspacing=_Unset.UNSET, zorder=_Unset.UNSET, **kwargs)[source]#
Create a legend on the specified axes with configuration defaults.
- Parameters:
*args (tuple) –
Positional arguments for legend specification:
If 1 arg:
labelsonlyIf 2 args:
handles,labels
Maximum of 2 positional arguments allowed.
ax (matplotlib.axes.Axes | None, optional, default=None) – The axes object on which to place the legend. If
None, usesget_ax(ax)to resolve the current axes.handles (Sequence, optional, default=None) – Artists (lines, patches) to display in legend.
labels (Sequence, optional, default=None) – Text labels corresponding to artists.
loc (str | int | _Unset, optional, default=_UNSET) –
Legend location. If
_UNSET, usesconfig.legend.loc.Accepts standard matplotlib
locstrings/codes (e.g.'upper right','lower left','center',0–10) as well as well as two new positions'top'and'bottom'. These place the legend above and below the axes. token ('left','center','right'), e.g.'bottom left','top center','bottom right'.'top'/'bottom'must be combined with exactly one horizontal position ('left','center','right'), e.g.'bottom left','top center','bottom right'.If
loccontains'bottom'/'top',bbox_to_anchoris computed automatically from the token combination and any explicitly passedbbox_to_anchoris discarded.bbox_to_anchor (tuple | matplotlib.transforms.Bbox | _Unset, optional, default=_UNSET) – Bbox that the legend will be anchored to. If
_UNSET, useslocrelative to the axes.ncols (int | _Unset, optional, default=_UNSET) – Number of columns. If
_UNSET, usesconfig.legend.ncols.fontsize (int | str | _Unset, optional, default=_UNSET) – Fontsize for legend text in points. If
_UNSET, usesconfig.legend.fontsize, resolved viaconfig.fontsizes.resolve('legend')as a scaling factor relative toconfig.fontsizes.size.labelcolor (str | Sequence | _Unset, optional, default=_UNSET) – Text color for legend labels. Accepts a single color, a list of colors, or
'linecolor'/'markerfacecolor'/'markeredgecolor'to match the corresponding artist property.numpoints (int | _Unset, optional, default=_UNSET) – Number of marker points in the legend for
Line2Dentries. If_UNSET, usesconfig.legend.numpoints.scatterpoints (int | _Unset, optional, default=_UNSET) – Number of marker points in the legend for scatter plot entries. If
_UNSET, usesconfig.legend.scatterpoints.markerscale (float | _Unset, optional, default=_UNSET) – Relative size of legend markers compared to plotted markers. If
_UNSET, usesconfig.legend.markerscale.markerfirst (bool | _Unset, optional, default=_UNSET) – If
True, marker is placed to the left of the label. If_UNSET, usesconfig.legend.markerfirst.reverse (bool | _Unset, optional, default=_UNSET) – If
True, reverses the legend entry order. If_UNSET, usesconfig.legend.reverse.frameon (bool | _Unset, optional, default=_UNSET) – Enable legend frame. If
_UNSET, usesconfig.legend.frameon.fancybox (bool | _Unset, optional, default=_UNSET) – Enable rounded box frame. If
_UNSET, usesconfig.legend.fancybox.framealpha (float | _Unset, optional, default=_UNSET) – Frame alpha transparency [0, 1]. If
_UNSET, usesconfig.legend.framealpha.facecolor (str | _Unset, optional, default=_UNSET) – Frame background color. If
_UNSET, usesconfig.legend.facecolor.edgecolor (str | _Unset, optional, default=_UNSET) – Frame edge color. If
_UNSET, usesconfig.legend.edgecolor.mode ({'expand'} | _Unset, optional, default=_UNSET) – If
'expand', horizontally expands legend to fill axes width.bbox_transform (matplotlib.transforms.Transform | _Unset, optional, default=_UNSET) – Transform for
bbox_to_anchor. If_UNSET, usesax.transAxes.linewidth (float | {'spines'} | _Unset, optional, default=_UNSET) – Linewidth of the legend. If
'spines', uses thelinewidthof the spines fromax. If_UNSET, does not set.title (str | _Unset, optional, default=_UNSET) – Legend title. If
_UNSET, usesconfig.legend.title.title_fontsize (int | str | _Unset, optional, default=_UNSET) – Fontsize for legend title text in points. If
_UNSET, usesconfig.fontsizes.resolve('legend_title')as a scaling factor relative toconfig.fontsizes.size.alignment ({'center', 'left', 'right'} | _Unset, optional, default=_UNSET) – Legend alignment. If
_UNSET, usesconfig.legend.alignment.borderpad (float | _Unset, optional, default=_UNSET) – Padding between legend content and frame, in units of fontsize. If
_UNSET, usesconfig.legend.borderpad.labelspacing (float | _Unset, optional, default=_UNSET) – Vertical spacing between legend entries, in units of fontsize. If
_UNSET, usesconfig.legend.labelspacing.handlelength (float | _Unset, optional, default=_UNSET) – Length of legend handles, in units of fontsize. If
_UNSET, uses2.handleheight (float | _Unset, optional, default=_UNSET) – Height of legend handles, in units of fontsize. If
_UNSET, uses0.7.borderaxespad (float | _Unset, optional, default=_UNSET) – Padding between legend and axes, in units of fontsize. If
_UNSET, usesconfig.legend.borderaxespad.columnspacing (float | _Unset, optional, default=_UNSET) – Spacing between columns in units of fontsize. If
_UNSET, usesconfig.legend.columnspacing.zorder (float | _Unset, optional, default=_UNSET) – Legend zorder. If
_UNSET, usesconfig.zorder.legend.
- Returns:
Created matplotlib legend.
- Return type:
Legend
- Raises:
ValueError – If more than 2 positional arguments provided.
Overview#
Thin wrapper around matplotlib.axes.Axes.legend(). Accepts all Matplotlib
arguments and adds two features: extra location keywords and a different default
frame style. Labels are taken from the label keyword of the plotting calls on
ax, exactly as in Matplotlib.
Default Style#
frameon defaults to False. Pass frameon=True to draw the frame. Frame
appearance is controlled by the usual Matplotlib keywords:
edgecolorsets the edge color.fancybox=Truerounds the frame corners.alphasets the frame transparency.
import matplotlib.pyplot as plt
import numpy as np
import visualastro as va
plt.style.use(['full', 'cm'])
rng = np.random.default_rng(42)
bimodal = np.concatenate([
rng.normal(-1.5, 0.6, 30000),
rng.normal(2.0, 1.0, 20000),
])
fig, ax = plt.subplots(figsize=(6,6))
va.hist(
bimodal,
ax=ax,
label='bimodal', color='k',
vlines=[np.median(bimodal), np.mean(bimodal), np.std(bimodal)],
vlines_color=['violetred', 'Holy Blue', 'ibmorg'],
vlines_ls=['solid', 'dotted', 'dashed'],
vlines_lw=1.5,
vlines_labels=['median', 'mean', 'std'],
)
va.legend(ax=ax, loc='upper right')
plt.show()
(Source code, svg)
Frame#
With frameon=True, the frame is drawn with square corners and the edge color
given by edgecolor.
frameon=Trueenables the frame.edgecolor='k'sets a black edge.Corners are square unless
fancybox=Trueor the active style setslegend.fancybox: True.
import matplotlib.pyplot as plt
import numpy as np
import visualastro as va
plt.style.use(['full', 'cm'])
rng = np.random.default_rng(42)
bimodal = np.concatenate([
rng.normal(-1.5, 0.6, 30000),
rng.normal(2.0, 1.0, 20000),
])
lognormal = rng.lognormal(mean=1.0, sigma=0.6, size=5000)
fig, ax = plt.subplots(figsize=(6,6))
va.hist(
[lognormal, bimodal],
ax=ax,
histtype='stepfilled',
ylog=True,
alpha=0.7,
label=['lognorm', 'bimodal'],
color=['r', 'b'],
)
va.legend(ax=ax, frameon=True, ec='k')
plt.show()
(Source code, svg)
New Locations#
'top' and 'bottom' place the legend outside the axes, above or below the
plotting area. Each may be combined with a horizontal keyword:
'top','top left','top center','top right''bottom','bottom left','bottom center','bottom right'
All standard Matplotlib loc values ('upper right', 'best', …) remain valid.
import matplotlib.pyplot as plt
import numpy as np
import visualastro as va
plt.style.use(['full', 'cm'])
rng = np.random.default_rng(42)
nongauss = [
rng.gamma(shape=2.0, scale=2.0, size=2000),
rng.laplace(loc=4.0, scale=2.0, size=2000),
rng.uniform(low=-6.0, high=10.0, size=2000),
rng.standard_t(df=3, size=2500) * 2.0 + 2.0,
-rng.lognormal(mean=1.0, sigma=0.5, size=2600) + 8.0,
rng.weibull(a=1.5, size=2200) * 5.0 - 2.0,
rng.beta(a=0.5, b=0.5, size=2400) * 16.0 - 6.0,
rng.chisquare(df=3, size=2300) * 1.5 - 1.0,
]
fig, ax = plt.subplots(1, 2, figsize=(12,6))
va.hist(
nongauss,
ax=ax[0],
histtype='stepfilled',
color='celestial',
alpha=0.8,
label=[r'$\psi$', r'$\phi$', r'$\lambda$', r'$\epsilon$', r'$\nu$', r'$\rho$', r'$\chi$', r'$\mu$'],
xlim=(-10,20),
)
va.legend(
ax=ax[0], frameon=True, ec='k', reverse=True, ncols=4,
markerfirst=False, fancybox=True, loc='bottom center'
)
x = np.arange(500)
y1, y2, y3 = np.cumsum(rng.normal(size=(3, x.size)), axis=1)
va.step(x, y1, color='stratosphere blue', label=r'$A$')
va.step(x, y2, color='soup of the day', label=r'$B$')
va.step(x, y3, color='aurora green', label=r'$C$')
va.legend(loc='top center', ncols=3, borderaxespad=-1, frameon=True, ec='k')
plt.show()
(Source code, svg)
Setting the Line Width#
You can also set the linewidth of the legend box directly.
import matplotlib.pyplot as plt
import numpy as np
import visualastro as va
plt.style.use(['full', 'cm'])
rng = np.random.default_rng(42)
bimodal = np.concatenate([
rng.normal(-1.5, 0.6, 30000),
rng.normal(2.0, 1.0, 20000),
])
lognormal = rng.lognormal(mean=1.0, sigma=0.6, size=5000)
normals = [
rng.normal(0, 10, 2000),
rng.normal(3.5, 6, 2000),
rng.normal(3.5, 4, 2000),
rng.normal(0, 5, 2500),
rng.normal(-3, 8, 2600),
]
fig, ax = plt.subplots(figsize=(6,6))
va.hist(
normals,
ax=ax,
histtype='barstacked',
color='evenaworm',
labels = [
r'$\mathcal{N}(\mu=0,\ \sigma=10)$',
r'$\mathcal{N}(\mu=3.5,\ \sigma=6)$',
r'$\mathcal{N}(\mu=3.5,\ \sigma=4)$',
r'$\mathcal{N}(\mu=0,\ \sigma=5)$',
r'$\mathcal{N}(\mu=-3,\ \sigma=8)$',
],
xlim=(-45, 45),
)
va.legend(ax=ax, loc='upper left', ncols=1, linewidth=1.3, ec='k', frameon=True)
plt.show()
(Source code, svg)
See Also#
hist()step()