使用matplotlib绘制d中有间隙的数据帧

2024-10-01 09:39:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个如下的数据帧:

import pandas as pd
import numpy as np
period0 = pd.date_range('1/1/2011', periods=50, freq='D')
period1 = pd.date_range('18/5/2012', periods=50, freq='D')
period2 = pd.date_range('7/11/2014', periods=50, freq='D')
df = pd.concat((pd.DataFrame(period0), pd.DataFrame(period1), pd.DataFrame(period2)), axis=0)

df['y'] = pd.DataFrame(np.random.rand(150,1))

这些日期和时段是任意选择的,以创建一些间隙和日期。你知道吗

当我尝试绘制数据帧时,matplotlib会在日期间隔之间自动绘制一条线:

plt.plot(df[0], df['y'])

结果: enter image description here

我也试过dotplot。但这并没有阻止绘图创建线条:

plt.plot(df[0], df['y'], ':')

结果: enter image description here

我还发现了一个relevant question。不幸的是,它没有解决我的问题。你知道吗

那么,我该怎么办?你知道吗


Tags: 数据importdataframedfdateasnp绘制
2条回答

如果无法修改现有索引,可以尝试:

df.groupby(pd.Grouper(key=0, freq='1D'))['y'].last().plot()

您应该定义不希望被视为NaN的值:

https://matplotlib.org/examples/pylab_examples/nan_test.html

例如:

df.index = df[0].astype('datetime64')
#defining df[0] as index

idx = pd.date_range(start = '1/1/2011', end = max(period2), freq='D')
#creating new index

df = df.reindex(idx)
#reindexing df - it preserves values from 'y'

plt.plot(df.index, df['y'])
#creating plot

相关问题 更多 >