简体   繁体   English

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

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

I am trying to plot multiple figures in a loop using matplotlib in python3 .我正在尝试在python3中使用matplotlib循环 plot 多个数字。 For every element in loop I draw the actual curve and Fitted curve.对于循环中的每个元素,我绘制实际曲线和拟合曲线。 Here is the code that I have written:这是我编写的代码:

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

I am trying to put R-squared, Decay value and several other things in figure so that it is easy to visualize.我试图将R-squared, Decay value and several other things放在图中,以便于可视化。 For some of the plots alignment is fine but for others the text goes outside plot area.对于某些地块 alignment 很好,但对于其他地块,文本超出 plot 区域。 I am running the same code for different iteration.我为不同的迭代运行相同的代码。 How to fix it?如何解决?

Here are the plots:这里是情节:

在此处输入图像描述

在此处输入图像描述

You use plt.text location values with fixed numbers but your axis range is changing.您使用具有固定数字的plt.text位置值,但您的轴范围正在改变。 One option is to plot locations based on your data, for example the last [-1] or middle [int(t.shape[0]/2.)] element on your curve with a shift tshift to offset the text, eg一种选择是 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