Matplotlib--legend函数

Matplotlib–legend函数

写在课前:

  1. 产生空白画布
import matplotlib.pyplot as plt

fig = plt.figure()

plt.show()

函数功能:
Place a legend on the axes.
在坐标系中放置图例

函数语法:

有三种使用legend()函数的形式:

  1. legend()
    Automatic detection of elements to be shown in the legend
    The elements to be added to the legend are automatically determined, when you do not pass in any extra arguments.
    In this case, the labels are taken from the artist. You can specify them either at artist creation or by calling the set_label() method on the artist:
    自动检测图例中显示的元素。若不传入任何其他参数,添加到图例中的元素将自主决定。在这种情况下,标签从artist中获取。可以通过artist创建或者通过调用set_label()方法设定标签
import matplotlib.pyplot as plt
import numpy as np

x = [1,2,3,4,5]
y = np.power(x,2)

plt.scatter(x,y,label='figure-scatter')
plt.legend()

plt.show()

Matplotlib--legend函数_第1张图片

  1. legend(labels)
    Labeling existing plot elements
    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
    Note: This way of using is discouraged, because the relation between plot elements and labels is only implicit by their order and can easily be mixed up
    标记现有图元素
    为轴上已经存在的线制作图例(例如,通过绘图),只需使用可迭代的字符串调用此函数,每个图例项一个
    注意:这种使用方法不推荐,因为图形元素和标签之间的关系仅按其顺序隐含,很容易混淆。

legend()中的标签需要加中括号,否则只显示第一个字母(原因不清楚)

import matplotlib.pyplot as plt
import numpy as np

x = [1,2,3,4,5]
y = np.power(x,2)

plt.scatter(x,y)
plt.legend(['figure-scatter'])

plt.show()

Matplotlib--legend函数_第2张图片

  1. legend(handles, labels)
    Explicitly defining the elements in the legend
    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。

明确定义图例中的元素,传入一一对应的artists与标签

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2.1,0.1)
y1 = np.power(x,3)
y2 = np.power(x,2)
y3 = np.power(x,1)


# 此处的line后面必须加,才能正常输出图例内容,否则显示空白图例框(不明白原因)
line1, = plt.plot(x,y1,ls=':')
line2, = plt.plot(x,y2,ls='--')
line3, = plt.plot(x,y3,ls='-')

plt.legend([line1,line2,line3],['y=x^3','y=x^2','y=x'],loc='upper left')

plt.show()

Matplotlib--legend函数_第3张图片
handles: sequence of Artist, optional
A list of Artists (lines, patches) to be added to the legend. Use this together with labels, if you need full control on what is shown in the legend and the automatic mechanism described above is not sufficient.
The length of handles and labels should be the same in this case. If they are not, they are truncated to the smaller length.
图例句柄: 可选参数,Artist列表
添加到图例中的Artist列表。和labels标签一起使用,可完全控制图例中显示的内容。handles参数的长度与labels参数的长度应该一致,若不一致则以较小的长度为准。

labels: list of str, optional
A list of labels to show next to the artists. Use this together with handles, if you need full control on what is shown in the legend and the automatic mechanism described above is not sufficient.

标签:可选参数,字符串列表
标签列表,与handles参数一起使用,可完全控制图例中显示的内容。

handles参数与labels参数联合使用,可完全控制图例中显示的内容。

loc: str or pair of floats, default: rcParams[“legend.loc”] (default: ‘best’) (‘best’ for axes, ‘upper right’ for figures)
The location of the legend.
位置:字符串或者浮点数,默认位置:best;图例的位置

  1. The strings ‘upper left’, ‘upper right’, ‘lower left’, ‘lower right’ place the legend at the corresponding corner of the axes/figure.

  2. The strings ‘upper center’, ‘lower center’, ‘center left’, ‘center right’ place the legend at the center of the corresponding edge of the axes/figure.

  3. The string ‘center’ places the legend at the center of the axes/figure.

  4. The string ‘best’ places the legend at the location, among the nine locations defined so far, with the minimum overlap with other drawn artists. This option can be quite slow for plots with large amounts of data; your plotting speed may benefit from providing a specific location.

  5. The location can also be a 2-tuple giving the coordinates of the lower-left corner of the legend in axes coordinates (in which case bbox_to_anchor will be ignored).

  6. For back-compatibility, ‘center right’ (but no other location) can also be spelled ‘right’, and each “string” locations can also be given as a numeric value:

对应参数解释:

  1. 参数*‘upper left’, ‘upper right’, ‘lower left’, ‘lower right’* 将图例放在坐标系或者图像的对应角。
  2. 参数*‘upper center’, ‘lower center’, ‘center left’, ‘center right’* 将图例放在坐标系或者图像对应边的中心位置
  3. 参数*‘center’* 将图例放在坐标系或者图像的中间位置
  4. 参数 ‘best’ 放置 图例在*‘upper left’, ‘upper right’, ‘lower left’, ‘lower right’ ,‘upper center’, ‘lower center’, ‘center left’, ‘center right’, ‘center’* 9个位置中的1个,使图例与其他部分的重合交叠最少。对于具有大量数据的绘图,此选项可能会非常慢。 提供特定的位置可能会提高您的绘图速度。
  5. 位置也可以是一个二元数组,二元数组的位置决定图例左下角的位置,以比例显示(x/y轴长度的比例)(这种情况下参数bbox_to_anchor会被忽略)
  6. 为了实现向后兼容,“中右”(但没有其他位置)也可以拼写为“右”,并且每个“字符串”位置也可以以数值形式给出

图例的位置为第5种情况的二元数组,数组loc=(0,25,0.5),则图例左下角放置在横轴 0.25 ∗ 2 = 0.5 0.25*2=0.5 0.252=0.5,纵轴 0.5 ∗ 8 = 4 0.5*8=4 0.58=4 ( 0.5 , 4 ) (0.5,4) 0.54的位置。

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 中心
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2.1,0.1)
y1 = np.power(x,3)
y2 = np.power(x,2)
y3 = np.power(x,1)

plt.plot(x,y1,ls=':',label='$x^{3}$')
plt.plot(x,y2,ls='--',label='$x^{2}$')
plt.plot(x,y3,ls='-',label='$x^{1}$')

plt.xlim(0,2)
plt.ylim(0,8)
plt.legend(loc=(0.25,0.5))


plt.show()

Matplotlib--legend函数_第4张图片

bbox_to_anchor: BboxBase, 2-tuple, or 4-tuple of floats
Box that is used to position the legend in conjunction with loc. Defaults to axes.bbox (if called as a method to Axes.legend) or figure.bbox (if Figure.legend). This argument allows arbitrary placement of the legend.
图例线框位置:二元或者四元的浮点型数组。用于放置图例的框,使用此参数可以将图例放置在想要的任意位置。
If a 4-tuple or BboxBase is given, then it specifies the bbox (x, y, width, height) that the legend is placed in. To put the legend in the best location in the bottom right quadrant of the axes (or figure):
若给定4元数组参数则为给出图例放置的位置(x,y)与图例框的大小(width, height)。
(四个元素的不理解)

bbox_to_anchorloc参数同时使用,如:

loc=‘center’, bbox_to_anchor=(0.5,0.5),表示图例的中心位置在坐标系的中间位置,即图例的中心在 2 ∗ 0.5 = 1 , 8 ∗ 0.5 = 4 ; ( 1 , 4 ) 2*0.5=1,8*0.5=4;(1,4) 20.5=1,80.5=4;(1,4)的位置

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2.1,0.1)
y1 = np.power(x,3)
y2 = np.power(x,2)
y3 = np.power(x,1)

plt.plot(x,y1,ls=':',label='$x^{3}$')
plt.plot(x,y2,ls='--',label='$x^{2}$')
plt.plot(x,y3,ls='-',label='$x^{1}$')

plt.xlim(0,2)
plt.ylim(0,8)
plt.legend(loc='center',bbox_to_anchor=(0.5,0.5))
plt.grid()

plt.show()

Matplotlib--legend函数_第5张图片

loc=‘upper left’,bbox_to_anchor=(0.5,0.5) 表示图例的左上位置在坐标系 2 ∗ 0.5 = 1 , 8 ∗ 0.5 = 4 ; 即 ( 1 , 4 ) 2*0.5=1,8*0.5=4;即(1,4) 20.5=1,80.5=4;(1,4)的位置

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2.1,0.1)
y1 = np.power(x,3)
y2 = np.power(x,2)
y3 = np.power(x,1)

plt.plot(x,y1,ls=':',label='$x^{3}$')
plt.plot(x,y2,ls='--',label='$x^{2}$')
plt.plot(x,y3,ls='-',label='$x^{1}$')

plt.xlim(0,2)
plt.ylim(0,8)
plt.legend(loc='upper left',bbox_to_anchor=(0.5,0.5))
plt.grid()

plt.show()

Matplotlib--legend函数_第6张图片
ncol: int, default: 1
The number of columns that the legend has.
列数:整数,默认:1列
图例内容展示的列数

图列展示为2列:ncol=2

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2.1,0.1)
y1 = np.power(x,3)
y2 = np.power(x,2)
y3 = np.power(x,1)

plt.plot(x,y1,ls=':',label='$x^{3}$')
plt.plot(x,y2,ls='--',label='$x^{2}$')
plt.plot(x,y3,ls='-',label='$x^{1}$')

plt.xlim(0,2)
plt.ylim(0,8)
plt.legend(loc='upper left',bbox_to_anchor=(0.05,0.95),ncol=2)
plt.grid()

plt.show()

Matplotlib--legend函数_第7张图片
prop: None or matplotlib.font_manager.FontProperties or dict
The font properties of the legend. If None (default), the current matplotlib.rcParams will be used.
图例的字体属性,None或者字典项
若为None,则使用当前matplotlib.rcParams 环境配置字体

matplotlib.rcParams 环境默认配置字体
font={‘family’ : ‘monospace’,
‘weight’ : ‘bold’,
‘size’ : ‘larger’}


import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2.1,0.1)
y1 = np.power(x,3)
y2 = np.power(x,2)
y3 = np.power(x,1)

plt.plot(x, y1, ls='--', lw=1, label='$x^3$')
plt.plot(x, y2, ls='-.', lw=2, label='$x^2$')
plt.plot(x, y3, ls=':', lw=3, label='$x^1$')

plt.xlim(0,2)
plt.ylim(0,8)
plt.grid(ls=':',color='r')
plt.legend(loc='upper left',ncol=1,
           bbox_to_anchor=(0.05, 0.95),
           shadow=True,
           prop={'family' : 'monospace',
        'weight' : 'bold',
        'size'   : 'larger'})
plt.show()

Matplotlib--legend函数_第8张图片
fontsize: int or {‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’}
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.
字体大小:整数或者取值于{‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’}
图例的字体大小,如果该值为数字,则大小将是以磅为单位的绝对字体大小。字符串值是相对于当前默认字体大小的。仅当未指定prop时才使用此参数。


import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2.1,0.1)
y1 = np.power(x,3)
y2 = np.power(x,2)
y3 = np.power(x,1)

plt.plot(x, y1, ls='--', lw=1, label='$x^3$')
plt.plot(x, y2, ls='-.', lw=2, label='$x^2$')
plt.plot(x, y3, ls=':', lw=3, label='$x^1$')

plt.xlim(0,2)
plt.ylim(0,8)
plt.grid(ls=':',color='r')
plt.legend(loc='upper left',ncol=1,
           bbox_to_anchor=(0.05, 0.95),
           shadow=True,
           fontsize=30)
plt.show()

Matplotlib--legend函数_第9张图片
labelcolor: str or list
Sets the color of the text in the legend. Can be a valid color string (for example, ‘red’), or a list of color strings. The labelcolor can also be made to match the color of the line or marker using ‘linecolor’, ‘markerfacecolor’ (or ‘mfc’), or ‘markeredgecolor’ (or ‘mec’).
标签颜色:字符串或者列表
设置图例中的文本颜色。可以是单个字符串(如:‘red’),或者颜色列表。也可以使用 ‘linecolor’ 或’markerfacecolor’ (or ‘mfc’), 或 ‘markeredgecolor’ (or ‘mec’)去匹配线或者标记颜色

  1. 图例中的文本颜色为单个字符串颜色

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2.1,0.1)
y1 = np.power(x,3)
y2 = np.power(x,2)
y3 = np.power(x,1)

plt.plot(x, y1, ls='--', lw=1, label='$x^3$')
plt.plot(x, y2, ls='-.', lw=2, label='$x^2$')
plt.plot(x, y3, ls=':', lw=3, label='$x^1$')

plt.xlim(0,2)
plt.ylim(0,8)
plt.grid(ls=':',color='r')
plt.legend(loc='upper left',ncol=1,
           bbox_to_anchor=(0.05, 0.95),
           shadow=True,
           fontsize=8,
           labelcolor='r')
plt.show()

Matplotlib--legend函数_第10张图片

  1. 图例中的文本颜色为列表

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2.1,0.1)
y1 = np.power(x,3)
y2 = np.power(x,2)
y3 = np.power(x,1)

plt.plot(x, y1, ls='--', lw=1, label='$x^3$')
plt.plot(x, y2, ls='-.', lw=2, label='$x^2$')
plt.plot(x, y3, ls=':', lw=3, label='$x^1$')

plt.xlim(0,2)
plt.ylim(0,8)
plt.grid(ls=':',color='r')
plt.legend(loc='upper left',ncol=1,
           bbox_to_anchor=(0.05, 0.95),
           shadow=True,
           fontsize=8,
           labelcolor=['r','y','c'])
plt.show()

Matplotlib--legend函数_第11张图片
3.图例文本颜色与线条颜色匹配


import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2.1,0.1)
y1 = np.power(x,3)
y2 = np.power(x,2)
y3 = np.power(x,1)

plt.plot(x, y1, ls='--', lw=1, label='$x^3$')
plt.plot(x, y2, ls='-.', lw=2, label='$x^2$')
plt.plot(x, y3, ls=':', lw=3, label='$x^1$')

plt.xlim(0,2)
plt.ylim(0,8)
plt.grid(ls=':',color='r')
plt.legend(loc='upper left',ncol=1,
           bbox_to_anchor=(0.05, 0.95),
           shadow=True,
           fontsize=8,
           labelcolor='linecolor')
plt.show()

Matplotlib--legend函数_第12张图片
numpoints: int, default: rcParams[“legend.numpoints”] (default: 1)
The number of marker points in the legend when creating a legend entry for a Line2D (line).
图例条目中标记点的数量(不理解),针对折线图

scatterpoints: int, default: rcParams[“legend.scatterpoints”] (default: 1)
The number of marker points in the legend when creating a legend entry for a PathCollection (scatter plot).

图例中散点数量:图例条目中标记点的数量,针对散点图

图例中散点标记数量为3:scatterpoints=3


import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2.1,0.1)
y1 = np.power(x,3)
y2 = np.power(x,2)
y3 = np.power(x,1)

plt.scatter(x, y1, label='$x^3$')
plt.scatter(x, y2,  label='$x^2$')
plt.scatter(x, y3, label='$x^1$')

plt.xlim(0,2)
plt.ylim(0,8)
plt.grid(ls=':',color='r')
plt.legend(loc='upper left',ncol=1,
           bbox_to_anchor=(0.05, 0.95),
           shadow=True,scatterpoints=3)
plt.show()

Matplotlib--legend函数_第13张图片
图例中散点标记数量为1:scatterpoints=1


import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2.1,0.1)
y1 = np.power(x,3)
y2 = np.power(x,2)
y3 = np.power(x,1)

plt.scatter(x, y1, label='$x^3$')
plt.scatter(x, y2,  label='$x^2$')
plt.scatter(x, y3, label='$x^1$')

plt.xlim(0,2)
plt.ylim(0,8)
plt.grid(ls=':',color='r')
plt.legend(loc='upper left',ncol=1,
           bbox_to_anchor=(0.05, 0.95),
           shadow=True,scatterpoints=1)
plt.show()

Matplotlib--legend函数_第14张图片

scatteryoffsets: iterable of floats, default: [0.375, 0.5, 0.3125]
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].
浮点数的迭代,默认: [0.375, 0.5, 0.3125]。为散点图图例条目创建的标记的垂直偏移量(相对于字体大小)。0.0在图例文本的底部,而1.0在顶部。要以相同的高度绘制所有标记,请将其设置为[0.5]。(不理解为什么有三个变量值)

markerscale: float, default: rcParams[“legend.markerscale”] (default: 1.0)
The relative size of legend markers compared with the originally drawn ones.
标记大小:浮点型,默认大小为1,图例标记的与原始绘制标记的相对大小
实践表明该参数对于散点图起作用,作于折线图则无作用
原始大小:


import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2.1,0.1)
y1 = np.power(x,3)
y2 = np.power(x,2)
y3 = np.power(x,1)

plt.scatter(x, y1, label='$x^3$')
plt.scatter(x, y2,  label='$x^2$')
plt.scatter(x, y3, label='$x^1$')

plt.xlim(0,2)
plt.ylim(0,8)
plt.grid(ls=':',color='r')
plt.legend(loc='upper left',ncol=1,
           bbox_to_anchor=(0.05, 0.95),
           shadow=True,
           fontsize=8)
plt.show()

Matplotlib--legend函数_第15张图片

标记相对大小为2:markerscale=2


import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2.1,0.1)
y1 = np.power(x,3)
y2 = np.power(x,2)
y3 = np.power(x,1)

plt.scatter(x, y1, label='$x^3$')
plt.scatter(x, y2,  label='$x^2$')
plt.scatter(x, y3, label='$x^1$')

plt.xlim(0,2)
plt.ylim(0,8)
plt.grid(ls=':',color='r')
plt.legend(loc='upper left',ncol=1,
           bbox_to_anchor=(0.05, 0.95),
           shadow=True,
           fontsize=8,
           markerscale=2)
plt.show()

Matplotlib--legend函数_第16张图片
markerfirst: bool, default: True
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.
标记在前:布尔型,默认值为True。当为True时,图例标记放在图例标签的左边,否则放在右边,标签文本在前

标签文本在前,标记在后,markerfirst=False


import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2.1,0.1)
y1 = np.power(x,3)
y2 = np.power(x,2)
y3 = np.power(x,1)

plt.scatter(x, y1, label='$x^3$')
plt.scatter(x, y2,  label='$x^2$')
plt.scatter(x, y3, label='$x^1$')

plt.xlim(0,2)
plt.ylim(0,8)
plt.grid(ls=':',color='r')
plt.legend(loc='upper left',ncol=1,
           bbox_to_anchor=(0.05, 0.95),
           shadow=True,fontsize=8,
           markerfirst=False)
plt.show()

Matplotlib--legend函数_第17张图片
frameon: bool, default: rcParams[“legend.frameon”] (default: True)
Whether the legend should be drawn on a patch (frame).
图例框:图例是否绘制在框上,布尔型,默认:有框。

无图例框,frameon=False


import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2.1,0.1)
y1 = np.power(x,3)
y2 = np.power(x,2)
y3 = np.power(x,1)

plt.scatter(x, y1, label='$x^3$')
plt.scatter(x, y2,  label='$x^2$')
plt.scatter(x, y3, label='$x^1$')

plt.xlim(0,2)
plt.ylim(0,8)
plt.grid(ls=':',color='r')
plt.legend(loc='upper left',ncol=1,
           bbox_to_anchor=(0.05, 0.95),
           shadow=True,fontsize=8,
           markerfirst=False,frameon=False)
plt.show()

Matplotlib--legend函数_第18张图片
fancybox: bool, default: rcParams[“legend.fancybox”] (default: True)
Whether round edges should be enabled around the FancyBboxPatch which makes up the legend’s background.
是否圆角框:布尔型,默认:圆角框(True),是否启用圆角边缘。默认采用圆角框。该参数需要在参数frameon=True时才能显示效果,否则没有边框无从定义直角与圆角边框。

fancybox=False,采用直角框


import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2.1,0.1)
y1 = np.power(x,3)
y2 = np.power(x,2)
y3 = np.power(x,1)

plt.scatter(x, y1, label='$x^3$')
plt.scatter(x, y2,  label='$x^2$')
plt.scatter(x, y3, label='$x^1$')

plt.xlim(0,2)
plt.ylim(0,8)
plt.grid(ls=':',color='r')
plt.legend(loc='upper left',ncol=1,
           bbox_to_anchor=(0.05, 0.95),
           shadow=True,fontsize=8,
           markerfirst=False,frameon=True,
           fancybox=False)
plt.show()

Matplotlib--legend函数_第19张图片
shadow: bool, default: rcParams[“legend.shadow”] (default: False)
Whether to draw a shadow behind the legend.

图例阴影:布尔型,默认:无阴影,决定是否绘制图例的阴影,实践表明该参数必须在参数frameon=True时才能显示效果。
当 frameon=False,shadow=True无效果展示


import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2.1,0.1)
y1 = np.power(x,3)
y2 = np.power(x,2)
y3 = np.power(x,1)

plt.scatter(x, y1, label='$x^3$')
plt.scatter(x, y2,  label='$x^2$')
plt.scatter(x, y3, label='$x^1$')

plt.xlim(0,2)
plt.ylim(0,8)
plt.grid(ls=':',color='r')
plt.legend(loc='upper left',ncol=1,
           bbox_to_anchor=(0.05, 0.95),
           shadow=True,fontsize=8,
           markerfirst=False,frameon=False)
plt.show()

Matplotlib--legend函数_第20张图片
当 frameon=True,shadow=True阴影效果展示


import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2.1,0.1)
y1 = np.power(x,3)
y2 = np.power(x,2)
y3 = np.power(x,1)

plt.scatter(x, y1, label='$x^3$')
plt.scatter(x, y2,  label='$x^2$')
plt.scatter(x, y3, label='$x^1$')

plt.xlim(0,2)
plt.ylim(0,8)
plt.grid(ls=':',color='r')
plt.legend(loc='upper left',ncol=1,
           bbox_to_anchor=(0.05, 0.95),
           shadow=True,fontsize=8,
           markerfirst=False,frameon=True)
plt.show()

Matplotlib--legend函数_第21张图片

framealpha: float, default: rcParams[“legend.framealpha”] (default: 0.8)
The alpha transparency of the legend’s background. If shadow is activated and framealpha is None, the default value is ignored.
图例透明度: 浮点型,默认值:0.8,图例背景的透明度,若如果激活了阴影并且framealpha为None,则默认值将被忽略。(实践表明默认的透明度更像是1而不是0.8)

framealpha=0.8 的图形


import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2.1,0.1)
y1 = np.power(x,3)
y2 = np.power(x,2)
y3 = np.power(x,1)

plt.plot(x, y1, ls='-', label='$x^3$')
plt.plot(x, y2, ls='-.', label='$x^2$')
plt.plot(x, y3, ls=':',label='$x^1$')

plt.xlim(0,2)
plt.ylim(0,8)
plt.grid(ls=':',color='r')
plt.legend(loc='upper left',ncol=1,
           bbox_to_anchor=(0.05, 0.95),
           shadow=True,
          framealpha=0.8)
plt.show()

Matplotlib--legend函数_第22张图片
framealpha=None 的图形


import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2.1,0.1)
y1 = np.power(x,3)
y2 = np.power(x,2)
y3 = np.power(x,1)

plt.plot(x, y1, ls='-', label='$x^3$')
plt.plot(x, y2, ls='-.', label='$x^2$')
plt.plot(x, y3, ls=':',label='$x^1$')

plt.xlim(0,2)
plt.ylim(0,8)
plt.grid(ls=':',color='r')
plt.legend(loc='upper left',ncol=1,
           bbox_to_anchor=(0.05, 0.95),
           shadow=True,
          framealpha=None)
plt.show()

Matplotlib--legend函数_第23张图片
默认透明度图形


import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2.1,0.1)
y1 = np.power(x,3)
y2 = np.power(x,2)
y3 = np.power(x,1)

plt.plot(x, y1, ls='-', label='$x^3$')
plt.plot(x, y2, ls='-.', label='$x^2$')
plt.plot(x, y3, ls=':',label='$x^1$')

plt.xlim(0,2)
plt.ylim(0,8)
plt.grid(ls=':',color='r')
plt.legend(loc='upper left',ncol=1,
           bbox_to_anchor=(0.05, 0.95),
           shadow=True)
plt.show()

Matplotlib--legend函数_第24张图片
透明度framealpha=1的图形


import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2.1,0.1)
y1 = np.power(x,3)
y2 = np.power(x,2)
y3 = np.power(x,1)

plt.plot(x, y1, ls='-', label='$x^3$')
plt.plot(x, y2, ls='-.', label='$x^2$')
plt.plot(x, y3, ls=':',label='$x^1$')

plt.xlim(0,2)
plt.ylim(0,8)
plt.grid(ls=':',color='r')
plt.legend(loc='upper left',ncol=1,
           bbox_to_anchor=(0.05, 0.95),
           shadow=True,
           framealpha=1)
plt.show()

Matplotlib--legend函数_第25张图片
facecolor: “inherit” or color, default: rcParams[“legend.facecolor”] (default: ‘inherit’)
The legend’s background color. If “inherit”, use rcParams[“axes.facecolor”] (default: ‘white’).
填充颜色:图例的背景颜色,若为"inherit",使用默认颜色:白色


import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2.1,0.1)
y1 = np.power(x,3)
y2 = np.power(x,2)
y3 = np.power(x,1)

plt.plot(x, y1, ls='-', label='$x^3$')
plt.plot(x, y2, ls='-.', label='$x^2$')
plt.plot(x, y3, ls=':',label='$x^1$')

plt.xlim(0,2)
plt.ylim(0,8)
plt.grid(ls=':',color='r')
plt.legend(loc='upper left',ncol=1,
           bbox_to_anchor=(0.05, 0.95),
           shadow=True,framealpha=0.8,
           facecolor='cyan')
plt.show()

Matplotlib--legend函数_第26张图片
edgecolor: “inherit” or color, default: rcParams[“legend.edgecolor”] (default: ‘0.8’)
The legend’s background patch edge color. If “inherit”, use take rcParams[“axes.edgecolor”] (default: ‘black’).
图例边界颜色:默认:黑色

修改图例边界边框为红色:edgecolor=‘r’


import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2.1,0.1)
y1 = np.power(x,3)
y2 = np.power(x,2)
y3 = np.power(x,1)

plt.plot(x, y1, ls='-', label='$x^3$')
plt.plot(x, y2, ls='-.', label='$x^2$')
plt.plot(x, y3, ls=':',label='$x^1$')

plt.xlim(0,2)
plt.ylim(0,8)
plt.grid(ls=':',color='r')
plt.legend(loc='upper left',ncol=1,
           bbox_to_anchor=(0.05, 0.95),
           shadow=True,framealpha=0.8,
           facecolor='cyan',edgecolor='r')
plt.show()

Matplotlib--legend函数_第27张图片
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).
模式:若模式设置为**“expand”****(不理解)**


import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2.1,0.1)
y1 = np.power(x,3)
y2 = np.power(x,2)
y3 = np.power(x,1)

plt.plot(x, y1, ls='-', label='$x^3$')
plt.plot(x, y2, ls='-.', label='$x^2$')
plt.plot(x, y3, ls=':',label='$x^1$')

plt.xlim(0,2)
plt.ylim(0,8)
plt.grid(ls=':',color='r')
plt.legend(loc='upper left',ncol=1,
           bbox_to_anchor=(0.05, 0.95),
           shadow=True,framealpha=0.8,
           facecolor='cyan',edgecolor='r',
           mode='expand')
plt.show()

Matplotlib--legend函数_第28张图片
bbox_transform: None or matplotlib.transforms.Transform
The transform for the bounding box (bbox_to_anchor). For a value of None (default) the Axes’ transAxes transform will be used.(不理解)

title: str or None
The legend’s title. Default is no title (None).
图例的标题:字符串或者None,默认无标题

title_fontsize: int or {‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’}, default: rcParams[“legend.title_fontsize”] (default: None)
The font size of the legend’s title.
图例标题字体大小: 整数或者取值于{‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’},默认:无(因为默认无标题)

设置图例标题字体大小为8: title_fontsize=8


import matplotlib.pyplot as plt
import numpy as np
import matplotlib
x = np.arange(0,2.1,0.1)
y1 = np.power(x,3)
y2 = np.power(x,2)
y3 = np.power(x,1)

plt.plot(x, y1, ls='-', label='$x^3$')
plt.plot(x, y2, ls='-.', label='$x^2$')
plt.plot(x, y3, ls=':',label='$x^1$')

plt.xlim(0,2)
plt.ylim(0,8)
plt.grid(ls=':',color='r')
plt.legend(loc='upper left',ncol=1,
           bbox_to_anchor=(0.05, 0.95),
           shadow=True,title='power function',
           title_fontsize=8)
plt.show()

Matplotlib--legend函数_第29张图片
borderpad: float, default: rcParams[“legend.borderpad”] (default: 0.4)
The fractional whitespace inside the legend border, in font-size units.
图例边框内边距: 浮点型,默认值:0.4,图例边框内的空格,以字体大小为单位
数值越大,文本内容与边界框之间的距离越大。

borderpad=2


import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2.1,0.1)
y1 = np.power(x,3)
y2 = np.power(x,2)
y3 = np.power(x,1)

plt.scatter(x, y1, label='$x^3$')
plt.scatter(x, y2,  label='$x^2$')
plt.scatter(x, y3, label='$x^1$')

plt.xlim(0,2)
plt.ylim(0,8)
plt.grid(ls=':',color='r')
plt.legend(loc='upper left',ncol=1,
           bbox_to_anchor=(0.05, 0.95),
           shadow=True,borderpad=2)
plt.show()

Matplotlib--legend函数_第30张图片
labelspacing: float, default: rcParams[“legend.labelspacing”] (default: 0.5)
The vertical space between the legend entries, in font-size units.
图例条目间间距: 浮点型,默认值:0.5,图例条目之间的垂直距离,以字体大小为单位
labelspacing越大,图例条目之间的垂直距离越大


import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2.1,0.1)
y1 = np.power(x,3)
y2 = np.power(x,2)
y3 = np.power(x,1)

plt.scatter(x, y1, label='$x^3$')
plt.scatter(x, y2,  label='$x^2$')
plt.scatter(x, y3, label='$x^1$')

plt.xlim(0,2)
plt.ylim(0,8)
plt.grid(ls=':',color='r')
plt.legend(loc='upper left',ncol=1,
           bbox_to_anchor=(0.05, 0.95),
           shadow=True,borderpad=2,
           labelspacing=2)
plt.show()

Matplotlib--legend函数_第31张图片
handlelength: float, default: rcParams[“legend.handlelength”] (default: 2.0)
The length of the legend handles, in font-size units.
图例句柄的长度: 浮点型,默认值:2,图例句柄的长度,以字体大小为单位

图例句柄的长度为3: handlelength=3


import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2.1,0.1)
y1 = np.power(x,3)
y2 = np.power(x,2)
y3 = np.power(x,1)

plt.plot(x, y1,ls='-', label='$x^3$')
plt.plot(x, y2, ls='-.', label='$x^2$')
plt.plot(x, y3, ls=':',label='$x^1$')

plt.xlim(0,2)
plt.ylim(0,8)
plt.grid(ls=':',color='r')
plt.legend(loc='upper left',ncol=1,
           bbox_to_anchor=(0.05, 0.95),
           shadow=True,borderpad=2,
           labelspacing=1,handlelength=3)
plt.show()

Matplotlib--legend函数_第32张图片
图例句柄的长度为1: handlelength=1


import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2.1,0.1)
y1 = np.power(x,3)
y2 = np.power(x,2)
y3 = np.power(x,1)

plt.plot(x, y1,ls='-', label='$x^3$')
plt.plot(x, y2, ls='-.', label='$x^2$')
plt.plot(x, y3, ls=':',label='$x^1$')

plt.xlim(0,2)
plt.ylim(0,8)
plt.grid(ls=':',color='r')
plt.legend(loc='upper left',ncol=1,
           bbox_to_anchor=(0.05, 0.95),
           shadow=True,borderpad=2,
           labelspacing=1,handlelength=1)
plt.show()

Matplotlib--legend函数_第33张图片
handletextpad: float, default: rcParams[“legend.handletextpad”] (default: 0.8)
The pad between the legend handle and text, in font-size units.
图例句柄与文本之间的间距: 浮点型,默认值:0.8,以字体大小为单位

图例句柄与文本之间的间距为2: handletextpad=2


import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2.1,0.1)
y1 = np.power(x,3)
y2 = np.power(x,2)
y3 = np.power(x,1)

plt.plot(x, y1,ls='-', label='$x^3$')
plt.plot(x, y2, ls='-.', label='$x^2$')
plt.plot(x, y3, ls=':',label='$x^1$')

plt.xlim(0,2)
plt.ylim(0,8)
plt.grid(ls=':',color='r')
plt.legend(loc='upper left',ncol=1,
           bbox_to_anchor=(0.05, 0.95),
           shadow=True,borderpad=2,
           labelspacing=1,handlelength=1,
           handletextpad=2)
plt.show()

Matplotlib--legend函数_第34张图片
图例句柄与文本之间的间距为1: handletextpad=1


import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2.1,0.1)
y1 = np.power(x,3)
y2 = np.power(x,2)
y3 = np.power(x,1)

plt.plot(x, y1,ls='-', label='$x^3$')
plt.plot(x, y2, ls='-.', label='$x^2$')
plt.plot(x, y3, ls=':',label='$x^1$')

plt.xlim(0,2)
plt.ylim(0,8)
plt.grid(ls=':',color='r')
plt.legend(loc='upper left',ncol=1,
           bbox_to_anchor=(0.05, 0.95),
           shadow=True,borderpad=2,
           labelspacing=1,handlelength=1,
           handletextpad=0)
plt.show()

Matplotlib--legend函数_第35张图片
borderaxespad: float, default: rcParams[“legend.borderaxespad”] (default: 0.5)
The pad between the axes and legend border, in font-size units.
浮点型,默认值:0.5,坐标轴和图例边框之间的距离,以字体大小为单位**(不理解)**

columnspacing: float, default: rcParams[“legend.columnspacing”] (default: 2.0)
The spacing between columns, in font-size units.
列间距:浮点型,默认值2,列之间的距离,以字体大小为单位

列间距为0:columnspacing=0


import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2.1,0.1)
y1 = np.power(x,3)
y2 = np.power(x,2)
y3 = np.power(x,1)

plt.plot(x, y1,ls='-', label='$x^3$')
plt.plot(x, y2, ls='-.', label='$x^2$')
plt.plot(x, y3, ls=':',label='$x^1$')

plt.xlim(0,2)
plt.ylim(0,8)
plt.grid(ls=':',color='r')
plt.legend(loc='upper left',ncol=3,
           bbox_to_anchor=(0.05, 0.95),
           shadow=True,borderpad=2,
           labelspacing=1,handlelength=1,
           handletextpad=0,columnspacing=0)
plt.show()

Matplotlib--legend函数_第36张图片
列间距为5: columnspacing=5


import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0,2.1,0.1)
y1 = np.power(x,3)
y2 = np.power(x,2)
y3 = np.power(x,1)

plt.plot(x, y1,ls='-', label='$x^3$')
plt.plot(x, y2, ls='-.', label='$x^2$')
plt.plot(x, y3, ls=':',label='$x^1$')

plt.xlim(0,2)
plt.ylim(0,8)
plt.grid(ls=':',color='r')
plt.legend(loc='upper left',ncol=3,
           bbox_to_anchor=(0.05, 0.95),
           shadow=True,borderpad=2,
           labelspacing=1,handlelength=1,
           handletextpad=0,columnspacing=5)
plt.show()

Matplotlib--legend函数_第37张图片
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 matplotlib.legend.Legend.get_legend_handler_map.(不理解)

疑问汇总

序号 问题
1 legend()中的标签需要加中括号,否则只显示第一个字母
2 line1, = plt.plot(x,y1,ls=’:’) line后面必须加‘,’,才能正常输出图例内容,否则显示空白图例框
3 参数 numpoints,针对线图,不知如何使用,参数调整未观察到变动
4 参数 framealpha,实践看着默认透明度不是0.8
5 参数 bbox_to_anchor中的width, height
6 参数 scatteryoffsets为什么列表中有三个变量
7 参数 mode
8 参数 bbox_transform
9 参数 borderaxespad
10 参数 handler_map

官方文档: legend函数

你可能感兴趣的:(Matplotlib)