按时间戳绘制 numpy 数组的直方图 [英] plotting a histogram of a numpy array by timestamp

查看:51
本文介绍了按时间戳绘制 numpy 数组的直方图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数组有成对的 Unix 时间戳和值.

My array has pairs of unix timestamps and values.

[[  1.40170249e+09   9.00000000e+01]
 [  1.40170249e+09   9.10000000e+01]
 [  1.40170249e+09   9.20000000e+01]
 ..., 
 [  1.41149703e+09   1.09000000e+02]
 [  1.41149703e+09   1.06000000e+02]
 [  1.41149703e+09   1.06000000e+02]]

我设法用 pyplot.hist(array[:,1]); 绘制了整个第二列的直方图;pyplot.show().但我真正想做的是按天对 array[:,1] 进行分类(由数组 [:,0] 中的 unix 时间戳派生),并将它们绘制为堆叠直方图,每个(彩色)堆栈代表一天.这样做的最佳方法是什么?

I have managed to plot a histogram of the whole second column with pyplot.hist(array[:,1]); pyplot.show(). But what I really want to do, is to bin array[:,1] by day (as derived by the unix timestamps in array[:,0]), and plot these as a stacked histogram, with each (colored) stack representing a day. What might be the best way to do that?

推荐答案

既然你有一个 groupby 参与其中,那么使用 pandas 是有意义的:>

Since you have a groupby involved in this, it will make sense to use pandas:

In [192]:
import pandas as pd
import numpy as np
import time
A = np.array([[  1.40170249e+09,   9.00000000e+01],
             [  1.40170249e+09,   9.10000000e+01],
             [  1.40170249e+09,   9.20000000e+01],
             [  1.41149703e+09,   1.09000000e+02],
             [  1.41149703e+09,   1.06000000e+02],
             [  1.41149703e+09,   1.06000000e+02]])
df = pd.DataFrame(A, columns=['date', 'val'])
df['date'] = df.date.map(lambda x: time.gmtime(x))
print df
                                   date  val
0    (2014, 6, 2, 9, 48, 10, 0, 153, 0)   90
1    (2014, 6, 2, 9, 48, 10, 0, 153, 0)   91
2    (2014, 6, 2, 9, 48, 10, 0, 153, 0)   92
3  (2014, 9, 23, 18, 30, 30, 1, 266, 0)  109
4  (2014, 9, 23, 18, 30, 30, 1, 266, 0)  106
5  (2014, 9, 23, 18, 30, 30, 1, 266, 0)  106
In [193]:

grp_obj = df.groupby(df.date.map(lambda x: time.strftime('%Y-%m-%d', x)))
plt.hist([value.val.values for grp, value in grp_obj],
         stacked=True, 
         label=[grp for grp, value in grp_obj])
plt.legend()
Out[193]:
<matplotlib.legend.Legend at 0x10902d950>

而且您还需要按年-月-日对它们进行分组,以避免将不同月份/年份中的日期组合在一起.

And also you need to group them by year-month-day in order to avoid having days in different months/years grouped together.

这篇关于按时间戳绘制 numpy 数组的直方图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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