def setXLocator(ax, xlim_min, xlim_max): day_range = (xlim_max - xlim_min).days # if day_range <= 2: # days = mdates.HourLocator(interval=4) # ax.xaxis.set_major_locator(days) # ax.xaxis.set_major_formatter(mdates.DateFormatter('%H')) if day_range <= 60: days = mdates.DayLocator(interval=(day_range / 6)) ax.xaxis.set_major_locator(days) ax.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d')) else: month_range = day_range / 30 if month_range <= 12.: months = mdates.MonthLocator() # every month ax.xaxis.set_major_locator(months) ax.xaxis.set_major_formatter(mdates.DateFormatter('%b')) elif month_range <= 24.: months = mdates.MonthLocator(interval=2) ax.xaxis.set_major_locator(mdates.AutoDateLocator()) ax.xaxis.set_major_formatter(mdates.DateFormatter('%b')) elif month_range <= 48.: months = mdates.MonthLocator(interval=4) ax.xaxis.set_major_locator(months) ax.xaxis.set_major_formatter(mdates.DateFormatter('%b')) else: years = mdates.YearLocator() ax.xaxis.set_major_locator(years) ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y')) if month_range <= 48: add_year_xaxis(ax, xlim_min, xlim_max)
def add_year_xaxis(ax, xlim_min, xlim_max): ''' add year xaxis ''' if xlim_min.year == xlim_max.year: ax.set_xlabel(xlim_min.year, fontsize=11, fontproperties=FONT0) return newax = ax.twiny() newax.set_frame_on(True) newax.grid(False) newax.patch.set_visible(False) newax.xaxis.set_ticks_position('bottom') newax.xaxis.set_label_position('bottom') newax.set_xlim(xlim_min, xlim_max) newax.xaxis.set_major_locator(mdates.YearLocator()) newax.xaxis.set_major_formatter(mdates.DateFormatter('%Y')) newax.spines['bottom'].set_position(('outward', 20)) newax.spines['bottom'].set_linewidth(0.6) newax.tick_params(which='both', direction='in') set_tick_font(newax) newax.xaxis.set_tick_params(length=5)