我尝试使用以下代码在具有日期时间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版)
问题在于,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()
结果:
注意 :Matplotlib 1.0.1 非常 旧。我不能保证我的例子会起作用。您应该尝试更新!