【问题标题】:Seaborn columnwise violinplotSeaborn 列式小提琴图
【发布时间】:2023-03-31 15:50:01
【问题描述】:

我有一个字典 d,它列出了数字的出现:

{'item1': [42, 1, 2, 3, 42, 2, 1, 1, 1, 1, 1],
 'item2': [2, 5],
 'item3': [5, 1, 7, 2, 7, 1, 42, 2, 9]}

然后我将其转换为 DataFrame 计算这些出现次数:

df = pd.DataFrame.from_dict({k: dict(Counter(v)) for k, v in d.items()})

    item1  item2  item3
42    2.0    NaN    1.0
1     6.0    NaN    2.0
2     2.0    1.0    2.0
3     1.0    NaN    NaN
5     NaN    1.0    1.0
7     NaN    NaN    2.0
9     NaN    NaN    1.0

如何使用seaborn.violinplot 绘制从d 派生的此数据帧或其他一些数据帧,以便数据帧中的每一列根据每列值及其各自索引提供的数据表示图中的小提琴?

我尝试了多种组合,我认为这在直觉上是最接近的,但不幸的是仍然失败:

sns.violinplot(x=df.keys(), y=df.index, data=df)

【问题讨论】:

    标签: python pandas dataframe plot seaborn


    【解决方案1】:

    下面的代码创建了情节:

    # Import libraries
    import pandas as pd
    import collections
    import seaborn as sns
    
    # Create dictionary
    d = {'item1': [42, 1, 2, 3, 42, 2, 1, 1, 1, 1, 1],
     'item2': [2, 5],
     'item3': [5, 1, 7, 2, 7, 1, 42, 2, 9]}
    
    # Create DataFrame and melt
    df = pd.DataFrame.from_dict({k: dict(collections.Counter(v)) for k, v in d.items()})
    df = df.melt()
    
    # Plot
    sns.violinplot(x="variable", y="value", data=df)
    

    【讨论】:

      【解决方案2】:

      这样就够了

      from collections import Counter
      d = {'item1': [42, 1, 2, 3, 42, 2, 1, 1, 1, 1, 1],
           'item2': [2, 5],
           'item3': [5, 1, 7, 2, 7, 1, 42, 2, 9]}
      df = pd.DataFrame.from_dict({k: dict(Counter(v)) for k, v in d.items()})
      
      sns.violinplot(data=df)
      

      【讨论】:

        【解决方案3】:

        DataFrame 传递给seaborn.violinplot,因此每个系列(列)都单独绘制:

        sns.violinplot(data=df)
        

        【讨论】:

          猜你喜欢
          • 2017-05-25
          • 2021-08-29
          • 2018-02-18
          • 2021-10-14
          • 2018-01-15
          • 2021-02-23
          • 2016-03-10
          • 2020-07-03
          • 1970-01-01
          相关资源
          最近更新 更多