【问题标题】:Use matplotlib to plot dataframe that has gaps in date使用 matplotlib 绘制日期有间隙的数据框
【发布时间】:2019-01-07 05:56:27
【问题描述】:

我有一个如下的数据框:

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'])

结果:

我也试过dotplot。但这并没有阻止情节创建线:

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

结果:

我还找到了relevant question。不幸的是,它并没有解决我的问题。

那么,我该怎么办?

【问题讨论】:

  • 您是否考虑过使用散点图而不是线图?
  • 感谢您的建议。我试试看。

标签: python pandas matplotlib


【解决方案1】:

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

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

【讨论】:

  • 哇!它奇迹般地做到了我想要的。感谢您的回答。
【解决方案2】:

您应该将不希望看到的值定义为 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

【讨论】:

  • 实际上我无法为它编写函数。这对我来说有点难,因为我有多个这样的数据框。能否请您添加一些伪代码?
  • 代码有效。感谢这个有价值的代码。对此,我真的非常感激。但是当我尝试多次运行代码时,我得到了这个错误:ValueError: cannot reindex from a duplicate axis
  • @ImportanceOfBeingErnest reindex(idx) 添加新索引,对于 df['y] 中没有数据的行会产生 NaN
  • 我之前的评论是为了帮助改进答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-04
  • 1970-01-01
  • 2019-05-14
  • 2016-11-11
  • 1970-01-01
相关资源
最近更新 更多