Home > Enterprise >  Order categories in a grouped bar in matplotlib
Order categories in a grouped bar in matplotlib

Time:02-01

I am trying to plot a groupby-pandas-dataframe in which I have a categorical variable by which I would like to order the bars.

A sample code of what I am doing:

import pandas as pd

df = {"month":["Jan", "Jan", "Jan","Feb", "Feb", "Mar"], 
      "cat":["High", "High", "Low", "Medium", "Low", "High"]}

df = pd.DataFrame(df)

df.groupby("month")["cat"].value_counts().unstack(0).plot.bar()

Which plots:

enter image description here

However, I would like to plot within each category the order to be Jan, Feb, March.

Any help on how to achieve this would be a appreciated.

Kind regards.

CodePudding user response:

You could make the month column categorical to fix an order:

import pandas as pd

df = {"month": ["Jan", "Jan", "Jan", "Feb", "Feb", "Mar"],
      "cat": ["High", "High", "Low", "Medium", "Low", "High"]}
df = pd.DataFrame(df)
df["month"] = pd.Categorical(df["month"], ["Jan", "Feb", "Mar"])

df.groupby("month")["cat"].value_counts().unstack(0).plot.bar(rot=0)

pandas bar plot with fixed ordering

An alternative would be to select the column order after the call to unstack(0):

df.groupby("month")["cat"].value_counts().unstack(0)[["Jan", "Feb", "Mar"]].plot.bar(rot=0)

CodePudding user response:

I recommend you to use the enter image description here

  •  Tags:  
  • Related