Osca
Osca

Reputation: 1694

Plot subplots base on a column's values by using loop

I want to plot subplots base on a dataframe column's values (value of the column: "name"). I'm able to plot one plot, but when using a loop to do multiple plots, they don't show.

Plot one plot

d = {'date': ['2020-01', '2020-01', '2020-02', '2020-02'], 'id':[1, 2, 3, 4], 'name':['a', 'b', 'b', 'a'], 'type':['org', 'person', 'org', 'person']}
df = pd.DataFrame(data=d)

pivot = df[df['name'] == 'a'].groupby('date')['type'].value_counts(normalize=True).mul(100).reset_index(name='count').pivot('date', 'type', 'count')
ax = pivot.plot(kind='bar')
ax.legend(bbox_to_anchor=(1, 1), loc='upper left')

enter image description here

Using loop to plot subplots base on values of the column: "name"

for i, name in enumerate(names):
    ax = plt.subplot(1, 2, i+1)
    pivot = df[df['name'] == name].groupby('date')['type'].value_counts(normalize=True).mul(100).reset_index(name='count').pivot('date', 'type', 'count')
    ax.plot(kind='bar', stacked=True, data=pivot)
    ax.legend(bbox_to_anchor=(1, 1), loc='upper left')

enter image description here

Upvotes: 1

Views: 476

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150735

Try with Pandas' plot function. Also, use groupby for faster data extraction:

for i, (name, data) in enumerate(df.groupby('name')):
    ax = plt.subplot(1, 2, i+1)
    pivot = (data.groupby('date')['type']
                 .value_counts(normalize=True)
                 .mul(100).unstack('type')              # you don't need to reset index, just unstack
                 .plot(kind='bar', stacked=True, ax=ax) # plot with pandas plot function
            )

    ax.legend(bbox_to_anchor=(1, 1), loc='upper left')

Output:

enter image description here

Upvotes: 2

Related Questions