I am using series and matplotlib to plot some graph like that :
basically, I build them using
ax.plot(df)
where df is a series with index : ‘Sep’, ‘Oct’, ‘Nov’, ….
and value some number.
What I wanted to have is fill the background, but only after the ‘Mar’ index (for example)
Currently the only things I was able to do is to create a series with only ‘Mar’ to ‘Jul’ as index with constant value to identify the "area", but ideally I would fill the background with some color to identify clearly both part of the graph (before mars it is data realised, after it is some prediction of my algo)
For example, if I use :
ax.set_facecolor('silver')
I have this result :
but that should appear only after ‘Mars’, but I don’t find any way to filter the background to apply this kind of function
>Solution :
As mentioned, you can use axvspan() to add a suitable background colour.
For example:
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import date2num
import random
from datetime import datetime, timedelta
# Create some random data
data = []
x = datetime(2021, 1, 1)
y = 0
day = timedelta(days=1)
for _ in range(100):
x += day
y += random.random()
data.append([x, y])
df = pd.DataFrame(data, columns=['Date', 'Value'])
df.plot('Date', 'Value')
ax = plt.gca()
march = date2num(datetime(2021, 3, 1))
latest = date2num(data[-1][0])
ax.axvspan(xmin=march, xmax=latest, facecolor='silver')
plt.show()
Giving you:


