Plotly - 更改特定条形图的颜色

Plotly - Change colors of specific bars

我有以下格式的数据框:

我想创建这样的组条形图:

我可以使用以下代码在 Plotly 中生成以下图表:

abc = pd.read_csv('bar dara.csv')
colors    = ['#ED7D31','#EF995F','#FFD68A','#FFA500','#FFB52E','#FFC55C','#FF6347','#FF4500','#FF7F50']

fig = px.bar(abc, x='Column A', y='Column C',
             color=abc['Column B'], barmode='group',
             text=abc['Column C'].astype(str),
             color_discrete_sequence=colors)

fig.update_layout(title_text='abcd', title_x=0.5,title_font_color='#ED7D31')
fig.update_layout(
    xaxis_title='ylabel')
fig.update_layout(
    yaxis_title="Column C")

fig.update_traces(texttemplate='%{text:,}')
# Don't forget to remove from update_traces
fig.update_traces(textfont_size=12)
fig.update_traces(texttemplate='%{text:,}')
fig.update_yaxes(tickformat=",d")
fig.show()

你能帮我告诉我如何改变对应于 A1 的柱状图的颜色吗?

这不是最优雅的解决方案,但您可以单独绘制条形图:为对应于 A1 的条形图创建 fig1,并为所有其他条形图创建 fig2酒吧。然后你可以创建 fig3 组合来自 fig1 和 fig2 的数据。

import pandas as pd
import plotly.express as px
import plotly.graph_objects as go

abc = pd.DataFrame({
    "Column A":["A1"]*2+["A2"]*4+["A3"]*4+["A4"]*4+["A5"]*4,
    "Column B":["B1","B2"]+["B1","B2","B3","B4"]*4,
    "Column C":[12,10,14,12,10,8,10,8,6,4,9,7,5,3,6,4,2,0]
})

abc_a1_bars = abc[abc["Column A"] == "A1"]
abc_non_a1_bars = abc[abc["Column A"] != "A1"]

colors = ['#ED7D31','#EF995F','#FFD68A','#FFA500','#FFB52E','#FFC55C','#FF6347','#FF4500','#FF7F50']

fig1 = px.bar(abc_a1_bars, x='Column A', y='Column C',
             color=abc_a1_bars['Column B'], barmode='group',
             text=abc_a1_bars['Column C'].astype(str),
             color_discrete_sequence=["grey","#FFD68A"])
fig1.update_traces(showlegend=False)

fig2 = px.bar(abc_non_a1_bars, x='Column A', y='Column C',
             color=abc_non_a1_bars['Column B'], barmode='group',
             text=abc_non_a1_bars['Column C'].astype(str),
             color_discrete_sequence=colors)

fig3 = go.Figure(data=fig1.data + fig2.data)

fig3.update_layout(title_text='abcd', title_x=0.5,title_font_color='#ED7D31')
fig3.update_layout(
    xaxis_title='ylabel')
fig3.update_layout(
    yaxis_title="Column C")

fig3.update_traces(texttemplate='%{text:,}')
# Don't forget to remove from update_traces
fig3.update_traces(textfont_size=12)
fig3.update_traces(texttemplate='%{text:,}')
fig3.update_yaxes(tickformat=",d")
fig3.show()