Adding axhline to my plot and constraining the xmax and xmin with datetime objects

Viewed 25

I have a time series of temperatures for a given location. I have done some analyses using other data and remote sensing to determine the Start and End of the forest growing season for the same location. Now I would like to impose small horizontal lines on a secondary x-axis, which display the length of the growing season. Ideally, it would look something like this. Where the primary x axis is temp, the secondary x axis is a static value for a single growing season and the y axis is the 13 year time period ploted as a datetime object. So basically, i want the same blue lines, but i want there length to be determined by two datetime values.

I am aware that axhline() takes a y positional argument (which will be the static value for the growing season), and a xmin and an xmax which must be normalized floats between 0 and 1.

My question is then, how do I normalize a 13 year-long (daily) dataframe in order to give the plt.axhline() the appropriate values xmin and xmax values.

here is the code i am using to plot the figure above

and here is the dataframe with the dates for the start and end of each of the 13 axhline() lines

fig, temp = plt.subplots()
temp.plot(df_w.index, df_w['TA_F'], color = 'red', label = 'TEMP')

# set x-label 
temp.set_xlabel('Date')
temp.tick_params('x', labelsize =24)

# set primary y label
temp.set_ylabel('Tempurature (C)')
temp.tick_params('y', colors = 'red', labelsize =24)

# set x-axis limits as the min and max of the series
temp.set_xlim(date2num([df_w.index.min(), df_w.index.max()]))
temp.xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'))
temp.xaxis.set_major_locator(mdates.YearLocator(1, month=1, day=1))

temp.set_ylim(2,28)

season = temp.twinx()

season.set_ylabel('GPP 20th percent yearly max')
season.tick_params('y', colors = 'blue', labelsize =24)

season.scatter(df_d.index, SRO_20['GPP_MINCORRECTED_20th'], marker = '^',color = 'blue')

plt.show()
1 Answers

Consider using hlines instead of axhline if you want to use data coordinates instead of axes coordinates. Any normalization you manage to do will collapse the moment the user zooms in.

Related