非类别数据帧到seaborn绘图的分类数据boxplots、swarmplots、stripplots

2024-04-26 11:43:14 发布

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

我在使用分类数据图时遇到了困惑,这可能是因为我不太理解这个概念。在

我有一个数据帧:

      A         B         C
 0  1.438161 -0.210454 -1.983704
 1 -0.283780 -0.371773  0.017580
 2  0.552564 -0.610548  0.257276
 3  1.931332  0.649179 -1.349062
 4  1.656010 -1.373263  1.333079
 5  0.944862 -0.657849  1.526811

我可以很容易地用seaborn绘制每列的箱线图:

^{pr2}$

但是swarmplot和stripplots都不起作用,我想是因为需要分类数据吗?在

     value   indx       
   1.438161    A
  -0.283780    A
       ...
   0.552564    B
   1.931332    B
       ...
   1.656010    C
   0.944862    C

有没有一种我不知道的简单快捷的方法?在

https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.swarmplot.html


Tags: 数据方法https概念value绘制分类seaborn
2条回答

我想您需要参数data

sns.boxplot(data=df)

Docs

data : DataFrame, array, or list of arrays, optional

Dataset for plotting. If x and y are absent, this is interpreted as wide-form. Otherwise it is expected to be long-form.

graph

IIUC,您可以使用^{}将其中一个变量转换为分类格式,以帮助绘制swarmplots和{}。在

In [3]: df_sns = pd.melt(df, value_vars=['A', 'B', 'C'])

In [4]: df_sns
Out[4]: 
   variable     value
0         A  1.438161
1         A -0.283780
2         A  0.552564
3         A  1.931332
4         A  1.656010
5         A  0.944862
6         B -0.210454
7         B -0.371773
8         B -0.610548
9         B  0.649179
10        B -1.373263
11        B -0.657849
12        C -1.983704
13        C  0.017580
14        C  0.257276
15        C -1.349062
16        C  1.333079
17        C  1.526811

In [5]: sns.swarmplot(x='variable', y='value', data=df_sns)
Out[5]: <matplotlib.axes._subplots.AxesSubplot at 0x268db2a6e10>

enter image description here

相关问题 更多 >