1

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

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.