繁体   English   中英

如何向 Matplotlib 图例添加多个元素?

[英]How do you add more than one element to a Matplotlib legend?

我似乎无法弄清楚如何在折线图的图例中添加多个元素。 我在这里附上了我的图表,任何帮助将不胜感激!

这是我的代码:

fig1 = figure()

ax0 = fig1.add_subplot(111)
line0 = ax0.plot(ln_xdata0, ln_ydata0, '_-', label = "Sweden Crime Rate")
ylabel("Sweden Crime Rate")
xlabel("Year")


ax1 = fig1.add_subplot(111, sharex = ax0, frameon = False, label = "Sweden Population Growth (in millions)")
line1 = ax1.plot(ln_xdata1, ln_ydata1, 'xr-', label = "Sweden Population Growth")
ax1.yaxis.tick_right()
ax1.yaxis.set_label_position("right")
ylabel("Sweden Population Growth (in millions)")


plt.title("Sweden Crime Rate and Population Growth")

plt.legend(loc = 'lower right')
plt.show()

还有我的图表

您在两个单独的轴上绘图,因此当您调用plt.legend()时,它只采用最新的轴。 您可以通过创建代理艺术家并将其手动添加到图例中来解决此问题:

import matplotlib.pyplot as plt
# import lines so we can create Line2D instances to go into the legend
import matplotlib.lines as mlines

fig, ax = plt.subplots(1)

line0 = ax.plot(range(20),range(20), 'ob-', label = "Sweden Crime Rate")
ax.set_ylabel("Sweden Crime Rate")
ax.set_xlabel("Year")

# setup the second axis
ax2 = ax.twinx()
ax2.set_ylabel("Sweden Population Growth (in millions)")
# plot the second line
line1 = ax2.plot(range(10),range(10), 'xr-')

plt.title("Sweden Crime Rate and Population Growth")

# Create proxy artists to add to the legend
red_line  = mlines.Line2D([], [], color='red', marker='x', markersize=8, label='Sweden population growth')
blue_line = mlines.Line2D([], [], color='blue', marker='o', markersize=8, label='Sweden crime rate')

# Add the created lines to the legend
plt.legend(handles=[red_line, blue_line], loc='lower right')
plt.show()

作为旁注,我在这里使用twinx()来设置第二个轴,请查看文档 以这种方式使用代理艺术家可为您在图例中呈现的内容提供更大的灵活性。 这是output(显然不是真实数据):

阴谋

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM