How to sort plotly bar chart using category from another column ()

Hi all,

I am trying to plot a my bar chart such that “name” is my X Axis but i want sort them based on “category 1” and also to color the bars according to that category.

Category 1 Name Volume
A eee 20
A rrr 40
A ttt 30
B yyy 50
B fff 10
B ddd 20
C ccc 30
C www 10
C bbb 70
D hhh 80
D jjj 5
D ttt 60

ideally this is what i hope to acheive from my bar chart. Any idea how can i do that?

image

thank you!

Using Plotly Express, you could pass the category column name to the color parameter. All bars with the same category should then be colored accordingly.

The closest I could replicate is with the following code:

# %%
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go

# %%
df = pd.DataFrame({
    "category": ['A', 'A', 'B', 'B', 'C'],
    "name": ['aa', 'a2', 'be', 'bk', 'cp'],
    "volume": [10, 20, 2, 8, 13],
})

fig = px.bar(df, x='name', y='volume', color='category')
fig.show()

which generates:

Hi Pokgak,

thanks for the above, it certainly help but i think i found a second issue. i think i will need to have a 2 level category for my x-axis. The above looks good but i also realised that some of my “names” are repeating in different category and in those cases the bars are stacked, instead i had like them to still be separated by “category 1”

eg.

import pandas as pd
import plotly.express as px
import plotly.graph_objects as go

%%

dff = pd.DataFrame({
“category”: [‘A’, ‘A’, ‘B’, ‘B’, ‘C’,‘C’],
“name”: [‘aa’, ‘a2’, ‘de’, ‘bk’, ‘cp’,‘de’],
“volume”: [10, 20, 2, 8, 13,6],
})

fig = px.bar(dff, x=‘name’, y=‘volume’, color=‘category’, width=400, height=300)
fig.show()

image

any idea how can i create the dual level x axis in the example previously?

thank you!!

This might be too late but I just found out that the docs actually describe how to do this.

In short, for the x-axis, you need to pass an array containing two arrays: one array with the subcategory, and the other array with the values. The value is linked to the subcategory by their index position in the arrays.