简体   繁体   English

将文本放入matplotlib中的绘图中

[英]Putting text inside plot in matplotlib

I am making multiple line plots.我正在制作多条线图。 In each step I add another line to the previous plot.在每一步中,我都会在上一个图中添加另一条线。 They look like this:它们看起来像这样:

在此处输入图片说明

Now I want to delete legend and add names of the countries above the lines, for instance China above blue line.现在我想删除图例并添加线条上方的国家名称,例如蓝线上方的中国。 How can I add a text by the lines?如何按行添加文本?

My code for creating those multiple plots:我创建这些多个图的代码:

for i in years:
    yearsi=list((range(1960,i+1)))
    yearsi=map(str,yearsi)
    ax=df.pivot_table(values=yearsi, columns='Country Name').plot()
    ax.set_ylim([0, 1500])
    ax.set_xticks(range(0,61,10))
    ax.set_xticklabels(range(1960, 2021,10))

Where dataframe is like this数据框是这样的

在此处输入图片说明

I've just tested it out quickly and you should be able to achieve what you're looking for using Text if you get your coordinates right.我刚刚对其进行了快速测试,如果您获得正确的坐标,您应该能够使用Text实现您要查找的内容。

Create a new text instance:创建一个新的文本实例:

self.look_at_me = self.ax2.text(0, 0, 'Look at me!', size=12, color='g')

The above is all you should need for your example!以上就是您的示例所需的全部内容! The 0, 0 are the x, y coordinates for the text. 0, 0 是文本的 x, y 坐标。

Now I have a function which is animating a plot, you might not have this.现在我有一个动画情节的函数,你可能没有这个。 Anyway just for something extra you can update the position of the text to some new x and y coordinates based on the data.无论如何,只是为了额外的东西,您可以根据数据将文本的位置更新为一些新的 x 和 y 坐标。 ie IE

def animate(i):
    self.look_at_me.set_position((self.df['t'][i], self.df['r_mag'][i]))

That gives the following result and it should work with as many text labels as you need with the corresponding data.这给出了以下结果,它应该可以根据需要使用相应的数据处理尽可能多的文本标签。

在此处输入图片说明

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

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