简体   繁体   English

在Python中绘制直方图的时间序列

[英]Plot timeseries of histograms in Python

I'm trying to plot a time-series of histograms in Python. 我正在尝试用Python绘制时间序列的直方图。 There has been a similar question about this, but in R . 有一个类似的问题,但在R。 So, basically, I need the same thing, but I'm really bad in R. There are usually 48 values per day in my dataset. 所以,基本上,我需要相同的东西,但我在R中真的很糟糕。我的数据集中每天通常有48个值。 Where - 9999 represents missing data. 其中 - 9999表示缺少数据。 Here's the sample of the data. 这是数据的样本。

I started with reading in the data and constructing a pandas DataFrame . 我开始阅读数据并构建一个pandas DataFrame

import pandas as pd
df = pd.read_csv('sample.csv', parse_dates=True, index_col=0, na_values='-9999') 
print df

<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 336 entries, 2008-07-25 14:00:00 to 2008-08-01 13:30:00
Data columns (total 1 columns):
159.487691046    330  non-null values
dtypes: float64(1)

Now I can group the data by day: 现在我可以按天分组数据:

daily = df.groupby(lambda x: x.date())

But then I'm stuck. 但后来我被卡住了。 I don't know how to use this with matplotlib to get my timeseries of histograms. 我不知道如何使用matplotlib来获取直方图的时间序列。 Any help appreciated, not necessarily using pandas . 任何帮助表示赞赏,不一定使用pandas

Make a histogram and use matplotlib's pcolor . 制作直方图并使用matplotlib的pcolor

We need to bin the groups uniformly, so we make bins manually based on the range of your sample data. 我们需要统一分组,因此我们根据样本数据的范围手动制作分档。

In [26]: bins = np.linspace(0, 360, 10)

Apply histogram to each group. histogram应用于每个组。

In [27]: f = lambda x: Series(np.histogram(x, bins=bins)[0], index=bins[:-1])

In [28]: df1 = daily.apply(f)

In [29]: df1
Out[29]: 
            0    40   80   120  160  200  240  280  320
2008-07-25    0    0    0    3   18    0    0    0    0
2008-07-26    2    0    0    0   17    6   13    1    8
2008-07-27    4    3   10    0    0    0    0    0   31
2008-07-28    0    7   15    0    0    0    0    6   20
2008-07-29    0    0    0    0    0    0   20   26    0
2008-07-30   10    1    0    0    0    0    1   25    9
2008-07-31   30    4    1    0    0    0    0    0   12
2008-08-01    0    0    0    0    0    0    0   14   14

Following your linked example in R, the horizontal axis should be dates, and the vertical axis should be the range of bins. 在R中的链接示例之后,水平轴应为日期,垂直轴应为区间范围。 The histogram values are a "heat map." 直方图值是“热图”。

In [30]: pcolor(df1.T)
Out[30]: <matplotlib.collections.PolyCollection at 0xbb60e2c>

在此输入图像描述

It remains to label the axes. 它仍然是标记轴。 This answer should be of some help. 这个答案应该有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM