如何在 dash 应用程序中的 go.scatter 图中添加连续色阶

问题描述 投票:0回答:1

我有一个带有散点图的破折号应用程序。我正在使用 go.scatter 并将 Marker_color 设置为连续变量,但我希望能够将色标设置为 cividi 并具有颜色条图例。我怎样才能做到这一点? 我尝试使用 color_continuous_scale 并收到错误: ValueError: 为plotly.graph_objs.Scatter 类型的对象指定的属性无效:'color'。在我的应用程序中,我正在上传数据,但为了可重复性,我在本示例中使用了 Iris 数据集。

external_stylesheets = ["https://codepen.io/chriddyp/pen/bWLwgP.css"]

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
server = app.server

app.layout = html.Div(
    [
    dcc.Upload(
        id="upload-data",
        children=html.Div(["Drag and Drop or ", html.A("Select Files")]),
        multiple=True,
    ), dcc.Graph(id="Mygraph"),
        html.Div(id="output-data-upload"),
    ]
)


@app.callback(Output('Mygraph', 'figure'), [
Input('upload-data', 'contents'),
Input('upload-data', 'filename'),

])
def update_graph(contents, filename):
    x = []
    y = []
    color=[]

    df_two=px.data.iris()
    x=df_two['sepal_length']
    y=df_two['sepal_width']
    color=df_two['sepal_length']
        
    fig = go.Figure(
        data=[
            go.Scatter(
                mode="markers", 
                x=x, 
                y=y,
                marker_color=color,
             # This line doesn't work:   color_continuous_scale='cividis',
                showlegend=True
                    )
               
            ],
        layout=go.Layout(
            width=500,
            height=500,
        ))
    fig.update_layout(
        xaxis = dict(
        tickmode = 'linear',  
        dtick = 10
    ),
        yaxis=dict(
        tickmode= 'linear',
        dtick=10
        )
)
    return fig
python plotly-dash
1个回答
1
投票

要将颜色名称、颜色条和图例与“go.Scatter”一起用于您的标记,您必须直接在散点图的标记中输入属性。

一些例子这里

这是修改后的代码的示例:

@app.callback(Output('Mygraph', 'figure'), [
Input('upload-data', 'contents'),
Input('upload-data', 'filename'),

])
def update_graph(contents, filename):
    x = []
    y = []
    color=[]

    df_two=px.data.iris()
    x=df_two['sepal_length']
    y=df_two['sepal_width']
    color=df_two['sepal_length']
    
    fig = go.Figure(
        data=[
            go.Scatter(
                mode="markers", 
                x=x, 
                y=y,
                marker_color=color,
                marker=dict(
                  colorscale="Cividis",  
                  colorbar=dict(title='Colorbar')),
                showlegend=False,
                
                    )
               
            ],
        layout=go.Layout(
            width=500,
            height=500,
        ))
    fig.update_layout(
        xaxis = dict(
        tickmode = 'linear',  
        dtick = 10
    ),
        yaxis=dict(
        tickmode= 'linear',
        dtick=10
        )
)
    return fig

希望能帮到你。

© www.soinside.com 2019 - 2024. All rights reserved.