Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to plot a rectangle on a datetime axis using Matplotlib?
To plot a rectangle on a datetime axis using Matplotlib, we need to convert datetime objects to numeric values that Matplotlib can handle. This involves using matplotlib.dates module to work with time-based coordinates.
Required Steps
- Set up the figure and subplot
- Define datetime anchor points for the rectangle
- Convert datetime objects to numeric format using
mdates.date2num() - Create a
Rectanglepatch with datetime coordinates - Add the rectangle to the axes using
add_patch()method - Configure datetime formatting for the x-axis
- Set appropriate axis limits and display the plot
Example
Here's how to create a rectangle on a datetime axis ?
from datetime import datetime, timedelta from matplotlib.patches import Rectangle import matplotlib.pyplot as plt import matplotlib.dates as mdates # Set figure size and layout plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True # Create figure and subplot fig = plt.figure() ax = fig.add_subplot(111) # Define datetime range for rectangle startTime = datetime.now() endTime = startTime + timedelta(seconds=1) # Convert datetime to numeric format start = mdates.date2num(startTime) end = mdates.date2num(endTime) # Calculate width and create rectangle width = end - start rect = Rectangle((start, 0), width, 1, color='red') ax.add_patch(rect) # Configure datetime formatting locator = mdates.AutoDateLocator(minticks=3) formatter = mdates.AutoDateFormatter(locator) ax.xaxis.set_major_locator(locator) ax.xaxis.set_major_formatter(formatter) # Set axis limits plt.xlim([start - width, end + width]) plt.ylim([-0.5, 1.5]) plt.show()
Output
The code produces a plot with a red rectangle positioned on a datetime x-axis ?
Key Components
mdates.date2num() ? Converts datetime objects to numeric values that Matplotlib can plot
Rectangle patch ? Creates a rectangular shape with specified position, width, height, and color
AutoDateLocator/Formatter ? Automatically formats datetime labels on the x-axis for better readability
Conclusion
Use mdates.date2num() to convert datetime objects for Matplotlib compatibility. The Rectangle patch combined with proper datetime formatting creates clear time-based visualizations.
