Home > other >  pandas bar plot xlabel based on two column values
pandas bar plot xlabel based on two column values

Time:02-19

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

CodePudding user response:

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

  • Related