1

I was trying to explore this dataset https://www.kaggle.com/datasets/thedevastator/analyzing-credit-card-spending-habits-in-india/code?datasetId=2731425&sortBy=voteCount and I want to create a stacked bar of the 4 countries with the highest spend I use this syntax

dfg = df.groupby(['City']).sum().sort_values(by='Amount', ascending = False).head(4).reset_index()
fig = px.histogram(dfg, x='City', y = 'Amount')
fig.show()

but I found it difficult to make it stacked, I tried using pivot but it ain't work too, any way to make this possible?

1 Answers1

1

If you want a grouped bar plot, you should use the px.bar command, not px.histogram. To have stacked bars you need to add a new column with a dummy group (or meaningful if you have several countries):

px.bar(dfg.assign(country='India'), x='country', color='City', y = 'Amount')

Output:

enter image description here

To get the country from the original City column:

df[['City', 'Country']] = df['City'].str.split(', ', n=1, expand=True)

dfg = (df.groupby(['City', 'Country']).sum().sort_values(by='Amount', ascending = False)
         .groupby('Country').head(4).reset_index()
       )

px.bar(dfg, x='Country', color='City', y = 'Amount')
mozway
  • 194,879
  • 13
  • 39
  • 75