Python Matplotlib-具有日期值的x轴的平滑绘图线 [英] Python Matplotlib - Smooth plot line for x-axis with date values

查看:442
本文介绍了Python Matplotlib-具有日期值的x轴的平滑绘图线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使图形线条平滑,但是由于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)

然后我们绘制数据

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

我们得到

现在要使这条线平滑,可以使用一些有用的staekoverflow问题,例如:

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

  • Generating smooth line graph using matplotlib,
  • Plot smooth line with PyPlot
  • Creating numpy linspace out of datetime

但是对于我的示例,我似乎无法获得一些代码来完成此工作,有什么建议吗?

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

推荐答案

您可以使用pandas附带的插值功能.因为您的数据框已经具有每个索引的值,所以可以使用稀疏的索引填充它,并使用NaN值填充每个先前不存在的索引.然后,在选择许多插值之一后可用的方法,插值并绘制数据:

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

这篇关于Python Matplotlib-具有日期值的x轴的平滑绘图线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆