gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 16:20:33 25 4
gpt4 key购买 nike

我试图平滑图表线,但由于 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 问题,例如:

但我似乎无法让一些代码为我的示例执行此操作,有什么建议吗?

最佳答案

您可以使用 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

关于Python Matplotlib - 具有日期值的 x 轴的平滑绘图线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40559971/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com