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

px.scatter设置点大小仅显示首府,编程新手求问题排查

问题分析与修正方案

你的代码有三个关键问题,导致非首府城市点无法正常显示:

  1. 初始size参数的错误映射
    当你设置size='capital'时,如果capital字段是0/1的数值,Plotly会直接将点的尺寸映射为0和1——非首府(0)的点会小到几乎看不见,这是核心原因。

  2. update_traces的选择器写法无效
    Plotly的selector参数不支持{'capital': '0'}这种格式来筛选数据行,你的尺寸修改逻辑根本没作用到非首府的点上。

  3. fig.show缺少执行括号
    fig.show是方法引用,必须加括号fig.show()才能渲染并显示图表。


修正后的代码

方案一:通过遍历轨迹设置尺寸

import plotly.express as px

fig = px.scatter(dados, x='longitude', y='latitude', title='Mapa', color='uf')

# 遍历所有轨迹,根据数据判断是否为首府并设置尺寸
fig.for_each_trace(
    lambda trace: trace.update(marker_size=16) 
    if any(cap == 1 for cap in trace.customdata) 
    else trace.update(marker_size=15)
)

fig.show()

方案二:自定义尺寸字段(更直观)

import plotly.express as px

# 给不同类型的城市映射固定尺寸
dados['point_size'] = dados['capital'].map({0: 15, 1: 16})

fig = px.scatter(dados, x='longitude', y='latitude', title='Mapa', color='uf', size='point_size')
# 关闭自动尺寸缩放,保留我们设置的固定大小
fig.update_layout(scene=dict(aspectmode='data'))

fig.show()

内容的提问来源于stack exchange,提问作者Beatrice de Melo Silva

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.01 15:17:26