My code is using seaborn to draw a regression line with a timeseries data as the x axis, and whatever you want the y-axis to be. Since seaborn does not support this function directly, a dummy column has to be made first based on the timeseries (i.e. instead of using 2016-05-01, use 1,2,3,4,5... to represent the date. Then, plot the regression line using 1,2,3... as the x-axis and replace the 1,2,3 label with 2016-05-01, 2016-05-02...
def regplot_timeseries(df:pd.DataFrame, time_col:str, data_col:str, figsize=(14, 6), xlabel = '', ylabel = ''): # make a copy of the incoming data (think of the incoming data as an excel sheet visually) dfc = df.copy() # if it is a index, treat it slightly differently # add a column to the copy of the excel sheet for plotting purpose if time_col == 'index': dfc = dfc.sort_index() dfc['date_f'] = pd.factorize(dfc.index) + 1 mapping = dict(zip(dfc['date_f'], dfc.index.date)) else: dfc = dfc.sort_values(time_col_str) dfc['date_f'] = pd.factorize(dfc[time_col]) + 1 mapping = dict(zip(dfc['date_f'], dfc[time_col].dt.date)) # plotting fig, ax = plt.subplots() fig.set_size_inches(figsize, figsize) sns.regplot('date_f', data_col, data=dfc, ax=ax) labels = pd.Series(ax.get_xticks()).map(mapping).fillna('') ax.set_xticklabels(labels) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) # delete the copy to free up memory del dfc
I am new to functional programming, and from what I read, I shouldn't alter the data being passed in. In this case, I shouldn't alter
df, so I made a copy instead and deleted the copy at the end of the function. Is this the right to do it?