gpt4 book ai didi

python - 使用 matplotlib/seaborn 绘制数据透视表中的子图

转载 作者:行者123 更新时间:2023-12-01 06:34:42 24 4
gpt4 key购买 nike

我有来自数据帧的代码

Y = df['label']
for col in categorical_cols:
tab = pd.crosstab(df[col],Y)
annot = x.div(x.sum(axis=1).astype('float64'),axis=0)
annot.plot(kind='bar',stacked=True)
plt.title('Distribution of %s'%col)
plt.xlabel('%s'%col,size='x-large')
plt.xticks(rotation=45)
plt.legend()

如何在单个figure中使用不同的子图来绘制这些图,因为此循环会打印最后一列的图形。所以所有数字都是相同的。

另外:如何使用 matplotlib/seaborn 生成相同的结果,使用 matplotlib 显示%或绝对值。

最佳答案

您需要创建不同的子图,然后通过 ax 关键字将一个 axes 对象传递给 annot.plot 的每次调用,例如像这样:

import math
import matplotlib.pyplot as plt

n = len(categorical_cols)
nrows = math.ceil(float(n) / 3.0)
fig, ax = plt.subplots(ncols=3, nrows=nrows, figsize=(9, nrows*3))
ax = ax.flatten()

Y = df['label']
for idx, col in enumerate(categorical_cols):
tab = pd.crosstab(df[col],Y)
annot = x.div(x.sum(axis=1).astype('float64'),axis=0)
annot.plot(kind='bar',stacked=True, ax=ax[idx])
ax[idx].title('Distribution of %s'%col)
ax[idx].set_xlabel('%s'%col,size='x-large')
ax.tick_params('x', labelrotation=45)
plt.legend()

关于python - 使用 matplotlib/seaborn 绘制数据透视表中的子图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59732480/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com