Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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

like image 289
szczor1 Avatar asked Jan 27 '26 11:01

szczor1


1 Answers

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

like image 158
andy Avatar answered Jan 29 '26 02:01

andy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!