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

如何解决Plotly Scattergeo图例无法显示的问题?

解决Plotly Scattergeo图例不显示的问题

你的代码里用单条Scattergeo trace绑定连续数值作为颜色,这种情况下Plotly不会自动生成离散图例。要显示对应value的图例,有两种可行方案:

方案1:改用Plotly Express(推荐,代码更简洁)

Plotly Express会自动根据value字段分组并生成图例,无需手动配置:

import plotly.express as px

# 直接用px.scattergeo,指定color为value字段
fig = px.scattergeo(df_melted,
                    lon='Longitude',
                    lat='Latitude',
                    color='value',  # 按value分组生成颜色和图例
                    text='value',
                    scope='usa',
                    title='Footprints Compared Based on Lat & Lon Coordinates')

# 调整布局和图例位置
fig.update_layout(
    autosize=False,
    width=1000,
    height=1000,
    legend=dict(
        orientation="h",
        yanchor="bottom",
        y=1.02,
        xanchor="right",
        x=1
    )
)

fig.show()

方案2:修改Graph Objects代码,按value分组生成多trace

如果坚持用go.Figure,需要把每个value类别单独做成一条Scattergeo trace,指定name参数来生成图例:

import plotly.graph_objects as go

fig = go.Figure()

# 遍历每个唯一的value值,添加对应的trace
for val in df_melted['value'].unique():
    subset = df_melted[df_melted['value'] == val]
    fig.add_trace(go.Scattergeo(
        lon=subset['Longitude'],
        lat=subset['Latitude'],
        text=subset['value'],
        name=str(val),  # 这里的name会显示在图例中
        marker_color=subset['colors'].iloc[0]  # 用该类别的颜色
    ))

# 更新布局
fig.update_layout(
    autosize=False,
    width=1000,
    height=1000,
    title='Footprints Compared Based on Lat & Lon Coordinates)',
    geo_scope='usa',
    showlegend=True  # 现在多trace情况下这个参数生效
)

fig.update_layout(legend=dict(
    orientation="h",
    yanchor="bottom",
    y=1.02,
    xanchor="right",
    x=1
))

fig.show()

补充说明

你之前设置showlegend=True无效,是因为单条trace用连续颜色时,Plotly会用**颜色轴(coloraxis)**来展示颜色对应关系,而不是图例。只有当存在多条带有name参数的trace时,showlegend=True才会显示离散图例,对应每个trace的名称。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 23:45:44