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

在geom_tile图层添加geom_scatterpie时遇geom转grob错误

解决geom_scatterpie与geom_tile底图的兼容性错误

错误原因

该错误源于ggplot2 3.5.1与scatterpie包的图层渲染逻辑冲突,加上地理瓦片底图未明确指定地理坐标系,导致scatterpie无法正确将饼图转换为图形对象(grob)。

解决方案

方法1:添加地理坐标系coord_sf()

因为底图是基于经纬度的地理瓦片数据,显式指定地理坐标系能让scatterpie正确识别经纬度位置,解决图层转换错误:

修改后的完整代码:

library(sf); library(maptiles)
library(tidyverse); library(scatterpie)

nc <- st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
nc_osm <- get_tiles(nc, crop = TRUE, zoom = 7)

dt_osm_i <- nc_osm %>%
  terra::as.data.frame(xy = TRUE)
names(dt_osm_i) <- c("x", "y", "red", "green", "blue")

dt_osm <- dt_osm_i %>%
  as_tibble() %>% 
  mutate(hex = rgb(red, green, blue, maxColorValue = 255)) 

pie = data.frame(
  lon=c(-82.5,-77,-80.5,-79), 
  lat=c(34,35,36,34.5), 
  A=c(0.25,0.75,0,0.25), 
  B=c(0.75,0.10,0,0.75), 
  C=c(0,0.15,1,0), 
  group=1,
  radius=0.05)

ggplot() +
  geom_tile(data= dt_osm, aes(x, y, fill = hex)) +
  scale_fill_identity() +
  geom_scatterpie(data = pie, mapping = aes(x = lon, y = lat, r = radius),
                  cols=c("A", "B", "C")) +  # 移除不必要的group映射
  coord_sf() +  # 新增地理坐标系
  theme_light() + xlab("") + ylab("")

方法2:调整scatterpie参数(可选)

如果方法1仍有问题,可尝试:

  • 移除geom_scatterpie映射中的group参数(所有饼图group均为1,无分组必要)
  • 给radius设置固定值而非映射(如r = 0.05,而非写入aes映射)

说明

在R 4.4.0和ggplot2 3.5.1的环境下,上述方法可稳定解决该错误;地理坐标系coord_sf()是核心修复点,它让底图与scatterpie的经纬度坐标系统一。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 01:57:13