【问题标题】:How to plot multiple figures as subplots and multiples columns of a dataframe in seaborn?如何在seaborn中将多个图形绘制为数据框的子图和多列?
【发布时间】:2021-03-09 17:09:54
【问题描述】:

我一直试图在子图中绘制我的数据框的所有列,但它不起作用。 有什么聪明的方法吗?

import padas as pd
import seaborn as sns
    df = pd.DataFrame({'TR':np.arange(1, 6).repeat(5), 'A': np.random.randint(1, 100,25), 'B':  np.random.randint(50, 100,25), 'C':  np.random.randint(50, 1000,25), 'D':  np.random.randint(5, 100,25), 'E':  np.random.randint(5, 100,25),
                   'F':  np.random.randint(5, 100,25), 'G':  np.random.randint(5, 100,25), 'H':  np.random.randint(5, 100,25), 'I':  np.random.randint(5, 100,25), 'J':  np.random.randint(5, 100,25) })
row = 2
col = 5
r = sorted(list(range(0, row))*5)
c = list(range(0, col))*2

fig, axes = plt.subplots(row, col, figsize=(20, 10))

for j, k,i in zip( r, c, df.columns):
    plt.figure()
    g = sns.boxenplot(x = 'TR', y = df[i], ax= axes[j, k], data=df)

    plt.show()

【问题讨论】:

    标签: python pandas dataframe seaborn


    【解决方案1】:

    有一件事是您需要将plt.show 移出循环,并停止使用plt.figure 创建新的图形实例。

    还有,

    1. 扁平化axes 和压缩更容易
    2. 您似乎想从第 1 列而不是第 0 列进行绘图

    大家一起:

    row = 2
    col = 5
    
    fig, axes = plt.subplots(row, col, figsize=(20, 10))
    
    # flattern `axes` with `.ravel()`    
    # notice the `[1:]`
    for ax,i in zip( axes.ravel(), df.columns[1:]):
        # remove this as well
        #  plt.figure()
    
        # you just need to pass y = i
        g = sns.boxenplot(x = 'TR', y = i, ax= ax, data=df)
    
    # move `plt.show()` out of for loop:
    plt.show()
    

    输出:


    更新可能是一种更seaborn的方式是使用FacetGrid

    fg = sns.FacetGrid(data=df.melt('TR'), 
                       col='variable', col_wrap=5, sharey=False)
    fg.map(sns.boxenplot,'TR','value',order=df['TR'].unique)
    

    输出:

    【讨论】:

    • 非常感谢!
    • @MARCOSSANTOS 不客气。请参阅更新以获取其他解决方案。此外,如果它适合您,请考虑支持/接受答案。
    猜你喜欢
    • 1970-01-01
    • 2016-05-04
    • 2019-04-16
    • 2018-01-16
    • 1970-01-01
    • 2023-01-20
    • 2016-05-16
    • 2020-04-25
    • 1970-01-01
    相关资源
    最近更新 更多