在图形外部创建图例

2024-04-18 02:54:40 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的一张图中,我使用了次轴。我的代码创建两个不同的图例,并在我的图形中显示图例。这是我的代码:

fig3 = plt.figure()
ax3 = fig3.add_subplot(111)
ax4 = fig3.add_subplot(111)

ax4 = ax3.twinx()
line6 = ax3.plot(threshold, different_costs, '-r', label = 'Costs   differences', linewidth = 2.0)
line7 = ax4.plot(threshold, costs1, '-b', label = 'Costs of Model 1 (OFF)',    linewidth = 2.0)
line9 = ax4.plot(threshold, costs2, '-y', label = 'Costs of Model 2 (STANDBY)', linewidth = 2.0)

ax3.set_xlabel("Threshold")
ax3.set_ylabel("Costs savings")
ax4.set_ylabel("Total costs")

plt.suptitle("Costs savings of using MODEL 1")
plt.legend()

plt.show()

如何创建一个带有三个标签的图例?我怎样才能在图表之外显示这个传奇呢?


Tags: of代码addthresholdplotpltlabel图例
1条回答
网友
1楼 · 发布于 2024-04-18 02:54:40

在这部分代码中:

line6 = ax3.plot(threshold, different_costs, '-r', label = 'Costs   differences', linewidth = 2.0)
line7 = ax4.plot(threshold, costs1, '-b', label = 'Costs of Model 1 (OFF)',    linewidth = 2.0)
line9 = ax4.plot(threshold, costs2, '-y', label = 'Costs of Model 2 (STANDBY)', linewidth = 2.0)

要将所有行放到同一个图例上,请编写:

lns = line6 + line7 + line9
labels = [l.get_label() for l in lns]
plt.legend(lns, labels)

要想让你的传说脱离情节,请参考这个答案How to put the legend out of the plot,你可以写:

plt.legend(lns, labels, loc='upper right', bbox_to_anchor=(0.5, -0.05))

对于一些示例数据:

fig3 = plt.figure()
ax3 = fig3.add_subplot(111)
ax4 = fig3.add_subplot(111)

ax4 = ax3.twinx()
line6 = ax3.plot(range(0,10), range(0,10), '-r', label = 'Costs   differences', linewidth = 2.0)
line7 = ax4.plot(range(10,15), range(10,15), '-b', label = 'Costs of Model 1 (OFF)',    linewidth = 2.0)
line9 = ax4.plot(range(0,5), range(0,5), '-y', label = 'Costs of Model 2 (STANDBY)', linewidth = 2.0)

ax3.set_xlabel("Threshold")
ax3.set_ylabel("Costs savings")
ax4.set_ylabel("Total costs")

plt.suptitle("Costs savings of using MODEL 1")

lns = line6 + line7 + line9
labels = [l.get_label() for l in lns]
plt.legend(lns, labels, loc='upper right', bbox_to_anchor=(0.5, -0.05))

plt.show()

Lines on legend and Legend outside plot

相关问题 更多 >