I want to display total
and available
bars side by side for each fruit
.
Here is the data I'm using
import plotly.express as px
data_frame = {
"fruits": ["orange", "apple", "banana", "cherry"],
"total": [10, 20, 30, 25],
"available": [7, 10, 27, 15],
}
And I used plotly.express
as follow:
fig = px.bar(
data_frame,
x="fruits",
y=["total", "available"],
color="fruits",
barmode="group", # Is ignored
)
fig.show()
However, bars are still shown in stack
mode instead. What am I missing here?
Thanks in advance.
There might be a way to do this without changing your data from wide to long format, but I think it's more intuitive to melt your dataframe so that you have variable
and value
columns using:
df_melted = df.melt(id_vars='fruits', value_vars=['total','available'])
This gives you the following long format dataframe.
fruits variable value
0 orange total 10
1 apple total 20
2 banana total 30
3 cherry total 25
4 orange available 7
5 apple available 10
6 banana available 27
7 cherry available 15
Then you can create the bar chart using:
fig = px.bar(df_melted, x='fruits', y='value', color='variable', barmode='group')
This will allow plotly to differentiate the between total
and available
bars within each fruit
.