'Change stacked bar graph color with dropdown

I'm trying to create a stacked bar chart and then change color of it by dropdown value. Below is my sample code:

import pandas as pd
import numpy as np
import plotly.express as px
import dash
from dash import html
from dash import dcc
from dash.dependencies import Input, Output, State
import dash_bootstrap_components as dbc

app = dash.Dash(__name__,external_stylesheets=[dbc.themes.LUX]) # You can change external_stylesheets
    # Make the layout with two tabs
    
    colorscales = dir(px.colors.qualitative)
    df = px.data.medals_long()
    
    app.layout = html.Div([
        dbc.Row([html.H6('Color Palette',className='text-left'),
                dcc.Dropdown(id='color_range',placeholder="Color", # Dropdown for heatmap color
                    options=colorscales, 
                    value='aliceblue',
                    multi=False,
                    disabled=False,
                    clearable=True,
                    searchable=True),  
        dcc.Graph(id='bar_chart',figure={},style={'height':500,'width':'auto'})
        ])
    ])
    
    @app.callback(Output('bar_chart','figure'),
                 [Input('color_range', 'value')]) 
    
    def update_color(color_range):
        fig = px.bar(df, x="medal", y="count", color="nation", text="nation",
                     color_discrete_sequence = color_range)
        return fig
    
    if __name__ == "__main__":
        app.run_server(debug=False)

But it raised an error that said:

ValueError: 
    Invalid value of type 'builtins.str' received for the 'color' property of bar.marker
        Received value: 'a'

    The 'color' property is a color and may be specified as:
      - A hex string (e.g. '#ff0000')
      - An rgb/rgba string (e.g. 'rgb(255,0,0)')
      - An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
      - An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
      - A named CSS color:
            aliceblue, antiquewhite, aqua, aquamarine, azure,

I tried to change from colorscales = dir(px.colors.qualitative) to colorscales = px.colors.named_colorscales() and then change color_discrete_sequence to color_continuous_scale but it didn't work. It didn't raise error but color not change.

Thank you.



Solution 1:[1]

The modification is that the drop-down default should choose a qualitative color name. And the bar chart color specification needs to be written in the form px.colors.qualitative.G10.

app.layout = html.Div([
    dbc.Row([html.H6('Color Palette',className='text-left'),
            dcc.Dropdown(id='color_range',placeholder="Color", # Dropdown for heatmap color
                options=colorscales, 
                value='Plotly',# update
                multi=False,
                disabled=False,
                clearable=True,
                searchable=True),  
    dcc.Graph(id='bar_chart',figure={},style={'height':500,'width':'auto'})
    ])
])

def update_color(color_range):
    df = px.data.medals_long() # update
    fig = px.bar(df, x="medal", y="count", color="nation", text="nation",
                     color_discrete_sequence = eval('px.colors.qualitative.{}'.format(color_range))) # update
    return fig

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 r-beginners