Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to annotate pandas date-time format in Matplotlib like Plotly?

How to add annotate text example 1st Lockdown, 2nd Lockdown in Matplotlib like Plotly?

enter image description here

enter image description here

like image 557
Saurav Avatar asked Dec 30 '22 21:12

Saurav


1 Answers

Here is an example using ax.annotate, as another answer suggested:

import matplotlib.pyplot as plt
import pandas as pd

dr = pd.date_range('02-01-2020', '07-01-2020', freq='1D')

y = pd.Series(range(len(dr))) ** 2

fig, ax = plt.subplots()
ax.plot(dr, y)

ax.annotate('1st Lockdown',
            xy=(dr[50], y[50]), #annotate the 50th data point; you could select this in a better way
            xycoords='data', #the xy we passed refers to the data
            xytext=(0, 100), #where we put the text relative to the xy
            textcoords='offset points', #what the xytext coordinates mean
            arrowprops=dict(arrowstyle="->"), #style of the arrow
            ha='center') #center the text horizontally

ax.annotate('2nd Lockdown',
            xy=(dr[100], y[100]), xycoords='data',
            xytext=(0, 100), textcoords='offset points',
            arrowprops=dict(arrowstyle="->"), ha='center')

enter image description here

There are lots of options with annotate, so I would look for an example that matches what you want to do and try and follow that.

Annotations seem to be the "smart" way of doing this in matplotlib; you could also just use axvline and text, but you will likely need to add extra formatting to make things look nicer:

import matplotlib.pyplot as plt
import pandas as pd

dr = pd.date_range('02-01-2020', '07-01-2020', freq='1D')

y = pd.Series(range(len(dr))) ** 2

fig, ax = plt.subplots()
ax.plot(dr, y)

ax.axvline(dr[50], ymin=0, ymax=.7, color='gray')
ax.text(dr[50], .7, '1st Lockdown', transform=ax.get_xaxis_transform(), color='gray')

enter image description here

like image 146
Tom Avatar answered Jan 06 '23 02:01

Tom