繁体   English   中英

如何在 python 中使用 matplotlib 将文本放入图中

[英]How to put text in figure using matplotlib in python

我正在尝试在python3中使用matplotlib循环 plot 多个数字。 对于循环中的每个元素,我绘制实际曲线和拟合曲线。 这是我编写的代码:

plt.figure()
plt.plot(t, y,'g--',label="data")

plt.ylabel("Rate")
plt.xlabel("Time")
plt.title("{},{},{}".format(a,b,c),fontsize=8)

plt.text(0.8,0.8,"R-sq:"+str(round(r_squared,2)),fontsize=8)
plt.text(0.8,0.7,"decay:"+str(round(1/(12*fit_b),2)),fontsize=8)

plt.text(40.1,1.0,"#Cohort:"+str(C),fontsize=8)
plt.text(40.1,0.9,"Samples:"+str(int(S)),fontsize=8)

plt.grid()

plt.plot(t, yhat, 'b--',label='Fitted Function:\n $y = %0.4f e^{%0.4f t} $' % (fit_a, fit_b))
plt.legend(bbox_to_anchor=(0.4, 0.4), fancybox=True, shadow=True) #1.4, 1.1

name="./fig_weight/{}__{}__{}.png".format(a,b,c)
plt.savefig(name)
plt.show()

我试图将R-squared, Decay value and several other things放在图中,以便于可视化。 对于某些地块 alignment 很好,但对于其他地块,文本超出 plot 区域。 我为不同的迭代运行相同的代码。 如何解决?

这里是情节:

在此处输入图像描述

在此处输入图像描述

您使用具有固定数字的plt.text位置值,但您的轴范围正在改变。 一种选择是 plot 位置基于您的数据,例如曲线上的最后一个[-1]或中间[int(t.shape[0]/2.)]元素,使用移位tshift偏移文本,例如

plt.text(t[-1]+tshift, y[-1]+tshift,"R-sq:"+str(round(r_squared,2)),fontsize=8)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM