How to plot a rectangle on a datetime axis using Matplotlib?

MatplotlibPythonData Visualization

To plot a recatangle on a datetime axis using matplotlib, we can take the following steps −

  • Set the figure size and adjust the padding between and around the subplots.
  • Create a new figure or activate an existing figure.
  • Add an '~.axes.Axes' to the figure as part of a subplot arrangement using add_subplot() method.
  • To define a rectangle, find the anchor points using datetime and matplotlib's dates.
  • Add a '~.Patch' to the axes' using add_patch() method.
  • Set major axis locator and formatter.
  • Limit x and y axes scale.
  • To display the figure, use show() method.


from datetime import datetime, timedelta
from matplotlib.patches import Rectangle

import matplotlib.pyplot as plt
import matplotlib.dates as mdates

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

fig = plt.figure()

ax = fig.add_subplot(111)

startTime =
endTime = startTime + timedelta(seconds=1)
start = mdates.date2num(startTime)
end = mdates.date2num(endTime)

width = end – start
rect = Rectangle((start, 0), width, 1, color='red')

locator = mdates.AutoDateLocator(minticks=3)
formatter = mdates.AutoDateFormatter(locator)


plt.xlim([start - width, end + width])
plt.ylim([-.5, 1.5])


Published on 03-Jun-2021 09:07:46