Skip to main content
 首页 » 编程设计

python之如何将 seaborn 条形图绘制为子图

2024年12月31日10sky-heaven

我想为数据框中的列列表创建子图。但是,当我运行下面的代码时,出现与轴相关的索引错误

TypeError: 'AxesSubplot' object does not support indexing

%matplotlib inline 
import seaborn as sns 
import matplotlib.pyplot as plt 
nr_rows = 1 
nr_cols = 3 
 
cols_review = ['home_ownership', 'verification_status', 'loan_status'] 
li_col_reviews = list(cols_review) 
 
fig, axs = plt.subplots(nr_rows, nr_cols, figsize=(nr_cols*4,nr_rows*3)) 
 
for r in range(0,nr_rows): 
    for c in range(0, nr_cols):   
        col = r*nr_cols+c 
        if col < len(li_col_reviews): 
            col_count = pdf[li_col_reviews[col]].value_counts() 
            sns.set(style="darkgrid") 
            sns.barplot(col_count.index, col_count.values, alpha=0.9,ax = axs[r][c]) 
            plt.ylabel('Number of Occurrences', fontsize=12) 
            plt.xlabel(col, fontsize=12) 
            plt.tight_layout()     
            plt.show()  

请您参考如下方法:

您需要将 squeeze=False 添加到行 plt.subplots

我在这里修改了您的代码并使用了一些虚拟数据。此外,您必须将 plt.show() 置于循环之外。

import numpy as np 
import matplotlib.pyplot as plt 
import seaborn as sns 
 
nr_rows = 1 
nr_cols = 3 
 
cols_review = ['home_ownership', 'verification_status', 'loan_status'] 
 
fig, axs = plt.subplots(nr_rows, nr_cols, figsize=(nr_cols*4,nr_rows*3), squeeze=False) 
 
for r in range(0,nr_rows): 
    for c in range(0, nr_cols):   
        col = r*nr_cols+c 
        if col < len(cols_review): 
            x=np.random.rand(5) * 10 
            y=np.random.rand(5) 
            sns.set(style="darkgrid") 
            sns.barplot(x, y, alpha=0.9,ax = axs[r][c]) 
            plt.ylabel('Number of Occurrences', fontsize=12) 
            plt.xlabel(col, fontsize=12) 
plt.tight_layout()     
plt.show() 

Squeeze 默认设置为 True,这意味着: 从返回的数组轴中挤出额外的维度。因此不能用 [r][c] 索引。通过不挤压 (squeeze=False),您可以确保 axs 作为二维数组返回,然后可以使用 [r][c]

对其进行索引

您可能想阅读有关squeeze 参数的文章 here .