原文: https://pythonspot.com/matplotlib-legend/

Matplotlib 对图例具有本机支持。 图例可以放置在各个位置:图例可以放置在图表的内部或外部,并且可以移动位置。

legend()方法将图例添加到绘图中。 在本文中,我们将向您展示一些使用 matplotlib 的图例示例。

Matplotlib 内部图例

要将图例放置在内部,只需调用legend()

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. y = [2,4,6,8,10,12,14,16,18,20]
  4. y2 = [10,11,12,13,14,15,16,17,18,19]
  5. x = np.arange(10)
  6. fig = plt.figure()
  7. ax = plt.subplot(111)
  8. ax.plot(x, y, label='$y = numbers')
  9. ax.plot(x, y2, label='$y2 = other numbers')
  10. plt.title('Legend inside')
  11. ax.legend()
  12. plt.show()

Matplotlib 图例 - 图1

Matplotlib 内部图例

Matplotlib 底部图例

要将图例置于底部,请将legend()调用更改为:

  1. ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),  shadow=True, ncol=2)

考虑到我们设置了列数ncol = 2并设置了阴影。

完整的代码为:

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. y = [2,4,6,8,10,12,14,16,18,20]
  4. y2 = [10,11,12,13,14,15,16,17,18,19]
  5. x = np.arange(10)
  6. fig = plt.figure()
  7. ax = plt.subplot(111)
  8. ax.plot(x, y, label='$y = numbers')
  9. ax.plot(x, y2, label='$y2 = other numbers')
  10. plt.title('Legend inside')
  11. ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),  shadow=True, ncol=2)
  12. plt.show()

Matplotlib 图例 - 图2

放在底部的图例

Matplotlib 顶部图例

要将图例放在顶部,请更改bbox_to_anchor值:

  1. ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.00),  shadow=True, ncol=2)

代码:

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. y = [2,4,6,8,10,12,14,16,18,20]
  4. y2 = [10,11,12,13,14,15,16,17,18,19]
  5. x = np.arange(10)
  6. fig = plt.figure()
  7. ax = plt.subplot(111)
  8. ax.plot(x, y, label='$y = numbers')
  9. ax.plot(x, y2, label='$y2 = other numbers')
  10. plt.title('Legend inside')
  11. ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.00), shadow=True, ncol=2)
  12. plt.show()

Matplotlib 图例 - 图3

顶部图例

外部右侧图例

我们可以通过调整框的大小并相对于图例放置图例来在外部放置图例:

  1. chartBox = ax.get_position()
  2. ax.set_position([chartBox.x0, chartBox.y0, chartBox.width*0.6, chartBox.height])
  3. ax.legend(loc='upper center', bbox_to_anchor=(1.45, 0.8), shadow=True, ncol=1)

代码:

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. y = [2,4,6,8,10,12,14,16,18,20]
  4. y2 = [10,11,12,13,14,15,16,17,18,19]
  5. x = np.arange(10)
  6. fig = plt.figure()
  7. ax = plt.subplot(111)
  8. ax.plot(x, y, label='$y = numbers')
  9. ax.plot(x, y2, label='$y2 = other numbers')
  10. plt.title('Legend outside')
  11. chartBox = ax.get_position()
  12. ax.set_position([chartBox.x0, chartBox.y0, chartBox.width*0.6, chartBox.height])
  13. ax.legend(loc='upper center', bbox_to_anchor=(1.45, 0.8), shadow=True, ncol=1)
  14. plt.show()

Matplotlib 图例 - 图4

Matplotlib 外部图例

下载示例