gpt4 book ai didi

python-3.x - plotly:分组条形图中的降序

转载 作者:行者123 更新时间:2023-12-05 04:45:32 25 4
gpt4 key购买 nike

我正在努力

  1. 创建一个漂亮的图,该图按标签排序,然后按每个标签内的值排序。
  2. 如果可能,删除图表底部的标签,因为我在图例中有解释。

库:

from plotly import graph_objs as go
import plotly.express as px
import pandas as pd

我的数据是这样的:

df = pd.DataFrame({'LABEL': ['1', '1', '2', '2', '3', '3', '3', '3'],
'Cat2': ['a', 'b', 'a', 'b', 'c', 'a', 'e', 'f'],
'Value': [3, 2, 1, 4, 1, 3, 4, 1]})
df.sort_values(by=['LABEL', 'Value'], ascending=[True, False],inplace=True)

enter image description here

这是我的尝试:

COLOR_MAP = {str(i): c for i, c in enumerate(px.colors.qualitative.Light24)}

fig = go.Figure()

for i in df['LABEL'].unique():
df_ = df[df['LABEL'] == i]
fig.add_trace(go.Bar(
x=[df_['LABEL'], df_['Cat2']],
y=df_['Value'],
marker=dict(color=COLOR_MAP[i]),
name=f'{i}'))

fig.update_layout(legend_title='Cat1')

fig.update_layout(
xaxis=dict(tickangle=45))

fig.update_layout(xaxis={'categoryorder': 'trace'}) # I tried: 'total descending', 'category descending', 'array'

结果: enter image description here

我的期望: enter image description here

提前致谢!

最佳答案

  • plotly express中简单多了
  • 在定义 x
  • 的数据框中定义一个新列
from plotly import graph_objs as go
import plotly.express as px
import pandas as pd

df = pd.DataFrame(
{
"LABEL": ["1", "1", "2", "2", "3", "3", "3", "3"],
"Cat2": ["a", "b", "a", "b", "c", "a", "e", "f"],
"Value": [3, 2, 1, 4, 1, 3, 4, 1],
}
)
df.sort_values(by=["LABEL", "Value"], ascending=[True, False], inplace=True)

# define a concatenated column for x
df = df.assign(labx=df["LABEL"] + df["Cat2"])
px.bar(
df,
x="labx",
y="Value",
hover_data=["Cat2"],
color="LABEL",
color_discrete_sequence=px.colors.qualitative.Light24,
).update_layout(
xaxis={"tickmode": "array", "tickvals": df["labx"], "ticktext": df["Cat2"]}
)

enter image description here

没有 plotly 表达

import plotly.graph_objects as go

fig = go.Figure()

fig.add_trace(
go.Bar(
x=df["labx"],
y=df["Value"],
marker_color=df["LABEL"]
.map(
{v: c for v, c in zip(df["LABEL"].unique(), px.colors.qualitative.Light24)}
)
.values,
)
).update_layout(
xaxis={"tickmode": "array", "tickvals": df["labx"], "ticktext": df["Cat2"]}
)

关于python-3.x - plotly:分组条形图中的降序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69106190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com