我正在尝试为图例添加一些文字。这是关于框中的文字。另一个解决方案是文本框保留在图例下方,放大图形时不会移动。
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()
这是我现在的图表:
答案 0 :(得分: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)
此方法具有奖励效果,即您首先获得图例中已有的内容,因此您无需手动显式构建它。
答案 1 :(得分:2)
这会将文字添加到图例中(受此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()
答案 2 :(得分:0)
尝试在plt.text中使用transform。现在前两个坐标是相对于轴的。
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'))