使用matplotlib / seaborn从数据透视表绘制sub_plots

时间:2020-01-14 11:03:02

标签: python pandas matplotlib seaborn

我有一个数据框中的代码

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生成相同的值,从而显示%或绝对值。

1 个答案:

答案 0 :(得分:1)

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

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