Mufeez
Mufeez

Reputation: 55

Plotly - Change colors of specific bars

I have a data frame in the following format:

Dataframe

I want to create a group bar chart like this:

Expected

I am able to produce the following chart in the Plotly using the following code:

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()

Actual

Can you please help me in letting me know how to change color of the bar for the column bars corresponding to A1?

Upvotes: 1

Views: 938

Answers (1)

Derek O
Derek O

Reputation: 19610

It's not the most elegant solution, but you can use plot the bars separately: create fig1 for the bars corresponding to A1, and create fig2 for all of the other bars. Then you can create fig3 combining the data from fig1 and 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()

enter image description here

Upvotes: 1

Related Questions