2017-05-07 133 views
1

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

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

请参阅我的回答你的问题。让我知道它是否有效:) – Chuck

+0

它的工作原理!但现在我无法读取最后的标签(型号2(STANDBY)的费用)...你知道我该如何解决这个问题吗? – Kuijpers

+0

您可能必须在'bbox'内试验不同的数字以适合所有文字。如果答案解决了您的问题,请不要忘记加注并接受。 – Chuck

回答

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

Lines on legend and Legend outside plot