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

花卉

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

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)to更改为colorscales = px.colors.named_colorscales(),然后更改color_discrete_sequence为,color_continuous_scale但没有成功。它没有引发错误,但颜色没有改变。

谢谢你。

r-初学者

修改的是下拉默认应该选择一个定性的颜色名称。并且条形图颜色规范需要写在表格中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

在此处输入图像描述

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章