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

matplotlib axes draw rectangle
matplotlib rectangle label
matplotlib rectangle rotate
matplotlib hatched rectangle
matplotlib plot box
matplotlib shade rectangle
matplotlib add patch
how to draw a box python

I tried to plot a rectangle on a graph with a datetime x-axis using the following code:

from datetime import datetime, timedelta
from matplotlib.patches import Rectangle
import matplotlib.pyplot as plt

# Create new plot
fig = plt.figure()
ax = fig.add_subplot(111)

# Create rectangle
startTime = datetime.now()
width = timedelta(seconds = 1)
endTime = startTime + width
rect = Rectangle((startTime, 0), width, 1, color='yellow')

# Plot rectangle
ax.add_patch(rect)   ### ERROR HERE!!! ###
plt.xlim([startTime, endTime])
plt.ylim([0, 1])
plt.show()

However, I get the error:

TypeError: unsupported operand type(s) for +: 'float' and 'datetime.timedelta'

What's going wrong? (I'm using matplotlib version 1.0.1)

The problem is that matplotlib uses its own representation of dates/times (floating number of days), so you have to convert them first. Furthermore, you will have to tell the xaxis that it should have date/time ticks and labels. The code below does that:

from datetime import datetime, timedelta
from matplotlib.patches import Rectangle
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# Create new plot
fig = plt.figure()
ax = fig.add_subplot(111)

# Create rectangle x coordinates
startTime = datetime.now()
endTime = startTime + timedelta(seconds = 1)

# convert to matplotlib date representation
start = mdates.date2num(startTime)
end = mdates.date2num(endTime)
width = end - start

# Plot rectangle
rect = Rectangle((start, 0), width, 1, color='yellow')
ax.add_patch(rect)   

# assign date locator / formatter to the x-axis to get proper labels
locator = mdates.AutoDateLocator(minticks=3)
formatter = mdates.AutoDateFormatter(locator)
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)

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

# go
plt.show()

Result:

NOTE: Matplotlib 1.0.1 is very old. I can't guarantee that my example will work. You should try to update!

Rectangle patch added to a datetime x-axis is plotted with the wrong , Code for reproduction import pandas as pd import matplotlib.pyplot as mpp When adding a Rectangle patch to a plot with a datetime x-axis the width the units conversion machinery, so you have to convert by hand using  The following are code examples for showing how to use matplotlib.pyplot.Rectangle().They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Another error that you can see when trying to create a patches.Rectangle artist using the datetime values for x is:

TypeError: float() argument must be a string or a number.

The reason for this is that during Rectangle object initialization x argument is converted internally to float:

self._x = float(xy[0])

It doesn't work for datetime values. Solution proposed by @hitzg will solve this issue because matplotlib.dates.date2num() returns float.

How-to, I tried to plot a rectangle on a graph with a datetime x-axis using the following code: from datetime import datetime, timedelta from matplotlib.patches import  Return the height of the rectangle. Return the Transform instance which takes patch coordinates to data coordinates. For example, one may define a patch of a circle which represents a radius of 5 by providing coordinates for a unit circle, and a transform which scales the coordinates (the patch coordinate) by 5.

The issue is that the type(startTime) datetime.datetime isn't a valid type to pass into the rectangle. It needs to be typecast into a supported type in order to use the rectangle patch.

If all you really want is to make a yellow rectangle just make a normal plot with a yellow background:

from datetime import datetime, timedelta
from matplotlib.patches import Rectangle
import matplotlib.pyplot as plt

# Create new plot
fig = plt.figure()
ax = fig.add_subplot(111, axisbg='yellow')
plt.xticks(rotation=15)
plt.tight_layout()
# Create rectangle
startTime = datetime.now()
width = timedelta(seconds = 1)
endTime = startTime + width

#rect = Rectangle((0, 0), 1, 1, color='yellow')

# Plot rectangle
#ax.add_patch(rect)   ### ERROR HERE!!! ###

plt.xlim([startTime, endTime])
plt.ylim([0, 1])
plt.show()

matplotlib.patches.Rectangle, Plot numpy.datetime64 values; Check whether a figure is empty objects are handled the same way as datetime.datetime objects. The figure has a Rectangle instance called patch and the axes has a Rectangle instance called patch. between multiple rows and columns using the matplotlib.figure. Similar to plot, this plots y vs. x as lines or markers. However, the axis labels are formatted as dates depending on xdate and ydate. Parameters: x, yarray-like. The coordinates of the data points. If xdate or ydate is True, the respective values x or y are interpreted as Matplotlib dates. fmtstr, optional.

Fill Between and Alpha, Set the bottom coord of the rectangle. xy ¶. Return the left and bottom coords of the rectangle. Examples using matplotlib  So far in this chapter, using the datetime index has worked well for plotting, but there have been instances in which the date tick marks had to be rotated in order to fit them nicely along the x-axis. Luckily, matplotlib provides functionality to change the format of a date on a plot axis using the DateFormatter module, so that you can

Gallery, Let's compare two graphs of a financial times with a simple line plot on the prefers datetime instead of np.datetime64. date = r.date.astype('O') # create two subplots with the shared x and y axes fig, (ax1, ax2) = plt.subplots(1, 2, not a matplotlib limitation), so when using alpha save your figures in PNG,  You must first convert your timestamps to Python datetime objects (use datetime.strptime). Then use date2num to convert the dates to matplotlib format. Plot the dates and values using plot_date: dates = matplotlib.dates.date2num(list_of_datetimes) matplotlib.pyplot.plot_date(dates, values)

matplotlib.axes._axes, Pyplot. Color. Shapes and collections. Style sheets. Axes Grid. Axis Artist Demonstrates plotting contour (level) curves in 3D using the  From my understanding matplotlib is a plotting library. If you want to change the image data (e.g. draw a rectangle on an image), you could use PIL's ImageDraw, OpenCV, or something similar. Here is PIL's ImageDraw method to draw a rectangle. Here is one of OpenCV's methods for drawing a rectangle.

Comments
  • Note that if the dates in the x-axis are from pandas, you need to convert to python date-time first. The line start = mdates.date2num( startTime ) would then be start = mdates.date2num( startTime.to_pydatetime() ). The same goes for the end.