Python中的 Matplotlib.axes.Axes.legend()
Matplotlib是Python中的一个库,它是 NumPy 库的数值数学扩展。 Axes 类包含大部分图形元素:Axis、Tick、Line2D、Text、Polygon 等,并设置坐标系。 Axes 的实例通过回调属性支持回调。
matplotlib.axes.Axes.legend()函数
matplotlib 库的 axes 模块中的Axes.legend()函数用于在轴上放置图例。
Syntax: Axes.legend(self, *args, **kwargs)
Parameters: This method accepts the following parameters.
- labels : This parameter is the list of labels to show next to the artists.
- handles : This parameter is the list of Artists (lines, patches) to be added to the legend.
Returns:This method returns the matplotlib.legend.Legend instance.
下面的示例说明了 matplotlib.axes 中的 matplotlib.axes.Axes.legend()函数:
示例 1:
# Implementation of matplotlib function
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
line1, = ax.plot([1, 2, 3],
label ="Line 1",
color ="black",
linewidth = 4,
linestyle =':')
line2, = ax.plot([3, 2, 1],
label ="Line 2",
color ="green",
linewidth = 4)
first_legend = ax.legend(handles =[line1],
loc ='upper center')
ax.add_artist(first_legend)
ax.legend(handles =[line2], loc ='lower center')
fig.suptitle('matplotlib.axes.Axes.legend() \
function Example\n', fontweight ="bold")
plt.show()
输出:
示例 2:
# Implementation of matplotlib function
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(19680801)
fig, ax = plt.subplots()
for color in [ 'tab:green', 'tab:blue',
'tab:orange']:
n = 70
x, y = np.random.rand(2, n)
scale = 1000.0 * np.random.rand(n)
ax.scatter(x, y, c = color, s = scale,
label = color,
alpha = 0.35)
ax.legend()
ax.grid(True)
fig.suptitle('matplotlib.axes.Axes.legend() function\
Example\n', fontweight ="bold")
plt.show()
输出: