在图表外创建图例

3
在我的一个图表中,我使用了一个次要轴。我的代码创建了两个不同的图例,并在图表中显示了这些图例。以下是我的代码:
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()

我该如何创建一个包含三个标签的图例?以及如何将这个图例显示在我的图表外面?

请查看我的回答,如果可以的话,请告诉我 :) - Chuck
可以了!但是现在我无法阅读最后一个标签(模型2(待机)的成本)...你知道我该如何解决吗? - Kuijpers
你可能需要尝试在 bbox 中使用不同的数字来适应所有文本。如果答案解决了你的问题,请不要忘记点赞和接受。 - Chuck
我该如何点赞并接受答案? - Kuijpers
如果这个答案解决了你的问题,你可以通过以下链接进行点赞和接受:http://stackoverflow.com/help/someone-answers 和 https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work - Chuck
感谢您的接受 :) - Chuck
1个回答

0

在你的代码的这一部分下:

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)

如果想要将图例放在图形外面,请参考这个答案如何将图例放在图形外面,你可以这样写:

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接