Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Position text in matplotlib with date as axis

I'm trying to position text using the .text() method in matplotlib. My x-axis is formatted as datetime64. It works as advertised, but I nevertheless get an error as shown below.

My code:

fix, ax = plt.subplots()
ax.plot(x,y)
ax.text('2014-11-01', 82, 'Text goes here', fontsize=26, weight='bold', alpha=.8)
plt.text('2014-11-01', 77, s= 'Subtitle text goes here', fontsize=18)

Which returns a plot as expected: plot with text

In addition, an error is raised:

TypeError: must be real number, not str

I'm quite confused by this. I also tried passing in a number through matplotlib's dates.date2num(t) method, but that wasn't successful.

like image 618
Robert Ritz Avatar asked Aug 14 '26 04:08

Robert Ritz


1 Answers

You need to pass to .text() the coordinates before the actual text you want to insert. For example:

>>> text(0.5, 0.5,'matplotlib', horizontalalignment='center',
...      verticalalignment='center',
...      transform=ax.transAxes)

The error you're getting is caused by passing a string ('2014-11-01') where the method expects a number.

See the docs.

like image 56
Edgar Ramírez Mondragón Avatar answered Aug 16 '26 14:08

Edgar Ramírez Mondragón



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!