簡體   English   中英

如何在 seaborn 中將 plot 多個圖形作為 dataframe 的子圖和倍數列?

[英]How to plot multiple figures as subplots and multiples columns of a dataframe in seaborn?

我一直在嘗試 plot 我的 dataframe 在子圖中的所有列,但它不起作用。 有沒有聰明的方法呢?

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()

一件事是您需要將plt.show移出循環,並停止使用plt.figure創建新的圖形實例。

還,

  1. 更容易平整axes和 zip
  2. 看起來你想從第 1 列而不是第 0 列 plot

全部一起:

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()

Output:

在此處輸入圖像描述


更新可能更多的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)

Output:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM