在我的一张图中,我使用了辅助轴。我的代码创建了两个不同的图例,并在我的图表中显示了图例。这是我的代码:
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()
如何使用三个标签创建一个图例?如何在图表外显示此图例?
答案 0 :(得分: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)
要将您的图例置于情节之外,请参阅此答案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()