Elise
Elise

Reputation: 49

How to change colors of stacked barplot with Plotly?

I have started to use Plotly recently. I wanted to choose the colors, but I have the same color for my column and my legend.

What I have, the same color per age group:

enter image description here

What I would like to achieve:

enter image description here

My code

x = ['18-25', '25-35', '35-45','45-55','55-65']

plot = px.Figure(data=[
           go.Bar(
               name='Bulle de Babel',
               x=x,
               y=[97, 204, 192, 145, 96]
           ),
           go.Bar(
               name='Maniet',
               x=x,
               y=[30, 73, 85, 80, 43]
           ),
          go.Bar(
              name='iPhone',
              x=x,
              y=[165, 127, 143, 107, 86]
          ),
          go.Bar(
              name='hey',
              x=x,
              y=[115, 99, 92, 92, 31]
          ),
          go.Bar(
              name='usg',
              x=x,
              y=[64, 59, 51, 29, 23])
    ])
                                         
plot.update_layout(barmode='stack') 
plot.update_traces(marker_color=['#FDCCFF', '#0F22FA','#D73E0F','#ffd700','#707070'], showlegend=True) 

plot.show()

Upvotes: 1

Views: 226

Answers (1)

Hamzah Al-Qadasi
Hamzah Al-Qadasi

Reputation: 9786

You can change the color by marker_color and add it to each go.Bar:

x = ['18-25', '25-35', '35-45','45-55','55-65']

plot = go.Figure(data=[
           go.Bar(
               name='Bulle de Babel',
               x=x,
               y=[97, 204, 192, 145, 96],
               marker_color='#FDCCFF'
           ),
           go.Bar(
               name='Maniet',
               x=x,
               y=[30, 73, 85, 80, 43],
               marker_color='#0F22FA'
           ),
          go.Bar(
              name='iPhone',
              x=x,
              y=[165, 127, 143, 107, 86],
              marker_color='#D73E0F'
          ),
          go.Bar(
              name='hey',
              x=x,
              y=[115, 99, 92, 92, 31],
              marker_color='#ffd700'
          ),
          go.Bar(
              name='usg',
              x=x,
              y=[64, 59, 51, 29, 23],
              marker_color='#707070')
    ])
                                         
plot.update_layout(barmode='stack') 

plot.show()

Output:

enter image description here

Upvotes: 1

Related Questions