python - 如何将 seaborn barplots 绘制为子图?
问题描述
我想为数据框中的列列表创建子图。但是,当我运行下面的代码时,我收到与轴相关的索引错误
TypeError:“AxesSubplot”对象不支持索引
%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,这意味着:
extra dimensions are squeezed out from the returned array axs
. 因此不能用 索引[r][c]
。通过不挤压 (squeeze=False),您可以确保将axs
其作为二维数组返回,然后可以使用[r][c]
您可能想阅读这里squeeze
的论点。
推荐阅读
- html - 如何使用使用选项卡按钮的文本区域处理可访问性选项卡?
- android - android 系统库上的 Malloc_Debug 用于内存泄漏
- php - 如何通过 group by 找到更大的价值,并在 laravel 中找到元素计数并使其更高
- swift - Crashlytics 未从 iPhone 或 Real Deivce 发送崩溃报告
- java - 如何抵消Java“找不到行”错误?
- laravel - 在 laravel 中使用 vuex 模块进行 vuedraggable
- javascript - myFunc.prototype 与 new myFunc().prototype 之间的区别
- key-bindings - 有没有办法制作 Space Invaders 键绑定,这样当我射击时它不会停止运动?
- python - 关于 if-elif 函数的 Python 函数问题
- xpages - 如何从我的 XPages 代码向外部电子邮件 ID 发送电子邮件