# Drawing a regression line with a timeseries

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)[0] + 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])[0] + 1
mapping = dict(zip(dfc['date_f'], dfc[time_col].dt.date))

# plotting
fig, ax = plt.subplots()
fig.set_size_inches(figsize[0], figsize[1])
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?

• You don't need dfc, dfc.sort_index() and dfc.sort_values(time_col_str) both make a copy of the data. They don't perform an in-place sort.
• del dfc isn't needed, Python will perform that action at the end of the function anyway. Also I don't think it's doing what you think it's doing. I may be wrong, but since variables in Python are like names, when you're using del, you're just removing one name tag to the object.
Deletion of a name removes the binding of that name from the local or global namespace, depending on whether the name occurs in a global statement in the same code block.