2016-02-26 25 views
1

我正在嘗試向圖例添加一些文本。這是關於框中的文字。另一種解決方案是文本框停留在圖例下方,放大圖形時不會移動。將文本添加到python中的圖例

plt.scatter(stageheight,discharge,color='b',label='measured data') 
plt.plot(stageheight_hecras,discharge_hecras,'y^',label='modeled with HEC-RAS') 
plt.plot(stageheight_masked,discharge_predicted,'r-',label='regression line measured data') 
plt.plot(stageheight_hecras,discharge_predicted_hecras,'g-',label='regression line HEC-RAS') 
plt.plot(stageheight_masked,upper,'r--',label='15% error measured data') 
plt.plot(stageheight_masked,lower,'r--') 
plt.plot(stageheight_hecras,upper_hecras,'g--',label='30% error HEC-RAS') 
plt.plot(stageheight_hecras,lower_hecras,'g--') 
plt.fill_between(stageheight_masked,upper,lower,facecolor='red',edgecolor='red',alpha=0.5,label='test') 
plt.fill_between(stageheight_hecras,upper_hecras,lower_hecras,facecolor='green',alpha=0.5) 
plt.axhline(y=0.6,xmin=0,xmax=1,color='black',linewidth = 4.0,label='measuring range') 
plt.text(0.02,0.7,'measured rating curve $Q = 1.37H^2 + 0.34H - 0.007$\nmodeled ratign curve $Q = 2.71H^2 - 2.20H + 0.98$',bbox=dict(facecolor='none',edgecolor='black',boxstyle='square')) 
plt.title('Rating curve Catsop') 
plt.ylabel('discharge') 
plt.ylim(0,2.5) 
plt.xlim(0,1.2) 
plt.xlabel('stageheight[m]') 
plt.legend(loc='upper left', title='Legend') 
plt.grid(True) 
plt.show() 

這是圖我現在有:

this is the graph i have now

+0

您的意思是文字旁邊的符號(例如「用HEC-RAC建模」+ <額外文本)或者是否意味着圖例的另外一行?或者是其他東西? – Ben

+3

請檢查 http://stackoverflow.com/questions/16826711/is-it-possible-to-add-a-string-as-a-legend-item-in-matplotlib – den2042

回答

0

嘗試plt.text使用變換。現在前兩個座標是相對於軸的。

ax = plt.gca() 
ax.text(0.3,0.05,'measured rating curve $Q = 1.37H^2 + 0.34H - 0.007$\nmodeled ratign curve $Q = 2.71H^2 - 2.20H + 0.98$',transform=ax.transAxes, bbox=dict(facecolor='none',edgecolor='black',boxstyle='square')) 
1

這增加了文本傳說(本answer啓發):

from matplotlib.patches import Rectangle 

plt.plot(range(10)) 

p = plt.axhline(y=0.6,xmin=0,xmax=1,color='black',linewidth = 4.0,label='measuring range') 
plt.ylabel('discharge') 
plt.ylim(0,2.5) 
plt.xlim(0,1.2) 
plt.xlabel('stageheight[m]') 
text1 = 'measured rating curve $Q = 1.37H^2 + 0.34H - 0.007$' 
text2 = 'modeled ratign curve $Q = 2.71H^2 - 2.20H + 0.98$' 
extra = Rectangle((0, 0), 1, 1, fc="w", fill=False, edgecolor='none', linewidth=0) 
plt.legend([p, extra, extra],[p.get_label(), text1, text2], loc='upper left', title='Legend') 
plt.grid(True) 
plt.show() 

enter image description here

5

而不是繪製矩形假,你可以使用一個Patch,這不顯示在圖上或軸上:

import matplotlib.patches as mpatches 

extraString = 'measured rating curve $Q = 1.37H^2 + 0.34H - 0.007$\nmodeled rating curve $Q = 2.71H^2 - 2.20H + 0.98$' 
handles, labels = plt.get_legend_handles_labels() 
handles.append(mpatches.Patch(color='none', label=extraString)) 
plt.legend(handles=handles) 

This metho d具有獎勵效果,您首先可以獲取圖例中已有的任何內容,因此您無需手動明確地構建它。