如何将文本放在python图之外?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42435446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 21:40:26  来源:igfitidea点击:

How to put text outside python plots?

pythonmatplotlib

提问by dSb

I am plotting two time series and computing varies indices for them.

我正在绘制两个时间序列并为它们计算不同的索引。

How to write these indices for these plots outside the plot using annotationor textin python?

如何使用annotationtext在 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 teststroutside the plots. Here is the current plot:

我想teststr在情节之外打印。这是当前的情节:

plot

阴谋

回答by ImportanceOfBeingErnest

It's probably best to define the position in figure coordinates instead of data coordinates as you'd probably not want the text to change its position when changing the data.

最好在图形坐标而不是数据坐标中定义位置,因为您可能不希望文本在更改数据时更改其位置。

Using figure coordinates can be done either by specifying the figure transform (fig.transFigure)

可以通过指定图形变换 ( fig.transFigure)来使用图形坐标

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

or by using the textmethod of the figure instead of that of the axes.

或使用text图形的方法而不是轴的方法。

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

In both cases the coordinates to place the text are in figure coordinates, where (0,0)is the bottom left and (1,1)is the top right of the figure.

在这两种情况下,放置文本的坐标都是图形坐标,其中(0,0)是图形的左下角和(1,1)右上角。

At the end you still may want to provide some extra space for the text to fit next to the axes, using plt.subplots_adjust(left=0.3)or so.

最后,您仍然可能希望为文本提供一些额外的空间以适应轴,使用plt.subplots_adjust(left=0.3)左右。

回答by kazemakase

Looks like the text is there but it lies outside of the figure boundary. Use subplots_adjust()to make room for the text:

看起来文本在那里,但它位于图形边界之外。使用subplots_adjust()以腾出空间给文本:

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

在此处输入图片说明