How to place text outside python?

I draw two time series and compute indices for them.

How to write these indices for these graphs outside the graph using annotation or text in python?

Below is my code

 import matplotlib.pyplot as plt obs_graph=plt.plot(obs_df['cms'], '-r', label='Observed') plt.legend(loc='best') plt.hold(True) sim_graph=plt.plot(sim_df['cms'], '-g', label="Simulated") plt.legend(loc='best') plt.ylabel('Daily Discharge (m^3/s)') plt.xlabel('Year') plt.title('Observed vs Simulated Daily Discharge') textstr = 'NSE=%.2f\nRMSE=%.2f\n'%(NSE, RMSE) # print textstr plt.text(2000, 2000, textstr, fontsize=14) plt.grid(True) plt.show() 

I want to print teststr outside the graphs.

Here is the plot

files

+6
source share
2 answers

It is probably best to determine the position in the coordinates of the figures instead of the coordinates of the data, since you probably do not want the text to change its position when the data changes.

Using the coordinates of the figure can be done either by setting the transformation of the figure ( fig.transFigure )

 plt.text(0.02, 0.5, textstr, fontsize=14, transform=plt.gcf().transFigure) 

or using the text method of the shape, not the axis axis.

 plt.gcf().text(0.02, 0.5, textstr, fontsize=14) 

In both cases, the coordinates for placing the text are in the coordinates of the figures, where (0,0) is in the lower left and (1,1) in the upper right corner of the figure.

In the end, you might still want to provide extra space for text that fits near the axes using plt.subplots_adjust(left=0.3) or so.

+12
source

It seems that there is text, but it lies beyond the borders of the picture. Use subplots_adjust() to make room for text:

 import matplotlib.pyplot as plt textstr = 'NSE=%.2f\nRMSE=%.2f\n'%(1, 2) plt.xlim(2002, 2008) plt.ylim(0, 4500) # print textstr plt.text(2000, 2000, textstr, fontsize=14) plt.grid(True) plt.subplots_adjust(left=0.25) plt.show() 

enter image description here

0
source

Source: https://habr.com/ru/post/1015241/


All Articles