Matplotlib: How to plot sub plots from a table?

I have a code from a dataframe

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

How can I plot these using different subplots in a single figure because this loops prints the last column’s figure. So all figures are same.

Also: How can I produce the same using matplotlib/seaborn using matplotlib which shows me the % or absolute values

Answer

You need to create the different subplots and then pass one axes object to each call of annot.plot via the ax keyword, something like this:

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