问题在于,matplotlib使用其自己的日期/时间表示形式(浮动天数),因此您必须先进行转换。此外,您将不得不告诉xaxis它应该具有日期/时间刻度和标签。下面的代码可以做到这一点:
from datetime import datetime, timedeltafrom matplotlib.patches import Rectangleimport matplotlib.pyplot as pltimport matplotlib.dates as mdates# Create new plotfig = plt.figure()ax = fig.add_subplot(111)# Create rectangle x coordinatesstartTime = datetime.now()endTime = startTime + timedelta(seconds = 1)# convert to matplotlib date representationstart = mdates.date2num(startTime)end = mdates.date2num(endTime)width = end - start# Plot rectanglerect = Rectangle((start, 0), width, 1, color='yellow')ax.add_patch(rect)# assign date locator / formatter to the x-axis to get proper labelslocator = mdates.AutoDateLocator(minticks=3)formatter = mdates.AutoDateFormatter(locator)ax.xaxis.set_major_locator(locator)ax.xaxis.set_major_formatter(formatter)# set the limitsplt.xlim([start-width, end+width])plt.ylim([-.5, 1.5])# goplt.show()
结果:
注意 :Matplotlib 1.0.1 非常 旧。我不能保证我的例子会起作用。您应该尝试更新!



