【问题标题】:Plot multiple distributions in Seaborn histogram在 Seaborn 直方图中绘制多个分布
【发布时间】:2021-06-23 15:51:33
【问题描述】:

我有一个包含四列的数据框df_sz,我想在 Seaborn 中以“并排”方式绘制每列的直方图,即直方图之间没有重叠。但是,当我运行以下脚本时,它会与直方图重叠:

sns.histplot(data=df_sz, bins=50, alpha=0.5, shrink=0.8, log_scale=True, multiple='layer')

我已经尝试了 multiple 参数的所有选项,但它们都不起作用。

有什么解决办法吗?我真的需要在这个情节中使用 Seaborn。 我附上了数据框的屏幕截图和生成的直方图 .

【问题讨论】:

    标签: python plot seaborn histogram


    【解决方案1】:

    multiple= 参数似乎与hue= 参数一起使用。为此,应将数据框转换为long form

    import matplotlib.pyplot as plt
    import seaborn as sns
    import pandas as pd
    import numpy as np
    
    df_sz = pd.DataFrame({'Ann1': (2 ** np.random.uniform(1, 20, 200)).astype(int),
                          'Ann2': (2 ** np.random.uniform(1, 20, 200)).astype(int),
                          'Ann3': (2 ** np.random.uniform(1, 20, 200)).astype(int),
                          'Ann4': (2 ** np.random.uniform(1, 20, 200)).astype(int)})
    
    fig, ax = plt.subplots(figsize=(20, 4)) # very wide figure to accomodate 200 bars
    sns.histplot(data=df_sz.melt(), x='value', hue='variable', bins=50,
                 alpha=0.5, shrink=0.8, log_scale=True, multiple='dodge', ax=ax)
    ax.legend_.set_title('') # remove the legend title (the name of the hue column)
    ax.margins(x=0.01) # less spacing
    plt.tight_layout()
    plt.show()
    

    【讨论】:

    • 完美运行!非常感谢。
    • 我认为这里不需要融化。所有色调逻辑(和功能)都用于宽格式数据,它只是隐含的。
    • @mwaskom 谢谢。我刚刚测试了开发版本,宽格式工作正常。在当前的 0.11.1 中,长格式似乎是必要的。
    • 哎呀,是的,我猜应该是this bug
    猜你喜欢
    • 2021-11-03
    • 2019-04-09
    • 1970-01-01
    • 1970-01-01
    • 2016-07-21
    • 1970-01-01
    • 2016-11-04
    • 2022-01-25
    相关资源
    最近更新 更多