python - How to plot a rectangle on a datetime axis using matplotlib? -
i tried plot rectangle on graph datetime x-axis using following code:
from datetime import datetime, timedelta matplotlib.patches import rectangle import matplotlib.pyplot 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()
however, error:
typeerror: unsupported operand type(s) +: 'float' , 'datetime.timedelta'
what's going wrong? (i'm using matplotlib version 1.0.1)
the problem matplotlib uses own representation of dates/times (floating number of days), have convert them first. furthermore, have tell xaxis should have date/time ticks , labels. code below that:
from datetime import datetime, timedelta matplotlib.patches import rectangle import matplotlib.pyplot plt import matplotlib.dates 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 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 x-axis proper labels locator = mdates.autodatelocator(minticks=3) formatter = mdates.autodateformatter(locator) ax.xaxis.set_major_locator(locator) ax.xaxis.set_major_formatter(formatter) # set limits plt.xlim([start-width, end+width]) plt.ylim([-.5, 1.5]) # go plt.show()
result:
note: matplotlib 1.0.1 very old. can't guarantee example work. should try update!
Comments
Post a Comment