【问题标题】:Add quantile and mean lines in seaborn histogram subplots with loop使用循环在 seaborn 直方图子图中添加分位数和平均线
【发布时间】:2021-03-01 16:08:22
【问题描述】:

您好,我想在 seaborn 直方图子图中添加分位数和均值线。

示例数据:

import seaborn as sns
from matplotlib import pyplot as plt
penguins = sns.load_dataset("penguins")
penguins.dropna(inplace=True)
fig, axes = plt.subplots(2, 2, figsize=(20, 7))
plot_data = penguins[['bill_length_mm', 'bill_depth_mm', 'flipper_length_mm', 'body_mass_g']]
for col, ax in zip(plot_data, axes.flat):
    print(col, ax)
    sns.histplot(ax=ax, data=plot_data, x=plot_data[col], hue=penguins['sex'], multiple='stack')

将分位数线添加到单个子图:axes[0,0].axvline(plot_data['bill_length_mm'].quantile(0.25), 0, 1, color='red', ls='--')

我想为每个子图添加 0.25、0.5、0.75 分位数和平均值。

我试过了,但是不行

quantiles = [0.25, 0.5, 0.75]
colors = ['green', 'red', 'blue']
l = []
for col in plot_data.columns:
    for q, c in zip(quantiles, colors):
        l.append([col, q, plot_data.loc[:,col].quantile(q), c])

for l_, ax in zip(l, axes):
    ax.axvline(l_[2], 0, 1, color=l[3], ls='--')

【问题讨论】:

    标签: python pandas seaborn


    【解决方案1】:

    分别从要绘制的数据的统计中获取 25%、50% 和 75% 来绘制一条垂直线。请参考this

    import seaborn as sns
    from matplotlib import pyplot as plt
    
    penguins = sns.load_dataset("penguins")
    penguins.dropna(inplace=True)
    
    fig, axes = plt.subplots(2, 2, figsize=(20, 7))
    
    plot_data = penguins[['bill_length_mm', 'bill_depth_mm', 'flipper_length_mm', 'body_mass_g']]
    
    quantiles = ['25%','50%', '75%']
    colors = ['green', 'red', 'blue']
    
    for col, ax in zip(plot_data, axes.flat):
    #     print(col, ax)
        sns.histplot(ax=ax, data=plot_data, x=plot_data[col], hue=penguins['sex'], multiple='stack')
        desc = plot_data[col].describe()
    #     print(desc)
        for i in range(len(quantiles)):
            ax.axvline(desc[quantiles[i]], color=colors[i])
    

    【讨论】:

      【解决方案2】:

      你离得很近。您只需要在每个子图中为每个分位数颜色组合重复工作 axvline 解决方案。你正确地认为压缩它们是实现这一目标的一种方式。尽可能地坚持你的尝试:

      ...
      sns.histplot(ax=ax, data=plot_data, x=plot_data[col], hue=penguins['sex'], multiple='stack')
      for q, c in zip(quantiles, colors):
          ax.axvline(plot_data[col].quantile(q), 0, 1, color=c, ls='--')
      ...
      

      示例输出:

      【讨论】:

        猜你喜欢
        • 2021-08-09
        • 2022-06-11
        • 2019-01-21
        • 2021-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-19
        相关资源
        最近更新 更多