首页 > 解决方案 > Matplotlib 创建平滑图

问题描述

我正在使用Python 3.8,Matplotlib 3.2.2Scipy 1.5.0. 我是 Matplotlib 和 Pandas 的新手,但我已经到了那里。我在 Pandas Dataframe 中有一些气象数据,我可以在 x 轴上每 5 分钟绘制一次 24 小时气压和降雨与时间的关系图。我想平滑压力曲线,但不能让它工作。我已经在这里这里查看了教程,并且还查看了这个问题。这是未平滑的图表:气压和雨量与时间的关系图:

在此处输入图像描述

和代码:

-------- 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 是 Pandas Dataframe 的 df.index 中的 Datetimeindex 数组,y 是用于压力的浮点数组,z 是用于雨的浮点数组。我已经从上面的教程中尝试过:

-------- 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)

我必须将 x 中的时间转换为 UnixTime 否则我会收到错误,如果项目使曲线平滑,我还将数字加倍。当我这样做时,即使等待很长时间(超过 10 分钟),图表也不会出现。它卡在 plt.show 阶段。通常,图表会很快出现。任何帮助将非常感激。

标签: pythonpandasmatplotlibscipy

解决方案


推荐阅读