Matplotlib pcolormesh with time on x-axis and boolean true/false as the colouring

Viewed 271

I want a plot with the xticklabels as datetime-like objects and the colors to be True/False (1,0) depending on whether that time has been sampled.

The data I am working with looks like this:

import numpy as np
import pandas as pd 
import matplotlib.pyplot as plt 

all_days = pd.date_range("2001-01-01", "2020-12-31", freq="D")
times = all_days[::10]
arr = np.isin(all_days, times).reshape(1, -1)

The plotting code I have is here:

Producing a plot without the colouring (but the correct labels)

plt.pcolormesh(all_days, np.ones(1), arr)

Pcolormesh without the correct colouring

Or without the labels but with the colouring

plt.pcolormesh(arr)

Pcolormesh without the correct x-tick labels

Ultimately, I want a combination of these two plots, the xticklabels of the former and the colouring of the latter.

1 Answers

matplotlib.pyplot.pcolormesh optionally requires X and Y arrays which specify coordinates of the corners of quadrilaterals of the pcolormesh. So you need to pass a proper Y array:

  • size 1
  • from 0 to 1 as y axis limits

So you just need to use:

plt.pcolormesh(all_days, [0, 1], arr)

enter image description here

Related