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

19

我尝试使用以下代码在具有日期时间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()

然而,我遇到了错误:

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

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

3个回答

24
问题在于matplotlib使用自己的日期/时间表示方法(以浮点数形式表示天数),因此您需要先将它们转换为此格式。此外,您还需要告诉x轴应具有日期/时间刻度和标签。下面的代码可以实现这一点:
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()

结果:

enter image description here

注意:Matplotlib 1.0.1版本非常老旧。我无法保证我的示例代码可以正常工作。建议您尝试更新至最新版本!


请注意,如果x轴上的日期来自于pandas,则需要先转换为Python日期时间。然后,这一行语句start = mdates.date2num( startTime ) 将变成 start = mdates.date2num( startTime.to_pydatetime() )。同样,也是对于end - Luis

0
问题在于type(startTime) datetime.datetime不是传递到矩形中的有效类型。它需要被强制转换为支持的类型,以便使用矩形补丁。
如果你只想要一个黄色的矩形,那么可以用黄色背景做一个普通的绘图:
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()

0

在尝试使用日期时间值创建patches.Rectangle对象时,您可能会遇到另一种错误:

TypeError: float()的参数必须是字符串或数字。

造成这个错误的原因是在Rectangle对象初始化期间,x参数被内部转换为浮点数:

self._x = float(xy[0])

这对于日期时间值是行不通的。@hitzg提出的解决方案将解决此问题,因为matplotlib.dates.date2num()返回浮点数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接