返回

Matplotlib的图例功能妙用无穷,绘图神器,带你一探究竟!

后端

Matplotlib 中的图例是帮助观察者理解图像数据的重要工具。图例通常包含在图像中,用于解释不同的颜色、形状、标签和其他元素。

主要参数

当不设置图例的参数时,默认的图例是这样的:

import matplotlib.pyplot as plt

# Create a figure and axes
fig, ax = plt.subplots()

# Plot some data
ax.plot([1, 2, 3], [4, 5, 6])

# Show the legend
plt.legend()

# Display the figure
plt.show()

可以看到,默认的图例位于右上角,并且没有标题和标签。

我们可以通过设置图例的参数来改变它的位置和样式。例如,我们可以使用 loc 参数来设置图例的位置。

import matplotlib.pyplot as plt

# Create a figure and axes
fig, ax = plt.subplots()

# Plot some data
ax.plot([1, 2, 3], [4, 5, 6])

# Set the legend location
plt.legend(loc='upper left')

# Display the figure
plt.show()

现在,图例位于左上角。

我们还可以使用 title 参数来设置图例的标题。

import matplotlib.pyplot as plt

# Create a figure and axes
fig, ax = plt.subplots()

# Plot some data
ax.plot([1, 2, 3], [4, 5, 6])

# Set the legend title
plt.legend(title='Legend Title')

# Display the figure
plt.show()

现在,图例有了一个标题。

我们还可以使用 labels 参数来设置图例的标签。

import matplotlib.pyplot as plt

# Create a figure and axes
fig, ax = plt.subplots()

# Plot some data
ax.plot([1, 2, 3], [4, 5, 6], label='Line 1')
ax.plot([1, 2, 3], [7, 8, 9], label='Line 2')

# Set the legend labels
plt.legend(labels=['Line 1', 'Line 2'])

# Display the figure
plt.show()

现在,图例中有两个标签。

其他参数

除了上面介绍的主要参数外,Matplotlib 中的图例还有许多其他参数,可以帮助我们自定义图例的样式。

这些参数包括:

  • bbox_to_anchor:用于设置图例的位置。
  • borderaxespad:用于设置图例与轴之间的距离。
  • borderpad:用于设置图例与图例框之间的距离。
  • columns:用于设置图例的列数。
  • facecolor:用于设置图例的背景颜色。
  • fontsize:用于设置图例的字体大小。
  • framealpha:用于设置图例的边框透明度。
  • frameon:用于设置是否显示图例的边框。
  • handlelength:用于设置图例中句柄的长度。
  • handletextpad:用于设置图例中句柄与文本之间的距离。
  • labelspacing:用于设置图例中标签之间的距离。
  • loc:用于设置图例的位置。
  • markerscale:用于设置图例中标记的缩放比例。
  • mode:用于设置图例的模式。
  • ncol:用于设置图例的列数。
  • numpoints:用于设置图例中标记的点数。
  • prop:用于设置图例的字体属性。
  • shadow:用于设置是否显示图例的阴影。
  • title:用于设置图例的标题。
  • title_fontsize:用于设置图例标题的字体大小。
  • use_cmaps:用于设置是否使用颜色映射。

结语

Matplotlib 中的图例是一个非常有用的工具,可以帮助我们理解图像数据。通过设置图例的参数,我们可以自定义图例的位置、样式和标签,从而让图例更加清晰和美观。