plotly express:更改构面条形图的不同属性

问题描述

我想更改分面条形图的不同属性,但在文档中找不到任何提示

这是我的剧情:

enter image description here

我正在努力实现两件事:

(1) 将九个条形图分别旋转 90 度,使 Choice_1Choice_2 条并排而不是堆叠

(2) 根据 Choice_1Choice_2 的值为条形着色: - 如果 Choice_1 == 1.0,使用 color_1 作为 Choice_1 - 其他:对 color_2 使用 Choice_1 并在栏中显示 Choice_1 的值并使用 color_3 表示 Choice_2

color_n 只是一个 rgb 字符串,例如color_1 = 'rgba(90,170,70,1.0)'

这是我的代码

import pandas as pd
import plotly.express as px

df2 = pd.DataFrame({
    "Category": ["A","A","B","C","C"],"Year": [2021,2022,2023,2021,2023],"Choice_1": [0.9,0.8,1.0,0.5,0.7],"Choice_2": [0.1,0.2,0.0,0.3]
})

fig = px.bar(df2,x="Year",y=["Choice_1","Choice_2"],facet_row="Category",#orientation="h",#color = ?
             barmode="stack")
fig.update_yaxes(visible=False,showticklabels=False)
fig.update_layout(showlegend=False)
# rotate facet_row names
fig.for_each_annotation(lambda a: a.update(textangle=0))
# fix facet_row names: https://plotly.com/python/facet-plots/#customize-subplot-figure-titles
fig.for_each_annotation(lambda a: a.update(text=a.text.split("=")[-1]))

Choice_1Choice_2 的总和始终为 1。

对于 (1),我尝试在 orientation='h'-Call 中设置 px.bar,但它只是弄乱了情节(而不是简单地旋转它):

enter image description here

对于 (2),我能够为轨迹分配 color_2 和 color_3,但我不知道如何添加条件:

color_1 = 'rgba(85,175,72,1.0)'
color_2 = 'rgba(85,0.7)'
color_3 = 'rgba(205,75,1.0)'

fig.for_each_trace(
    lambda t: t.update(marker_color=color_1) if t.name == "Choice_1" else t.update(marker_color=color_3)
    )

我如何 (1) 旋转每个条形和 (2) 根据上述条件为每个条形着色/显示值?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)