Seaborn 时间序列图

Seaborn timeseries plot

我清理了一个数据集并达到了我的 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",
)

我认为原因是因为每个类别,当被视为一个 pandas 系列数组时,可能具有与其他类别不同的​​长度。可能是因为少了一些日期,但我不确定是不是这个原因,如果是这样的话我觉得很奇怪。

我还将 seaborn tsplot 方法的 condition= 参数设置为我认为 "categorical variable" 的位置(在我的例子中是 my_category 列), 但可能是我误解了如何使用 tsplot.

此外,groupby 的效果是我得到一个 pandas MultiIndex 嵌套 levels,但我不确定这是 seaborn 期望的格式,尽管它对我来说看起来不错,因为我正在尝试绘制由其中一列 (my_category) 标记的多个时间序列。

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

tsplot 需要每个条件的 "time" 相同,即对于每个条件,您需要在相同的时间单位采样数据。

从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