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

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

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

问题

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

这是我使用的数据:

  1. import plotly.express as px
  2. data_frame = {
  3. "fruits": ["orange", "apple", "banana", "cherry"],
  4. "total": [10, 20, 30, 25],
  5. "available": [7, 10, 27, 15],
  6. }

我使用了plotly.express,代码如下:

  1. fig = px.bar(
  2. data_frame,
  3. x="fruits",
  4. y=["total", "available"],
  5. color="fruits",
  6. barmode="group", # 被忽略了
  7. )
  8. fig.show()

然而,柱状图仍然以stack模式显示。我在这里漏掉了什么?

提前感谢。

英文:

I want to display total and available bars side by side for each fruit.

Here is the data I'm using

  1. import plotly.express as px
  2. data_frame = {
  3. "fruits": ["orange", "apple", "banana", "cherry"],
  4. "total": [10, 20, 30, 25],
  5. "available": [7, 10, 27, 15],
  6. }

And I used plotly.express as follow:

  1. fig = px.bar(
  2. data_frame,
  3. x="fruits",
  4. y=["total", "available"],
  5. color="fruits",
  6. barmode="group", # Is ignored
  7. )
  8. fig.show()

However, bars are still shown in stack mode instead. What am I missing here?

Thanks in advance.

答案1

得分: 1

可能有一种方法可以在不将数据从宽格式转换为长格式的情况下完成此操作,但我认为将数据框转换为"melted"格式更直观。你可以使用以下代码将数据框转换为"melted"格式,其中包含variablevalue列:

  1. df_melted = df.melt(id_vars='fruits', value_vars=['total','available'])

这将得到以下长格式的数据框:

  1. fruits variable value
  2. 0 orange total 10
  3. 1 apple total 20
  4. 2 banana total 30
  5. 3 cherry total 25
  6. 4 orange available 7
  7. 5 apple available 10
  8. 6 banana available 27
  9. 7 cherry available 15

然后,你可以使用以下代码创建条形图:

  1. 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:

  1. df_melted = df.melt(id_vars='fruits', value_vars=['total','available'])

This gives you the following long format dataframe.

  1. fruits variable value
  2. 0 orange total 10
  3. 1 apple total 20
  4. 2 banana total 30
  5. 3 cherry total 25
  6. 4 orange available 7
  7. 5 apple available 10
  8. 6 banana available 27
  9. 7 cherry available 15

Then you can create the bar chart using:

  1. 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:

确定