seaborn箱线图的子图

63
我有一个像这样的数据框。
import seaborn as sns
import pandas as pd
%pylab inline

df = pd.DataFrame({'a' :['one','one','two','two','one','two','one','one','one','two'], 
                   'b': [1,2,1,2,1,2,1,2,1,1], 
                   'c': [1,2,3,4,6,1,2,3,4,6]})

一个箱线图就可以了:
sns.boxplot(y="b", x="a", data=df, orient='v')

但我想为所有变量构建一个子图。我尝试过:

names = ['b', 'c']
plt.subplots(1,2)
sub = []

for name in names:
    ax = sns.boxplot(  y=name, x= "a", data=df,  orient='v' )
    sub.append(ax)

但它输出:

enter image description here

3个回答

136

我们使用子图创建这个图:

f, axes = plt.subplots(1, 2)

axes是一个包含每个子图的数组。

然后我们使用参数ax告诉每个绘图要在哪个子图中呈现。

sns.boxplot(  y="b", x= "a", data=df,  orient='v' , ax=axes[0])
sns.boxplot(  y="c", x= "a", data=df,  orient='v' , ax=axes[1])

结果如下:

enter image description here


10
如果你想要遍历多个不同的子图,可以使用plt.subplots函数:
import matplotlib.pyplot as plt

# Creating subplot axes
fig, axes = plt.subplots(nrows,ncols)

# Iterating through axes and names
for name, ax in zip(names, axes.flatten()):
    sns.boxplot(y=name, x= "a", data=df, orient='v', ax=ax)

工作示例:
import numpy as np

# example data
df = pd.DataFrame({'a' :['one','one','two','two','one','two','one','one','one','two'], 
                   'b': np.random.randint(1,8,10), 
                   'c': np.random.randint(1,8,10),
                   'd': np.random.randint(1,8,10),
                   'e': np.random.randint(1,8,10)})

names = df.columns.drop('a')
ncols = len(names)
fig, axes = plt.subplots(1,ncols)

for name, ax in zip(names, axes.flatten()):
    sns.boxplot(y=name, x= "a", data=df, orient='v', ax=ax)
    
plt.tight_layout()

enter image description here


4
names = ['b', 'c']
fig, axes = plt.subplots(1,2)

for i,t in enumerate(names):
    sns.boxplot(y=t, x="a", data=df, orient='v', ax=axes[i % 2])

例子:

names = ['b', 'c']
fig, axes = plt.subplots(1,2)
sns.set_style("darkgrid")
flatui = ["#95a5a6", "#34495e"]

for i,t in enumerate(names):
    sns.boxplot(y=t, x= "a", data=df, orient='v', ax=axes[i % 2], palette=flatui)

enter image description here


2
你能否添加一份解释,说明为什么你的解决方案应该有效? - Fabian Schultz
@FabianSchultz 我已经回答了,见上方。 - Edward

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接