【问题标题】:Plotting distplots on one panel for different features with seaborn使用 seaborn 在一个面板上绘制不同特征的分布图
【发布时间】:2019-05-31 06:13:08
【问题描述】:

我有一个包含 12 个不同特征的数据框。我想在 4x3 面板上一次性绘制每个直方图。

test = pd.DataFrame({
    'a': [10, 5, -2],
    'b': [2, 3, 1],
    'c': [10, 5, -2],
    'd': [-10, -5, 2],
    'aa': [10, 5, -2],
    'bb': [2, 3, 1],
    'cc': [10, 5, -2],
    'dd': [-10, -5, 2],
    'aaa': [10, 5, -2],
    'bbb': [2, 3, 1],
    'ccc': [10, 5, -2],
    'ddd': [-10, -5, 2]
})

我可以通过编写如下代码来做到这一点:

# plot
f, axes = plt.subplots(3, 4, figsize=(20, 10), sharex=True)
sns.distplot( test["a"] , color="skyblue", ax=axes[0, 0])
sns.distplot( test["b"] , color="olive", ax=axes[0, 1])
sns.distplot( test["c"] , color="teal", ax=axes[0, 2])
sns.distplot( test["d"] , color="grey", ax=axes[0, 3])
...

如何以优雅的方式循环和迭代功能?我想为每一行分配相同的四种颜色。

【问题讨论】:

    标签: python-3.x pandas matplotlib seaborn


    【解决方案1】:

    你可以在 for 循环中包含所有内容:

    colors =["skyblue", "olive", "teal", "grey"]
    f, axes = plt.subplots(3, 4, figsize=(20, 10), sharex=True)
    for i, ax in enumerate(axes.flatten()):
        sns.distplot( test.iloc[:, i] , color=colors[i%4], ax=ax)
    

    【讨论】:

    • 完美!谢谢!
    【解决方案2】:

    Seaborn 为此提供了FacetGrid

    import pandas as pd
    import matplotlib.pyplot as plt
    import seaborn as sns
    
    test = pd.DataFrame({
        'a': [10, 5, -2],
        'b': [2, 3, 1],
        'c': [10, 5, -2],
        'd': [-10, -5, 2],
        'aa': [10, 5, -2],
        'bb': [2, 3, 1],
        'cc': [10, 5, -2],
        'dd': [-10, -5, 2],
        'aaa': [10, 5, -2],
        'bbb': [2, 3, 1],
        'ccc': [10, 5, -2],
        'ddd': [-10, -5, 2]
    })
    data = pd.melt(test)
    data["hue"] = data["variable"].apply(lambda x: x[:1])
    
    g = sns.FacetGrid(data, col="variable", col_wrap=4, hue="hue")
    g.map(sns.distplot, "value")
    
    plt.show()
    

    【讨论】:

    • 绝对是一种更简单的方法。 OP 还需要每行相同的四种颜色。
    • 不确定是否真的需要,但我更新了答案以使情节丰富多彩,@XiaoyuLu
    • 它更简单,但我的功能范围非常不同,所以第一种方法对我来说效果更好。同样有 1m 行,它似乎也更快。
    猜你喜欢
    • 1970-01-01
    • 2021-11-03
    • 2016-10-31
    • 2020-05-30
    • 2016-07-21
    • 1970-01-01
    • 1970-01-01
    • 2023-02-24
    • 2020-06-22
    相关资源
    最近更新 更多