Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

pandas bar plot xlabel based on two column values

given the code below, I get the expected plot attached.
Is there a way to get pandas to plot the X labels as a combination of A and B?
I’ve tried passing in x=['A','B'] as well as x=('A','B') which does not work…

I would like the labels just to include both of them.
It is possible to pivot and get a semi-workable solution but I don’t want to actually compare the subset B side by side…
df.pivot(index='B',columns='A',values='Val').plot(kind='bar')

import pandas as pd


df = pd.DataFrame(columns=['A','B','Val'])

for a in range(2):
    for b in range(3):
        df = df.append({'A':str(a),'B':str(b),'Val':a+b},ignore_index=True)
        
df.plot(kind='bar',x='B',y='Val')

enter image description here
enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can create multiindex by setting columns A and B as index then use plot with kind=bar:

df.set_index(['A', 'B']).plot(kind='bar', y='Val')

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading