python - Align rectangles on date axis -
i draw rectangle indicate range within x axis. can use locators setting ticks , labels, don't seem succeed using them draw rectangle. how go it?!
import datetime dt matplotlib import pyplot plt import matplotlib.dates dates ddata = [dt.datetime.strptime('2010-02-05', "%y-%m-%d"), dt.datetime.strptime('2010-02-19', "%y-%m-%d"), dt.datetime.strptime('2010-03-05', "%y-%m-%d"), dt.datetime.strptime('2010-03-19', "%y-%m-%d"),] values = [123,678,987,345] d1 = zip(ddata,values) def nplot(data): x = [date (date, value) in data] y = [value (date, value) in data] # set stage fig, ax = plt.subplots() graph = fig.add_subplot(111) # plot data red line round markers graph.plot(x,y,'r-o') days = dates.daylocator(interval=7) # every week months = dates.monthlocator() # every month # create locators , ticks ax.xaxis.set_minor_locator(days) ax.xaxis.set_minor_formatter(dates.dateformatter('%d')) ax.xaxis.set_major_locator(months) ax.xaxis.set_major_formatter(dates.dateformatter('\n\n%b')) ax.xaxis.grid(true, which="major", linewidth=2) # how align rectangle specific dates? gca().add_patch(rectangle((data[0][0], 1000), data[2][0], 1000, facecolor='w', alpha=0.9)) # doesn't work plt.show() nplot(d1) 
with set minor ticks
locs = ax.xaxis.get_minorticklocs() and write rectangle. odd, location of left side 6-digit float, location right side number of days since left side. no idea how works, seems to...
gca().add_patch(rectangle((locs[0], 0), 7, 1000, facecolor='w', alpha=0.9)) and wanted beginning: mark recurring ranges.
locs = ax.xaxis.get_minorticklocs() loc_len = len(locs) zloc = zip(locs, [7] * loc_len) # seven-day loops in zloc[::2]: gca().add_patch(rectangle((i[0], 0), i[1], 1000, facecolor='w', alpha=0.9)) 
however, won't work if decide box months, each month has different number of days. @greg's suggestion of using fill_between option, set limits in relation data, not scale (which ok, guess):
xloc = zip(x[:-1], x[1:]) in xloc[::2]: ax.fill_between(i, 0, 1200, facecolor='w', alpha=0.5) ylim(0, 1200) plt.show() 
Comments
Post a Comment