Matplotlib 图例
Matplotlib 原生支持图例。图例可以放置在不同的位置:图例可以放在图表的内部或外部,并且可以移动位置。
legend()
方法将图例添加到图中。在本文中,我们将向你展示使用 Matplotlib 的一些图例。
Matplotlib 内部图例
要将图例放在里面,只需调用 legend()
:
import matplotlib.pyplot as plt
import numpy as np
y = [2,4,6,8,10,12,14,16,18,20]
y2 = [10,11,12,13,14,15,16,17,18,19]
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='$y = numbers')
ax.plot(x, y2, label='$y2 = other numbers')
plt.title('Legend inside')
ax.legend()
plt.show()
![Matplotlib](/img/Tutorial/Matplotlib/Matplotlib legend.svg)
Matplotlib 底部图例
要将图例放在底部,请将 legend()
调用更改为:
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05), shadow=True, ncol=2)
ncol=2
将列数设置为 2 列,shadow=True
设置图例会有阴影。
完整的代码是:
import matplotlib.pyplot as plt
import numpy as np
y = [2,4,6,8,10,12,14,16,18,20]
y2 = [10,11,12,13,14,15,16,17,18,19]
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='$y = numbers')
ax.plot(x, y2, label='$y2 = other numbers')
plt.title('Legend inside')
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05), shadow=True, ncol=2)
plt.show()
![图例放在底部](/img/Tutorial/Matplotlib/Matplotlib legend bottom.svg)
Matplotlib 的顶部图例
要将图例置于顶部,请更改 bbox\_to\_anchor
值:
ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.00), shadow=True, ncol=2)
代码如下:
import matplotlib.pyplot as plt
import numpy as np
y = [2,4,6,8,10,12,14,16,18,20]
y2 = [10,11,12,13,14,15,16,17,18,19]
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='$y = numbers')
ax.plot(x, y2, label='$y2 = other numbers')
plt.title('Legend inside')
ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.00), shadow=True, ncol=2)
plt.show()
![图例在上面](/img/Tutorial/Matplotlib/Matplotlib legend top inside.svg)
Matplotlib 图例放右侧外部
我们可以通过调整框的大小来设置图例,并将图例放在图的右侧外部,
chartBox = ax.get_position()
ax.set_position([chartBox.x0, chartBox.y0, chartBox.width*0.6, chartBox.height])
ax.legend(loc='upper center', bbox_to_anchor=(1.45, 0.8), shadow=True, ncol=1)
代码:
import matplotlib.pyplot as plt
import numpy as np
y = [2,4,6,8,10,12,14,16,18,20]
y2 = [10,11,12,13,14,15,16,17,18,19]
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='$y = numbers')
ax.plot(x, y2, label='$y2 = other numbers')
plt.title('Legend outside')
chartBox = ax.get_position()
ax.set_position([chartBox.x0, chartBox.y0, chartBox.width*0.6, chartBox.height])
ax.legend(loc='upper center', bbox_to_anchor=(1.45, 0.8), shadow=True, ncol=1)
plt.show()
![Matplotlib 放外面的图例](/img/Tutorial/Matplotlib/Matplotlib legend right outside.svg)