撰写自定义图例

Composing custom legends piece-by-piece.

注意

For more information on creating and customizing legends, see the following pages:

有时您不希望与已绘制的数据明确关联的图例。例如,假设您已绘制了10行,但不希望每个行都显示图例项。如果您只是绘制线条并调用ax.legend(),您将获得以下内容:

  1. # sphinx_gallery_thumbnail_number = 2
  2. from matplotlib import rcParams, cycler
  3. import matplotlib.pyplot as plt
  4. import numpy as np
  5. # Fixing random state for reproducibility
  6. np.random.seed(19680801)
  7. N = 10
  8. data = [np.logspace(0, 1, 100) + np.random.randn(100) + ii for ii in range(N)]
  9. data = np.array(data).T
  10. cmap = plt.cm.coolwarm
  11. rcParams['axes.prop_cycle'] = cycler(color=cmap(np.linspace(0, 1, N)))
  12. fig, ax = plt.subplots()
  13. lines = ax.plot(data)
  14. ax.legend(lines)

撰写自定义图例

请注意,每行创建一个图例项。在这种情况下,我们可以使用未明确绑定到绘制数据的Matplotlib对象组成图例。例如:

  1. from matplotlib.lines import Line2D
  2. custom_lines = [Line2D([0], [0], color=cmap(0.), lw=4),
  3. Line2D([0], [0], color=cmap(.5), lw=4),
  4. Line2D([0], [0], color=cmap(1.), lw=4)]
  5. fig, ax = plt.subplots()
  6. lines = ax.plot(data)
  7. ax.legend(custom_lines, ['Cold', 'Medium', 'Hot'])

撰写自定义图例2

还有许多其他Matplotlib对象可以这种方式使用。 在下面的代码中,我们列出了一些常见的代码。

  1. from matplotlib.patches import Patch
  2. from matplotlib.lines import Line2D
  3. legend_elements = [Line2D([0], [0], color='b', lw=4, label='Line'),
  4. Line2D([0], [0], marker='o', color='w', label='Scatter',
  5. markerfacecolor='g', markersize=15),
  6. Patch(facecolor='orange', edgecolor='r',
  7. label='Color Patch')]
  8. # Create the figure
  9. fig, ax = plt.subplots()
  10. ax.legend(handles=legend_elements, loc='center')
  11. plt.show()

撰写自定义图例3

下载这个示例