首页 > 解决方案 > 为 seaborn 子图创建 forloop 的问题

问题描述

我正在处理很多 csv 文件,每个文件代表不同的海底通道(水下河流)。我一直在编写函数来为每个通道使用 seaborn(小提琴图、distplots 等)创建各种图,并且在尝试循环并将数据框中的许多不同列绘制为子图时遇到了问题。问题是生成的三个子图显示为空白,并且生成的图虽然正确,但单独出现,而不是我想要的三个子图。我使用了一段非常相似的代码来生成 3 个小提琴图,并且效果很好。

我错过了什么?我对python很陌生,无法弄清楚。

def distPlots(df, fname):
    """
    df : dataframe
    filename : string for file export
    """
    copy = df.drop('Channel', axis=1)
    cols = copy.columns
    col_labels = ["Width (m)", "Height (m)", "Aspect ratio"]
    fig, ax = plt.subplots(1, 3, figsize=(17, 5))
    for var, label, subplot in zip(cols, col_labels, ax.flatten()):
        sns.displot(x=var, hue="Channel", data=df, kde=True, bins=20, ax=subplot)
        subplot.set_xlabel(label)
    plt.tight_layout()
    plt.show()
    plt.draw()
    fig.savefig(fname)  

distPlots(data_chc1, 'ChC1_distPlots.pdf')

标签: pythonfor-loopmatplotlibseaborn

解决方案


推荐阅读