seaborn boxplot的子图

时间:2016-12-29 16:59:15

标签: python-3.x loops boxplot seaborn

我有一个像这样的数据框

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

如何解决? thanx求助你

3 个答案:

答案 0 :(得分:17)

我们使用子图创建图:

<a href="[[+image:pthumb=`w=800&h=400&zc=0`]]" rel="lightbox" title="Click for enlagement" >
  <img src="[[+image:pthumb=`w=150&h=150&zc=0`]]" />
</a>

其中axis是每个子图的数组。

然后我们通过参数f, axes = plt.subplots(1, 2) 告诉每个我们想要它们的子图的情节。

ax

结果是:

enter image description here

答案 1 :(得分:0)

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

P.S。 @Fabian Schultz问为什么我的解决方案应该有效。我改变了我的代码,如下所示

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 :(得分:-1)

如果您希望遍历多个不同的子图,请使用 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