Putting text inside plot in matplotlib

szczor1 :

I am making multiple line plots. In each step I add another line to the previous plot. They look like this:

enter image description here

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

enter image description here

andy :

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

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.

enter image description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=361522&siteId=1