0

I am using Python 3.8, Matplotlib 3.2.2 and Scipy 1.5.0. I am new to Matplotlib and Pandas, but am getting there. I have some meterological data in a Pandas Dataframe and I can draw a graph of 24hrs of Barometric Pressure and Rain against Time every 5 mins on the x axis. I would like to smooth the Pressure Curve, but cannot get it to work. I have looked at the tutorial here and here and also looked at this question amongst others. Here is the unsmoothed graph: Plot of Barometric Pressure and Rain against Time:

enter image description here

and the code:

-------- snip --------
ax_graph_pressure.plot(x, y, linewidth=0.5, color='#C00000')
ax_graph_rain.bar(x, z, width=0.002, color='#FF0000')
ax_graph_pressure.grid(which='major', axis='y')
-------- snip --------
plt.show(dpi=96)

x is a Datetimeindex array from the df.index of the Pandas Dataframe and y is an array of Floats for Pressure and z in an array of floats for Rain. I have tried this from the tutorials above:

-------- snip --------
unix_time = []
# convert to Unix timestamp
for xx in df.index:
    unix_time.append(xx.replace(tzinfo=timezone.utc).timestamp())
xnew = np.linspace(unix_time[0], unix_time[len(unix_time) - 1], num = 576, endpoint=True)
f2 = interp1d(unix_time, y, kind='cubic')
ax_graph_pressure.plot(xnew, f2(xnew), linewidth=0.5, color='#C00000')
ax_graph_rain.bar(x, z, width=0.002, color='#FF0000')
ax_graph_pressure.grid(which='major', axis='y')
-------- snip --------
plt.show(dpi=96)

I had to convert the time in x to UnixTime or I get an error, I also double the number if items to smooth the curve. When I do this the graph does not appear even after a long wait (more than 10 mins). It gets stuck at the plt.show stage. Normally the graphs appears very quickly. Any help would be much appreciated.

Zephyr
  • 11,891
  • 53
  • 45
  • 80
themetman
  • 51
  • 6
  • 1
    you probably want a moving average, not an interpolation. – mikuszefski Jun 30 '20 at 07:54
  • 1
    Alternatively you can look into applying a savgol filter: http://scipy.github.io/devdocs/generated/scipy.signal.savgol_filter.html#scipy.signal.savgol_filter – Timo Jun 30 '20 at 08:15
  • 1
    You need a smoothing window, in your case a moving average would be OK. Pandas having a tool for everything, please see [this answer](https://stackoverflow.com/a/40060995/2749397) to see how it's simple to add a new column, containing the running average, to your dataframe. – gboffi Jun 30 '20 at 09:06
  • Thank you @gboffi The more I find out about Pandas the more magical it becomes! `df['PressureSmoothed'] = df.Pressure.rolling(window=5).mean()` Produced a nice smooth result. How easy was that!!!! – themetman Jun 30 '20 at 16:54

0 Answers0