如何向 Matplotlib 图例添加多个元素?
Posted
技术标签:
【中文标题】如何向 Matplotlib 图例添加多个元素?【英文标题】:How do you add more than one element to a Matplotlib legend? 【发布时间】:2020-08-18 08:36:54 【问题描述】:我似乎不知道如何在折线图的图例中添加多个元素。我已在此处附上我的图表,任何帮助将不胜感激!
这是我的代码:
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()
还有my graph
【问题讨论】:
【参考方案1】:您正在两个单独的轴上绘图,因此当您调用 plt.legend()
时,它只使用最新的轴。您可以通过创建 proxy artists 并手动将它们添加到图例中来解决此问题:
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()
来设置第二个轴checkout the documentation。以这种方式使用代理艺术家可为您在图例中呈现的内容提供更大的灵活性。这是输出(显然不是真实数据):
【讨论】:
以上是关于如何向 Matplotlib 图例添加多个元素?的主要内容,如果未能解决你的问题,请参考以下文章
Python使用matplotlib函数subplot可视化多个不同颜色的折线图为指定的子图添加图例信息(legend)