Python:使用 groupby 绘制熊猫数据框 - 奇怪的输出

Python: plot panda dataframe with groupby - weird output

我有一个数据框(对象类型,出于事先在某些步骤中插入列表的原因),其中三列看起来像这样

    data  stimulus trial
0   2     -2       1
1   2     -2       2
2   2     -2       3
3   2     -2       4
4   2     -2       5
5   2     -2       6
6   1     -2       7
...
159 1     2.5      16

目前我正在使用 seaborn,但我在将适当的图例插入到我的情节中时遇到困难。

# spi_num is my dataframe
sns.swarmplot(x="stimulus", y="data", data=spi_num.astype(np.float), edgecolor="black", linewidth=.9)
sns.boxplot(x="stimulus", y="data", data=spi_num.astype(np.float), saturation=1)

所以我有两个问题。我如何顺利地将图例与 seaborn 集成?我如何使用 pandas plot 命令得到这个图?我以为我需要这样的东西:

spi_num.astype(np.float).groupby('stimulus').plot.box()

但随后我得到 10 个数字(每个刺激一个),每个 xlabel 有 3 个箱线图,即 "data"、"stimulus" 和 "trial"。这不应该给我一个如上所示的情节吗?至少 he does it like this .


构建我的数据框

trial_vec    = np.tile(np.arange(16)+1, 10)     
stimulus_vec = np.repeat([-2., -1.75, -1., -0.75, -0.5,  0.5,  1.,  1.25,  1.75,  2.5 ], 16)                  
data_vec     = np.random.randint(0, 16, size=160)
spi_num      = pd.DataFrame({'trial': trial_vec, 'stimulus': stimulus_vec, 'data': data_vec}).astype('object')

您可以使用DataFrame.boxplot得到想要的箱形图

spi_num.astype(np.float).boxplot(column="data", by="stimulus")