【问题标题】:Subplot for seaborn boxplotseaborn箱线图的子图
【发布时间】:2017-05-14 00:50:12
【问题描述】:

我有一个这样的数据框

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)

但它输出:

【问题讨论】:

    标签: python python-3.x loops seaborn boxplot


    【解决方案1】:

    我们用子图创建图形:

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

    其中轴是一个包含每个子图的数组。

    然后我们用参数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])
    

    结果是:

    【讨论】:

      【解决方案2】:
      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)
      

      【讨论】:

      • 您能否解释一下为什么您的解决方案应该有效?
      • @FabianSchultz 我回答了,见上文
      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-08
        • 2021-09-08
        • 2019-04-29
        • 1970-01-01
        • 2020-12-08
        • 2019-01-31
        • 2018-02-16
        • 2020-08-03
        相关资源
        最近更新 更多