使用下拉菜单更改堆积条形图颜色

Change stacked bar graph color with dropdown

我正在尝试创建一个堆积条形图,然后通过下拉值更改它的颜色。下面是我的示例代码:

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)

但它引发了一个错误:

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,

我尝试将 colorscales = dir(px.colors.qualitative) 更改为 colorscales = px.colors.named_colorscales(),然后将 color_discrete_sequence 更改为 color_continuous_scale,但没有成功。它没有引发错误,但颜色没有改变。

谢谢。

修改是drop-down默认应该选择一个定性的颜色名称。而条形图颜色规范需要写成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