How to change legend/marker colours in plotly using python?

1.8k Views Asked by At

Quite simply, when I tell plotly to color the bars according to a characteristic (in this case it is carbon number) I am not happy with the default colors it chooses for each group (see link to bar chart png below). How do I adjust the legend/marker colors manually?

My code is currently as follows:

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

df = pd.read_csv('E vs I data ab.csv')

core_data = df.loc[df['isomer_grade']=='major']

fig = px.bar(core_data, x="isomer", y="19C002",  title="19C002", width=800, height=650, color="homologue")
             
fig.update_xaxes(showgrid=False, showline=True, mirror=True, linecolor='#E3E2E2', linewidth=2, title_text=' ')
fig.update_yaxes(showgrid=True, showline=True, mirror=True, linecolor='#E3E2E2', linewidth=2, 
                 ticks='outside', gridcolor='#FFFFFF', title_text='Exterior/Interior')

fig.update_layout(title=dict(x=.8, y=0.8))

fig.update_layout(yaxis=dict(range=[0,5]))
               
fig.update_layout(
    font_color="#939393",
    font_size=17,
    title_font_size=22,
    title_font_color="#939393",
)
    
fig.update_traces(marker_line_color='#FFFFFF', marker_line_width=1.5, opacity=1)

fig.layout.plot_bgcolor = '#E3E2E2'

fig.show()

bar chart colored according to carbon number - example

1

There are 1 best solutions below

0
On

Just had a friend help me out. updated code looks like this

import pandas as pd
import plotly.express as px

df = pd.read_csv('E vs I data ab.csv')
core_data = df.loc[df['isomer_grade'] == 'major']
colors = ['#2F45AC', '#4045C3', '#6B57DD', '#9165E4', '#BF72F1', '#CF8EE9', '#E9A2F9', '#F6C4FE']
fig = px.bar(core_data, x="isomer", y="19C002",  title="19C002", width=800,
             height=650, color="homologue", color_discrete_sequence=colors)
fig.update_xaxes(showgrid=False, showline=True, mirror=True,
                 linecolor='#E3E2E2', linewidth=2, title_text=' ')
fig.update_yaxes(showgrid=True, showline=True, mirror=True,
                 linecolor='#E3E2E2', linewidth=2, ticks='outside',
                 gridcolor='#FFFFFF', title_text='Exterior/Interior')
fig.update_layout(title=dict(x=.8, y=0.8))
fig.update_layout(showlegend=False)
fig.update_layout(yaxis=dict(range=[0, 5]))
fig.update_layout(font_color="#939393", font_size=17, title_font_size=22,
                  title_font_color="#939393")
fig.update_traces(marker_line_color='#FFFFFF', marker_line_width=1.5,
                  opacity=1)
fig.layout.plot_bgcolor = '#E3E2E2'
fig.show()

Just insert your own colors!