Plotly express bar colour change

How can I change the colour of the plotly express bar-chart to green in the following code?

import plotly.express as px
import pandas as pd

# prepare the dataframe
df = pd.DataFrame(dict(
        x=[1, 2, 3],
        y=[1, 3, 2]
    ))


# prepare the layout
title = "A Bar Chart from Plotly Express"

fig = px.bar(df, 
             x='x', y='y', # data from df columns
             color= pd.Series('green', index=range(len(df))), # does not work
             title=title,
             labels={'x': 'Some X', 'y':'Some Y'})
fig.show()

Hi @kashi
Welcome to Plotly forum!!!
Before working with plotly express you should have some background in plotly.py.

A figure consists in data, and layout (while animations have also, frames). Data is a list of traces such as
scatter, bar, heatmap, etc Each trace has a few attributes that can be updated after your fig was defined.

As long as you have no knowledge on plotly.py you are not able to update your figures according to your preferences.

In the case of your code above you should perform the following update:

fig.update_traces(marker_color='green')

To get info on Bar attributes just type:

help(go.Bar)

and similarly on any trace type.
To update the figure appearance (i.e to improve its aesthetics) you can update its layout. Just try it for your example:

fig.update_layout(width=700, height=500, bargap=0.05)
2 Likes

Thanks @empet. I did go through the background documents.

So, do you mean to say that the only way I can change the color of a bar created by plotly express is after it gets instantiated? Is there no property within px to change it?

@kashi

You can assign the same color to each bar setting color_discrete_sequence =['green']*3:

fig = px.bar(df, 
             x='x', y='y', 
             color_discrete_sequence =['green']*len(df),
             title=title,
             labels={'x': 'Some X', 'y':'Some Y'})

For more details on px.bar see https://plot.ly/python-api-reference/generated/plotly.express.bar.html.

2 Likes

Not sure when this functionality was added, for anyone coming here looking for solutions to grouped bar charts, what most people will want in this case is not color_discrete_sequence but instead color_discrete_map. For example:

fig = px.bar(
    df, 
    x='x', 
    y='y', 
    color='z',   # if values in column z = 'some_group' and 'some_other_group'
    color_discrete_map={
        'some_group': 'red',
        'some_other_group': 'green'
    }
)
5 Likes

Thank you so mucn <3, exactly what I was looking for!

Dude!, you saved me. I’ll use this to answer the question I posed earlier

Great answer.

fig.update_traces(marker_color='green')

How can I input RGB color or HEX color codes here?

Just replace the string 'green' by a shade of green color code:

fig.update_traces(marker_color='#008000')

or

fig.update_traces(marker_color='rgb(0,128,0)')
2 Likes

Thank you very much :smiley: