Matplotlib setting text in plot with plt.text () with pandas time series data

Matplotlib allows you to set text within the plot using matplotlib.axes.Axes.text() .

I draw Pandas series data, so the x axis is 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 can I do this? 2014-11-08 is actually not the x value on the x axis. How to find this place?

+5
source share
1 answer

There are several options. You can use values ​​from objects of objects of objects of a series, date or datetime from the Python standard datetime or pandas' Timestamp standard library to set the location of the x axis of the label on the time series graph.

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

Result

+5
source

Source: https://habr.com/ru/post/1238780/


All Articles