我尝试使用以下代码在具有日期时间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)
pandas
,则需要先转换为Python日期时间。然后,这一行语句start = mdates.date2num( startTime )
将变成start = mdates.date2num( startTime.to_pydatetime() )
。同样,也是对于end
。 - Luis