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

Python Plotly Scattermapbox线条按属性离散配色及图例分组问题

解决方案
  • 第一步:先定义分类属性到颜色的映射规则,同时新增集合记录已添加过的图例,避免重复生成图例条目
  • 第二步:循环添加trace时,绑定对应颜色、设置同属性的图例分组,控制同属性仅显示一次图例

修改后的完整代码如下:

import plotly.graph_objects as go
fig = go.Figure()
# 自定义分类属性和对应颜色,有更多分类可自行补充色值
color_map = {
    "Highway": "#1f77b4",
    "River": "#2ca02c"
}
added_legend_attrs = set()

for i in range(len(df)):
    current_attr = df['Attribute'][i]
    fig.add_trace(go.Scattermapbox(
        mode = "lines",
        lon = [df['lon.start'][i], df['lon.end'][i]],
        lat = [df['lat.start'][i], df['lat.end'][i]],
        line = dict(width = 3, color=color_map[current_attr]),
        legendgroup = current_attr,
        name = current_attr,
        showlegend = current_attr not in added_legend_attrs
        )
    )
    if current_attr not in added_legend_attrs:
        added_legend_attrs.add(current_attr)

# 原有后续的mapbox配置、fig.show()等代码保留即可

效果说明:

  1. 所有同属性的线条自动匹配对应颜色,实现离散颜色区分效果
  2. 图例仅按Attribute的唯一值生成条目,不会每条线单独生成图例
  3. 点击图例中的分类项,会同时显示/隐藏该分类下的所有关联线条

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 10:06:03