Plotly图表中的柱状图仍然以堆叠的方式显示,即使定义了barmod为group。

huangapple go评论88阅读模式
英文:

Plotly chart bars are still shown in stack with barmod defined to group

问题

我想要将每个水果的totalavailable柱状图并排显示。

这是我使用的数据:

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"格式,其中包含variablevalue列:

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能够区分每个水果中的totalavailable条形。

Plotly图表中的柱状图仍然以堆叠的方式显示,即使定义了barmod为group。

英文:

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.

Plotly图表中的柱状图仍然以堆叠的方式显示,即使定义了barmod为group。

huangapple
  • 本文由 发表于 2023年8月9日 03:18:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76862625.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定