如何使用matplotlib在日期时间轴上绘制矩形?

mch*_*hen 13 python matplotlib python-2.7

我尝试使用以下代码在具有日期时间x轴的图形上绘制矩形:

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()
Run Code Online (Sandbox Code Playgroud)

但是,我收到错误:

TypeError: unsupported operand type(s) for +: 'float' and 'datetime.timedelta'
Run Code Online (Sandbox Code Playgroud)

出了什么问题?(我正在使用matplotlib版本1.0.1)

hit*_*tzg 15

问题是matplotlib使用自己的日期/时间表示(浮动天数),因此您必须先转换它们.此外,您必须告诉xaxis它应该有日期/时间标记和标签.下面的代码是这样的:

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()
Run Code Online (Sandbox Code Playgroud)

结果:

在此输入图像描述

注意:Matplotlib 1.0.1 非常老.我无法保证我的例子能够奏效.你应该尝试更新!