You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Dash应用的go.Scatter散点图中添加连续颜色刻度

解决方法

要在go.Scatter中实现连续颜色刻度(cividis样式)并添加颜色条,不能直接使用color_continuous_scale(该属性属于Plotly Express),需要通过配置coloraxis来实现,具体步骤如下:

修改后的完整代码

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

import dash
from dash import html, dcc, Input, Output
import plotly.graph_objects as go
import plotly.express as px

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):
    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,
                # 指定使用coloraxis来映射颜色
                marker={"coloraxis": "coloraxis"},
                showlegend=False
            )
        ],
        layout=go.Layout(
            width=500,
            height=500,
            # 配置coloraxis,设置cividis颜色刻度并显示颜色条
            coloraxis={
                "colorscale": "cividis",
                "colorbar": {"title": "Sepal Length"}
            }
        )
    )
    fig.update_layout(
        xaxis = dict(
            tickmode = 'linear',  
            dtick = 0.5  # 原dtick=10不适合Iris数据集,调整为0.5更合理
        ),
        yaxis=dict(
            tickmode= 'linear',
            dtick=0.5
        )
    )
    return fig

if __name__ == '__main__':
    app.run_server(debug=True)

关键改动说明

  • 移除无效的color_continuous_scale参数,go.Scatter不支持该属性
  • 给marker添加coloraxis: "coloraxis"配置,将散点颜色映射到全局coloraxis
  • 在layout中配置coloraxis:
    • 设置colorscale="cividis"指定颜色样式
    • 通过colorbar配置颜色条标题等属性
  • 调整x轴和y轴的dtick值(原10过大,Iris数据范围小,改为0.5能显示更多合理刻度)
  • 关闭showlegend,连续颜色散点无需普通图例,颜色条已作为功能图例使用

内容的提问来源于stack exchange,提问作者Niam45

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 01:39:53