- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to plot a rectangle on a datetime axis using Matplotlib?
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.
Example
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 = datetime.now() endTime = startTime + timedelta(seconds=1) start = mdates.date2num(startTime) end = mdates.date2num(endTime) width = end – start rect = Rectangle((start, 0), width, 1, color='red') ax.add_patch(rect) locator = mdates.AutoDateLocator(minticks=3) formatter = mdates.AutoDateFormatter(locator) ax.xaxis.set_major_locator(locator) ax.xaxis.set_major_formatter(formatter) plt.xlim([start - width, end + width]) plt.ylim([-.5, 1.5]) plt.show()
Output
- Related Articles
- How to plot int to datetime on X-axis using Seaborn?
- How to rotate the rectangle patch in a plot using Matplotlib?
- How to plot a rectangle inside a circle in Matplotlib?
- How to plot data against specific dates on the X-axis using Matplotlib?
- Plot a circle inside a rectangle in Matplotlib
- How to draw axis lines inside a plot in Matplotlib?
- How to place customized legend symbols on a plot using Matplotlib?
- How to plot multiple Pandas columns on the Y-axis of a line graph (Matplotlib)?
- Changing the formatting of a datetime axis in Matplotlib
- Plot scatter points on polar axis in Matplotlib
- How to plot events on time using Matplotlib?
- Adding caption below X-axis for a scatter plot using Matplotlib
- Plot a rectangle with an edgecolor in Matplotlib
- How to add a legend on Seaborn facetgrid bar plot using Matplotlib?
- How to plot arbitrary markers on a Pandas data series using Matplotlib?

Advertisements