matplotlib 海运箱线图的子图

ipakzgxi  于 2023-05-23  发布在  其他
关注(0)|答案(3)|浏览(183)

我有一个这样的数据框

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)

但它输出:

f5emj3cl

f5emj3cl1#

我们用子图创建图形:

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

结果是:

fgw7neuy

fgw7neuy2#

如果你想遍历多个不同的子图,使用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()

wnvonmuf

wnvonmuf3#

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)

相关问题