Skip to content

Instantly share code, notes, and snippets.

@konverner
Created June 17, 2023 20:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save konverner/35be564bc6fb87687d7bcaba43ddfc6a to your computer and use it in GitHub Desktop.
Save konverner/35be564bc6fb87687d7bcaba43ddfc6a to your computer and use it in GitHub Desktop.
stacked barplot from dataframe
import pandas as pd
df = pd.DataFrame({'name': ['Store A', 'Store B', 'Store C', 'Store D']
'district': ['I', "II", "I", "III"],
"category": [X, X, Y, Z]
}
)
district_category_pivot_table = df.pivot_table('name', 'district', 'category', aggfunc='count')
district_category_pivot_table['total'] = district_category_pivot_table.sum(1)
district_category_pivot_table\
.sort_values(by='total', ascending=True)\
.drop(columns=['total'])\
.plot.barh(stacked=True, xlabel='', ylabel='', grid=True,
title='Number of name by district and category');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment