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

如何用Plotly替代ggplotly实现Choropleth+大小可变点的分层地图

解决Plotly原生实现Choropleth地图+动态大小质心点的问题

我来帮你搞定这个需求——把ggplotly实现的墨尔本SA3区域Choropleth地图+面积关联的质心点图层,改成稳定的Plotly原生代码。你遇到的图层异常和坐标警告,核心原因是坐标系不匹配以及Plotly原生图层的添加方式问题,下面是完整的解决方案:

问题回顾

你已经通过absmapsdata+ggplotly实现了目标效果,但改用Plotly原生代码时遇到两个问题:

  • 用plot_geo()叠加多边形和add_markers()时显示异常
  • 移除点图层后地图正常,但弹出坐标系转换警告:

    Warning message: The trace types 'scattermapbox' and 'scattergeo' require a projected coordinate system that is based on the WGS84 datum (EPSG:4326), but the crs provided is: '+proj=longlat +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +no_defs '. Attempting transformation to the target coordinate system.

解决方案

关键是先统一坐标系到Plotly要求的WGS84(EPSG:4326),再用Plotly专门的sf图层函数添加多边形,最后叠加质心点图层。

完整代码

# 安装依赖包(首次运行)
remotes::install_github("wfmackey/absmapsdata")
library(tidyverse)
library(sf)
library(absmapsdata)
library(plotly)

# 加载数据并预处理:过滤墨尔本区域+转换坐标系到WGS84
mapdata <- sa32016 %>%
  filter(gcc_name_2016 == "Greater Melbourne") %>%
  st_transform(crs = 4326)  # 这一步彻底解决坐标警告问题

# Plotly原生实现Choropleth+动态点图层
fig <- mapdata %>%
  # 初始化地理绘图环境
  plot_geo(hoverinfo = "text") %>%
  # 添加多边形图层(Choropleth)
  add_sf(
    text = ~paste("Area:", sa3_name_2016, "<br>Size:", areasqkm_2016),
    color = ~areasqkm_2016,  # 可选:按区域面积着色,不需要的话可以删除此行
    showlegend = FALSE,
    hoverinfo = "text"
  ) %>%
  # 添加质心点图层,点大小随面积变化
  add_scattergeo(
    # 直接从sf对象提取质心坐标,确保和多边形坐标系一致
    x = ~st_coordinates(st_centroid(geometry))[,1],
    y = ~st_coordinates(st_centroid(geometry))[,2],
    size = ~areasqkm_2016,
    text = ~paste("Area:", sa3_name_2016, "<br>Size:", areasqkm_2016),
    hoverinfo = "text",
    marker = list(opacity = 0.7)  # 调整点透明度,避免遮挡多边形
  ) %>%
  # 设置地图布局,聚焦澳大利亚区域
  layout(
    geo = list(
      scope = "australia",
      projection = list(type = "mercator")
    ),
    showlegend = FALSE
  )

# 查看最终效果
fig

核心优化点

  1. 坐标系统一:st_transform(crs=4326)把原始GRS80坐标系转换为Plotly要求的WGS84,彻底消除坐标警告,同时保证多边形和点的坐标系统完全匹配,避免图层错位。
  2. 用add_sf()添加多边形:Plotly的add_sf()是专门为sf空间对象设计的图层函数,比plot_geo(split=...)更稳定,能正确识别和渲染多边形 geometry,不会出现异常线条。
  3. 质心坐标提取:直接用st_centroid(geometry)从sf对象生成质心,不需要依赖数据集中的cent_long/cent_lat字段,确保点的位置和多边形完全对应。
  4. 图层顺序与透明度:先添加多边形再添加点,保证点在上方显示;通过marker(opacity)调整点的透明度,不影响下方多边形的查看和交互。

这样就能实现和ggplotly版本一致的效果,同时完全基于Plotly原生代码,没有异常和警告。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 19:52:53