英文:
Plotly chart bars are still shown in stack with barmod defined to group
问题
我想要将每个水果的total和available柱状图并排显示。
这是我使用的数据:
import plotly.express as px
data_frame = {
    "fruits": ["orange", "apple", "banana", "cherry"],
    "total": [10, 20, 30, 25],
    "available": [7, 10, 27, 15],
}
我使用了plotly.express,代码如下:
fig = px.bar(
    data_frame,
    x="fruits",
    y=["total", "available"],
    color="fruits",
    barmode="group", # 被忽略了
)
fig.show()
然而,柱状图仍然以stack模式显示。我在这里漏掉了什么?
提前感谢。
英文:
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.
答案1
得分: 1
可能有一种方法可以在不将数据从宽格式转换为长格式的情况下完成此操作,但我认为将数据框转换为"melted"格式更直观。你可以使用以下代码将数据框转换为"melted"格式,其中包含variable和value列:
df_melted = df.melt(id_vars='fruits', value_vars=['total','available'])
这将得到以下长格式的数据框:
   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
然后,你可以使用以下代码创建条形图:
fig = px.bar(df_melted, x='fruits', y='value', color='variable', barmode='group')
这将使Plotly能够区分每个水果中的total和available条形。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。



评论