Python seaborn中的tsplot越界错误

2024-04-24 23:55:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将时间序列数据绘制成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()

错误是:

^{pr2}$

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

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

那就行了。pointplot将时间视为分类数据,但这并不适合。如何使用tsplot完成此操作?它应该给出与pointplot相同的结果,除了x轴(t)应该像时间一样量化而不是分类。在

更新

下面是一个修改后的示例,它显示tsplot即使对大多数标签有多个观察结果,也会失败。在这个数据框中,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.scatter或{}的数据帧感知版本。在


Tags: 数据方法importfalsedfdata时间unit
1条回答
网友
1楼 · 发布于 2024-04-24 23:55:49

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

如果每组有一次以上的观察,即:

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

情节应该很好。在

相关问题 更多 >