首页 文章

Python Matplotlib - 带有日期值的x轴的平滑绘图线

提问于
浏览
3

我试图平滑图形线,但由于x轴值是日期,我很难做到这一点 . 假设我们有一个如下数据帧

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
%matplotlib inline

startDate = '2015-05-15'
endDate = '2015-12-5'
index = pd.date_range(startDate, endDate)
data = np.random.normal(0, 1, size=len(index))
cols = ['value']

df = pd.DataFrame(data, index=index, columns=cols)

然后我们绘制数据

fig, axs = plt.subplots(1,1, figsize=(18,5))
x = df.index
y = df.value
axs.plot(x, y)
fig.show()

我们得到

enter image description here

现在为了平滑这一行,有一些有用的staekoverflow问题就像:

但我似乎无法得到一些代码来为我的例子做任何建议?

1 回答

  • 3

    您可以使用 pandas 附带的插值功能 . 因为您的数据帧已经为每个索引都有一个值,您可以使用更稀疏的索引填充它,并使用 NaN 值填充每个以前不存在的索引 . 然后,在选择多个插值methods available之一后,插入并绘制数据:

    index_hourly = pd.date_range(startDate, endDate, freq='1H')
    df_smooth = df.reindex(index=index_hourly).interpolate('cubic')
    df_smooth = df_smooth.rename(columns={'value':'smooth'})
    
    df_smooth.plot(ax=axs, alpha=0.7)
    df.plot(ax=axs, alpha=0.7)
    fig.show()
    

    enter image description here

相关问题