Matplotlib allows one to set text within the plot inself with matplotlib.axes.Axes.text()
.
I am plotting Pandas Series data, so the x-axis are dates.
Datetime
2014-11-08 345
2014-11-09 678
2014-11-10 987
2014-11-11 258
Freq: W-SUN, dtype: int64
If I wanted to add text add location (x,y) = (2014-11-08, 345)
, how could I do this? 2014-11-08
is not actually the x value on the x-axis. How can I find this location?
There are several options. You can either use the values from the Series objects' index, date
or datetime
objects from the Python standard library's datetime
or pandas' Timestamp
object to set the x-axis location of a label on a time-series plot.
import pandas as pd
from pandas import Timestamp
import datetime as dt
import matplotlib.pyplot as plt
s = pd.Series({Timestamp('2014-11-08 00:00:00'): 345,
Timestamp('2014-11-09 00:00:00'): 678,
Timestamp('2014-11-10 00:00:00'): 987,
Timestamp('2014-11-11 00:00:00'): 258})
fig = plt.figure()
ax = fig.gca()
s.plot(ax=ax)
i = 0
ax.text(s.index[i], s.iloc[i], "Hello")
ax.text(dt.date(2014, 11, 9), 500, "World")
ax.text(Timestamp("2014-11-10"), 777, "!!!")
plt.show()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With