python - 将文本添加到python中的图例

标签 python matplotlib legend

我正在尝试向图例添加一些文本。它是关于框中的文本。另一种解决方案是文本框保持在图例下方,并且在您放大图表时不会移动。

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

最佳答案

与其绘制假矩形,不如使用 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)

此方法具有奖励效果,即您首先获得图例中已有的任何内容,因此您不必手动显式构建它。

关于python - 将文本添加到python中的图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35650098/

相关文章:

python - 如何删除 DataFrame 字符串中的特殊字符(例如 ",")?

Python、Selenium 和 Chromedriver - 使用 find_element_by_id 的无限循环导致 CPU 问题

python - 绘图标签位于 tkinter Canvas 上的图形之外

r - ggplot2完全自定义图例?

python - 在带有子图的 geopandas 图中添加图例会改变图的大小

python - Qt5: AttributeError: 'module' 对象没有属性 'QApplication'

python - StandardScaler 变换后可接受的均值和标准差偏移量是多少?

python - Matplotlib 直方图,条形之间没有线条

python - 具有不规则二维 numpy 数组的 Matplotlib basemap + contourf

r - ggplot 条形图 - 按照 x 轴因子拆分填充图例