【问题标题】:Arrange boxplots as a grid with seaborn `FacetGrid`使用 seaborn `FacetGrid` 将箱线图排列为网格
【发布时间】:2020-02-17 15:00:19
【问题描述】:

我有一个包含三列 Features, CV-fold, Accuracy, Network 的数据框。我想为每个网络制作一个箱线图,按特征和轴的 CV 折叠分组(参见示例图片)。

df = pd.read_csv(path)
df['Features'] = df["Features"].astype('category')
ordered_features = sorted(df.Network.value_counts().index)

df = df.loc[df['Accuracy'] > 0.1]
df.Accuracy = df.Accuracy*100

#sns.color_palette("husl", len(df['CV-fold'].value_counts().index))
#sns.set_palette('husl', len(df['CV-fold'].value_counts().index))

g = sns.FacetGrid(df, row="Network", row_order=ordered_features,
                  height=3, aspect=3, legend_out=True, despine=False)
g.map(sns.boxplot, x="CV-fold", y="Accuracy", hue="Features", data=df, palette='muted').add_legend()

g.set_axis_labels("", "Accuracy (%)")

因为我有 8 个不同的网络,所以我不想将它们全部放在一列或一行中,而是格式化为网格(例如 2x4)。此外,即使sharex 未启用,x 轴也仅标记在最底部的图形处。

我该怎么做?

【问题讨论】:

    标签: python python-3.x seaborn boxplot


    【解决方案1】:

    您可以使用 col_wrap 关键字参数来获得多行多列的绘图。

    要重复 x 轴标签,请使用 ax.tick_params()

    例子:

    import seaborn as sns, matplotlib.pyplot as plt
    
    tips = sns.load_dataset('tips')
    ordered_days = sorted(tips['day'].unique())
    g = sns.FacetGrid(tips,col='day',col_order=ordered_days,col_wrap=2)
    #                                               change this to 4 ^
    g.map(sns.boxplot,'sex','total_bill',palette='muted')
    for ax in g.axes.flatten(): 
        ax.tick_params(labelbottom=True)
    plt.tight_layout()
    plt.show()
    

    结果:

    【讨论】:

    • 工作就像一个魅力,谢谢!有没有办法增加绘图行之间的边距?
    • 我怎样才能指定网络的顺序(在你的情况下是天)?
    • @Linda:请参阅编辑后的答案,解决所有三个问题。
    • @Linda:这是我的错误,您没有为地图步骤指定数据。
    • 好的 nvm,我设法通过在调用tight_layout 后添加图例来修复它。非常感谢您的帮助!
    猜你喜欢
    • 2019-02-27
    • 1970-01-01
    • 1970-01-01
    • 2016-01-25
    • 2018-02-16
    • 2019-08-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    相关资源
    最近更新 更多