Skip to content

Instantly share code, notes, and snippets.

@yanniskatsaros
Created April 22, 2020 16:45
Show Gist options
  • Save yanniskatsaros/3af5fa1aec002b43931723a1fd33fa79 to your computer and use it in GitHub Desktop.
Save yanniskatsaros/3af5fa1aec002b43931723a1fd33fa79 to your computer and use it in GitHub Desktop.
LOWESS (Locally Weighted Scatterplot Smoothing) example with statsmodels and plotly
"""
References
----------
- https://www.statsmodels.org/stable/generated/statsmodels.nonparametric.smoothers_lowess.lowess.html#statsmodels.nonparametric.smoothers_lowess.lowess
- https://plotly.com/python/line-and-scatter/#scatter-and-line-plot-with-goscatter
"""
import numpy as np
import plotly.graph_objects as go
from statsmodels.nonparametric.smoothers_lowess import lowess
x = np.random.uniform(low = -2*np.pi, high = 2*np.pi, size=500)
y = np.sin(x) + np.random.normal(size=len(x))
# fit LOWESS using a fraction of 0.2, 0.4, ... 1.0 of the data
fits = [
(i/10,
lowess(y, x, frac=i/10, return_sorted=False)
) for i in range(2, 11, 2)
]
# visualization
fig = go.Figure()
fig.add_trace(
go.Scatter(
x=x,
y=y,
name='Sine',
mode='markers'
)
)
for frac, yhat in fits:
fig.add_trace(
go.Scatter(
x=x,
y=yhat,
name=f'LOWESS - frac = {frac}',
mode='markers'
)
)
fig.show()
@yanniskatsaros
Copy link
Author

Plot Output

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment