Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib, settng in-plot text with plt.text() with pandas time series data

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?

like image 912
ShanZhengYang Avatar asked Dec 20 '15 17:12

ShanZhengYang


1 Answers

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()

The result

like image 112
Martin Valgur Avatar answered Nov 08 '22 08:11

Martin Valgur