【问题标题】:Plot horizontal bar plot with seaborn用 seaborn 绘制水平条形图
【发布时间】:2019-05-29 18:07:40
【问题描述】:

我正在爬取一个目录并读取一堆文件并解析它们。我需要的只是获取数据框的大小。我通过使用len(df.index) 来做到这一点。

每个目录有 10 个文件,编号从 0 到 9。我将所有这些 len(df.index) 添加到数据框中,其中字母['A', 'B', 'C', 'D'] 来自类别列表。这些值由df2.loc[seed,nd] = len(df.index) 添加到数据框中。生成的数据框如下:

         A         B         C       D
0  10515.0  160592.0  221621.0  198884.0
1   9777.0  161307.0  222064.0  199841.0
2  10957.0  159954.0  219553.0  198622.0
3  12731.0  157862.0  221250.0       NaN
4  11765.0  162177.0       NaN       NaN
5   8849.0  155631.0       NaN       NaN
6  10549.0  160976.0       NaN       NaN
7   8694.0  158953.0       NaN       NaN
8  11696.0  160952.0       NaN       NaN
9  10590.0  161046.0       NaN       NaN

在我的脚本中,我在 for 循环中抓取了两个目录,XZ,从而生成了两个与上述类似的数据帧。

问题是我正在尝试使用 Seaborn 水平条形图绘制此数据框

sns.barplot(data=df2)

但是我不知道如何指定类别,比如显示here

如何做到这一点?我需要更改我的数据框格式吗?

我希望得到这样的结果(来自 MS Excel)

【问题讨论】:

  • 这 4 个类别的 X 和 Z 是什么?
  • 不缺少指定类别的列?
  • 对不起,我忘了说我爬了两个目录,Z 和 X。我会编辑帖子

标签: python pandas seaborn


【解决方案1】:

您可以使用两个DataFrames的concat和参数keys指定组,然后通过melt重塑,最后使用参数hue指定组:

dfs = [df21, df22]

df = pd.concat(dfs, keys=('X','Z')).reset_index(level=0).melt('level_0')
sns.barplot(x='value', y='variable', hue='level_0', data=df)

【讨论】:

    【解决方案2】:

    我认为这可以使用seabon's barplot functionorient 属性来实现。

    示例 -

    import pandas as pd
    import numpy as np
    import seaborn as sns
    df = pd.DataFrame(np.random.randint(0,10,size=(10, 4)), columns=list('ABCD'))
    sns.barplot(data=df, orient = 'h')
    

    【讨论】:

      猜你喜欢
      • 2017-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-28
      • 2017-05-24
      • 1970-01-01
      • 2018-09-24
      • 2020-07-03
      相关资源
      最近更新 更多