2

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()
2
  • Are you having issues starting/creating a for loop? Or did you have a specific error when trying to execute one? Commented Feb 11, 2020 at 0:24
  • Thanks a bunch busybear yes having issues starting/creating a for loop ^-^ Commented Feb 11, 2020 at 0:27

1 Answer 1

3

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

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.