williamscathy825
williamscathy825

Reputation: 195

Looping to create multiple graphs in matplotlib from one dataframe?

I want to plot 3 graphs separately from below df:

import pandas as pd
import matplotlib.pyplot as plt
d = {'a1': [1,2,3,1,2,3,1,2,3],
     'a2': ['a', 'a', 'a','b','b','b','c','c','c'],
     'a3': [100,200,300,700,800,900,10,20,30]}

df=pd.DataFrame(d)
df

a1  a2  a3
1   a   100
2   a   200
3   a   300
1   b   700
2   b   800
3   b   900
1   c   10
2   c   20
3   c   30

one graph for a, one for b, and one for c using a loop:

Here is an example for a:

df1=df[df['a2'] == 'a']
df1.plot(x='a1', y='a3', kind='bar')
plt.title("my graph for a", fontsize=12)
plt.show()

Upvotes: 2

Views: 1004

Answers (1)

busybear
busybear

Reputation: 10580

I'd suggest looking up for loops in general. You have everything you need in your example, you just need to throw it in a for loop iterating over ['a', 'b', 'c'] or df['a2'].unique():

for x in ['a', 'b', 'c']:
    ...

You'll find the bars will overlap if you go forward with this approach. Instead, you can arrange your dataframe and plot without the for loop. You'll need to rearrange your data with groups as your columns:

pd.pivot_table(data=df, index='a1', columns='a2', values='a3').plot.bar()

However, seaborn might be preferable for you. You can use barlot in one line:

import seaborn as sns
sns.barplot(data=df, x='a1', y='a3', hue='a2')

enter image description here

Upvotes: 3

Related Questions