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

2024-04-24 07:57:22 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: fromimportadddatetimematplotlibcreatefigplt
3条回答

问题是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()

结果:

enter image description here

注意:Matplotlib 1.0.1非常旧。我不能保证我的榜样会起作用。你应该尝试更新!

问题是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()

使用x的日期时间值创建patches.Rectangle艺术家时,您可以看到的另一个错误是:

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

原因是在Rectangle对象初始化期间x参数在内部转换为float:

self._x = float(xy[0])

它不适用于datetime值。@hitzg提出的解决方案将解决这个问题,因为matplotlib.dates.date2num()返回float。

相关问题 更多 >