简体   繁体   中英

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.

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.

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. 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.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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