Python seaborn 中的 tsplot 越界错误

tsplot out of bounds error in Python seaborn

我正在尝试将时间序列数据绘制为 seaborn 中的点,并按条件着色。我尝试了以下方法:

import matplotlib
import matplotlib.pylab as plt
import seaborn as sns
import pandas

df = pandas.DataFrame({"t": [0, 1],
                       "y": [1, 1],
                       "c": ["A", "B"]})
colors = {"A": "r", "B": "g"}
fig = plt.figure()
# this fails
sns.tsplot(time="t", value="y", condition="c", unit="c",
           data=df, err_style="unit_points", interpolate=False,
           color=colors)
plt.show()

错误是:

x_diff = x[1] - x[0]
IndexError: index 1 is out of bounds for axis 0 with size 1

但是如果我将数据绘制为:

# this works
sns.pointplot(x="t", y="y", hue="c", join=False, data=df)

然后就可以了。 pointplot 将时间视为分类数据,但这是不正确的。如何使用 tsplot 完成此操作?它应该给出与 pointplot 相同的结果,除了 x 轴 (t) 应该像时间一样定量缩放而不是分类。

更新

这是一个修改后的示例,它显示 tsplot 即使在大多数标签有多个观察结果时也会失败。在此 df 中,3 个条件中有 2 个具有多个观察值,但 1 个条件没有足以导致错误:

df = pandas.DataFrame({"t": [0, 1.1, 2.9, 3.5, 4.5, 5.9],
                       "y": [1, 1, 1, 1, 1, 1],
                       "c": ["A", "A", "B", "B", "B", "C"]})
colors = {"A": "r", "B": "g", "C": "k"}
print df
fig = plt.figure()
# this works but time axis is wrong
#sns.pointplot(x="t", y="y", hue="c", join=False, data=df)

# this fails
sns.tsplot(time="t", value="y", condition="c", unit="c",
           data=df, err_style="unit_points", interpolate=False,
           color=colors)
plt.show()

@mwaskom 建议制作普通情节。手动执行此操作很困难,而且容易出错,并且会重复 seaborn 已经完成的工作。 seaborn 已经有一种方法可以通过数据框中的各种功能来绘制和分面数据,我不想重现此代码。这是一种手动操作的方法,很麻烦:

# solution using plt.subplot
# cumbersome and error prone solution
# the use of 'set' makes the order non-deterministic
for l in set(df["c"]):
    subset = df[df["c"] == l] 
    plt.plot(subset["t"], subset["y"], "o", color=colors[l], label=l)

基本上我正在寻找类似 sns.pointplot 的东西,它使用数字而不是分类 x 轴。 seaborn 有这样的东西吗?另一种思考方式是将其视为 plt.scatterplt.plot.

的数据框感知版本

我认为问题真的是你的观察太少了。 2 个条件的 2 个观察意味着每个条件只有 1 个观察。对于时间序列图,这可能行不通。 x_diff = x[1] - x[0] 计算时间间隔长度,不能只对每组进行一次观察。

如果每组观察超过 1 个,即:

df = pandas.DataFrame({"t": [0, 1, 2, 3],
                       "y": [1, 1, 2, 4],
                       "c": ["A", "B", "A", "B"]})

它应该绘制得很好。