1

I want to create a plot showing both the real data and a smoothed version of the data. Now, I am using the following script:

import pandas as pd
import matplotlib.pyplot as plt

# DataFrame of 321 values
df = pd.read_csv('data.csv')
r = df.rolling(window=10, center=True, on='Value').mean()

fig = plt.figure()
ax = df['Value'].plot(style='--', c='b', alpha=0.5)
r.plot(ax=ax, legend=0, c='b')
plt.show()

However, I would like this to work similarly to e.g. TensorBoard. There, you specify a smoothing parameter between 0 and 1 which changes the window of the rolling mean, 0 being no smoothing and 1 being extreme smoothing. How is this done? Can I also do this in Python?

VMAtm
  • 27,943
  • 17
  • 79
  • 125
JNevens
  • 11,202
  • 9
  • 46
  • 72

1 Answers1

1

It seems that you can use scipy.interpolate package to add smoothness to your data, something like this:

from scipy.interpolate import spline

# 300 represents number of points to make between T.min and T.max
# you can use other number to adjust smoothness
axnew = np.linspace(df['Value'].min(), df['Value'].max(), 300)

power_smooth = spline(df['Value'], df['y_Value'], axnew)

plt.plot(xnew, power_smooth)
plt.show()

Sample from docs:

Cubic-spline

>>> x = np.arange(0, 2 * np.pi + np.pi / 4, 2 * np.pi / 8)
>>> y = np.sin(x)
# s parameter for adjust the smoothness
>>> tck = interpolate.splrep(x, y, s=0)
>>> xnew = np.arange(0, 2 * np.pi, np.pi / 50)
>>> ynew = interpolate.splev(xnew, tck, der=0)

enter image description here

Related question: Plot smooth line with PyPlot

Update: @ImportanceOfBeingErnest noticed that spline is depreciated in the newest version of scipy, so you should investigate the splev and splrep. Some samples can be found here.

Community
  • 1
  • 1
VMAtm
  • 27,943
  • 17
  • 79
  • 125