Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Matplotlib : fill subarea of a Graph

I am using series and matplotlib to plot some graph like that :

enter image description here

basically, I build them using

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

enter image description here

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:

demo screenshot

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading