Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotly express bar chart colour change

Tags:

python

plotly

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()
like image 648
reservoirinvest Avatar asked Mar 14 '20 09:03

reservoirinvest


2 Answers

It can be done: - with color_discrete_sequence =['green']*3, or, - with fig.update_traces(marker_color='green') after the bar is instantiated.

Ref: Community response

like image 194
reservoirinvest Avatar answered Nov 04 '22 13:11

reservoirinvest


Literally copying an answer from the community response that @reservoirinvest posted. This is what I was looking for...

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'
    }
)
like image 43
mdeverna Avatar answered Nov 04 '22 13:11

mdeverna