0

this is a bit detailed, but help appreciated. It's a slightly annoying feature of seaborn that regplot can't handle datetime axes. This is especially so when you want to use the lowess parameter, which estimates local means to give a curve (as opposed to line) that tracks changes in a plot. (This functionality is available in R, for instance.)

This is a problem for me because I have a linear plot that I'd like to smooth out but without using a rolling mean. This is my plot:

No Lowess line

To solve this problem, I took the index of my dataframe as the x-axis, and used statsmodels to calculate the lowess line as follows:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import statsmodels.api as sm

rated = pd.read_csv('filepath.csv')

rated['linear'] = rated.index

x = rated['linear']
y = rated['trust_num']

lowess = sm.nonparametric.lowess(y, x, frac=.2)


low_y = [i[1] for i in lowess]
low_x = [i[0] for i in lowess]

rated['low_y'] = low_y
rated['low_x'] = low_x

rated['low_y'] = low_y
rated['low_x'] = low_x

h = sns.lineplot(x = 'linear', y = 'trust_num', data = rated)
h = sns.lineplot(x = 'linear', y = 'low_y', data = rated, color = 'r')

This produces exactly what I'd like: Lowess line

The final step comes with assigning dates to the x-axis, which I do as follows:

labels = [i for i in rated['date']]
h.set_xticklabels(labels)

The result is a clustered x-axis, as below: bad dates

Fair enough, this is a common plotting problem. So I try to rotate my xtick labels:

plt.xticks(rotation=45)

But it makes no difference. Can anyone advise how I might declutter the axis? Seems a pain to nearly get there and fall at a seemingly simple problem!

Lodore66
  • 1,125
  • 4
  • 16
  • 34

0 Answers0