使用误差线绘制熊猫(时间序列)数据框

时间:2013-09-23 23:56:20

标签: python plot pandas time-series standard-error

我有一个pandas数据帧,表示来自地区,主题和使用不同度量的数据的几个不同时间序列。 pandas pivot-table允许我轻松地转移到数据的特定子集并绘制它。但是,我不能为我的生活弄清楚如何在剧情中添加误差条。由于旋转的行为取表格的指定部分的平均值或值,我写了一个小的labmda函数来制作第二个表,它与包含标准错误的第一个表完全对齐。但是,我无法通过添加具有这些值的误差条来更新绘图。我相信我可以通过将表中的数据提取到向量中来解决这个问题,但这会破坏数据框的有用性。

示例数据:

import numpy as np 
import matplotlib.pyplot as plt
import pandas as pd 

# datafile
fileIN = 'model_data.txt' 

# read in data 
data = pd.read_table(fileIN, sep='\t')

此数据如下所示:

In [9]: data.head()
Out[9]: 
  subject     drug group  TR     mask     data         measure
0  sub1S1  placebo    h1   1  region1  0.33333  total_accuracy
1  sub1S1  placebo    h1   1  region1  0.34615            facc
2  sub1S1  placebo    h1   1  region1  0.42308            sacc    
3  sub1S1  placebo    h1   1  region1  0.23077            dacc
4  sub1S1  placebo    h1   1  region1 -0.26923           fdist

# select just what we want to see 
stage1 = data[data['measure'] == 'total_accuracy']

这个新框架如下所示:

In [19]: stage1.head()
Out[19]: 
   subject     drug group  TR     mask     data         measure
0   sub1S1  placebo    h1   1  region1  0.33333  total_accuracy
10  sub1S1  placebo    h1   2  region1  0.39744  total_accuracy
20  sub1S1  placebo    h1   3  region1  0.44872  total_accuracy
30  sub1S1  placebo    h1   4  region1  0.48718  total_accuracy
40  sub1S1  placebo    h1   5  region1  0.48718  total_accuracy

表示时间的TR正在按预期进行。现在,我对我现在不感兴趣的所有会话药物和组数据采取均值,但将区域数据保留为列并保留时间:

table = pd.pivot_table(stage1,values='data',rows=['TR'],cols=['mask'])

结果:

    mask   region1   region2   region3
TR                                
1     0.302465  0.226020  0.227680
2     0.353040  0.277540  0.329060
3     0.341645  0.340215  0.378680
4     0.354700  0.303180  0.377970
5     0.404085  0.333330  0.320985
6     0.353750  0.409310  0.308165

这很好,因为现在我做的时候

ax = table.plot()

并设置我想要的所有属性,然后执行plt.show(),这正是我想要的。但是我需要在此图表上获取错误栏。如果我这样做:

# lambda function to get standard error
ste = lambda x: np.std(x) / np.sqrt(len(x))
# get a table of the standard errors 
ste_table = pd.pivot_table(stage1,values='data',rows=['TR'],cols=['mask'],aggfunc = ste)

然后我得到:

In [26]: ste_table
Out[26]: 
mask   region1   region2   region3
TR                                
1     0.021825  0.014771  0.047511
2     0.031396  0.030384  0.075547
3     0.075713  0.022327  0.049526
4     0.093678  0.048515  0.022832
5     0.058757  0.000000  0.008729

这是标准错误的正确值。但我无法找到一种方法来使用错误栏更新绘图。据我所知,我可以提取矢量,然后使用plt.errorbar绘制它们,但我觉得应该有一种简单的方法来告诉熊猫数据帧这些是相关的错误,我希望它们在图上。任何帮助是极大的赞赏。 (请原谅这篇文章的长度!我想彻底解释一下,我在这个论坛上是一个总菜鸟。另外,堆栈溢出不允许我用错误栏,错误栏或条形标记这个)

0 个答案:

没有答案