Seaborn时间序列情节

时间:2017-05-16 19:02:52

标签: python pandas plot time-series seaborn

我已经清理了一个数据集并达到了我的pandas数据框的样子:

aggregated_df = another_df.groupby(['datetime_x', 'my_category'])['my_value'].mean()
aggregated_df.head(3)

datetime_x  my_category
2011-10-01  foo         2090.91
2011-12-22  bar         2545.45
2012-01-06  foo         1944.44
Name: my_value, dtype: float64

当我尝试生成一个包含多个时间序列的图表(每个时间序列代表my_category个字段之一)时,我得到:ValueError: arrays must all be same length

sns.tsplot(
    data=aggregated_df, 
    time="datetime_x", 
    value="my_value",
    condition="my_category",
)

我认为原因是因为每个类别在被视为熊猫系列数组时,其长度可能与其他类别不同。也许是因为缺少某些日期,但我不确定这是什么原因,如果情况确实如此,我觉得很奇怪。

我还将seaborn condition=方法的tsplot参数设置为我认为应该是“分类变量”的位置(在我的情况下是my_category列),但是可能是我误解了如何使用tsplot

另外,groupby的效果是我得到了一个带有嵌套MultiIndex的pandas levels,但我不确定这是seaborn期望的格式,即使它看起来很好我正在尝试绘制由其中一列(my_category)标记的多个时间序列。

我做错了什么? 如何在同一个图表上绘制多个时间序列,每个时间序列都是从分类列中标记出来的?

1 个答案:

答案 0 :(得分:2)

tsplot需要每个条件的“时间”相同,即对于每个条件,您需要在同一时间单位对数据进行采样。

从tsplot docstring中查看此示例中数据框的结构,这将使其更清晰:

gammas = sns.load_dataset("gammas")
ax = sns.tsplot(time="timepoint", value="BOLD signal",
                unit="subject", condition="ROI",
                data=gammas)

我担心,tsplot在这种情况下对你没有帮助。

这个答案可能对您有所帮助,因为matplotlib和pandas的良好组合可以获得类似tsplot的行为:ref

相关问题