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

问题描述 投票:0回答:1

我似乎不知道如何将多个元素添加到我的线图的图例中。我把我的图附在这里,如果有任何帮助,我将感激不尽。

这是我的代码。

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()

And 我的图

python matplotlib graph legend linegraph
1个回答
0
投票

你是在两个不同的轴上绘制的,所以当你调用了 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() 在这里设置第二个轴。查阅文件. 以这种方式使用代理艺术家可以让你在图例中呈现的内容更加灵活。这里是输出(显然不是真实数据)。

plot

© www.soinside.com 2019 - 2024. All rights reserved.