python画图x轴为秒,Python Matplotlib-具有日期值的x轴的平滑绘图线

Im trying to smooth a graph line out but since the x-axis values are dates im having great trouble doing this. Say we have a dataframe as follows

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)

Then we plot the data

fig, axs = plt.subplots(1,1, figsize=(18,5))

x = df.index

y = df.value

axs.plot(x, y)

fig.show()

we get

zJha8.jpg

Now to smooth this line there are some usefull staekoverflow questions allready like:

But I just cant seem to get some code working to do this for my example, any suggestions?

解决方案

You can use interpolation functionality that is shipped with pandas. Because your dataframe has a value for every index already, you can populate it with an index that is more sparse, and fill every previously non-existent indices with NaN values. Then, after choosing one of many interpolation methods available, interpolate and plot your data:

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

rgyPg.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值