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

使用Rayshader的plot_gg时如何隐藏多边形边缘?

解决Rayshader plot_gg显示多边形边缘的问题

当使用rayshader::plot_gg()渲染基于sf多边形的ggplot图时,即使在geom_sf()中设置了colour=NA,仍会出现多边形边缘。这并非数据问题(你已验证多边形相互接触),而是rayshader的渲染机制会保留矢量图层的细微轮廓线。以下是两种可行的解决方法:

方法一:绑定边缘色与填充色

让多边形边缘颜色和填充色完全一致,从视觉上隐藏边缘:

library(ggplot2)
library(rayshader)
library(sf)    

temp <- tempfile()
download.file("https://www.cbs.nl/-/media/cbs/dossiers/nederland-regionaal/vierkanten/500/2022-cbs_vk500_2021_v1.zip", temp)
NLD <- read_sf(utils::unzip(temp, "cbs_vk500_2021_v1.gpkg"))

NLD <- NLD[-c(99:nrow(NLD)),]                # 测试用,减少数据量

NLD$aantal_inwoners <- ifelse(NLD$aantal_inwoners < 0, 1, NLD$aantal_inwoners)

kaart <- ggplot(NLD)+
  # 将边缘色与填充色绑定为同一变量
  geom_sf(aes(fill=aantal_inwoners, colour=aantal_inwoners)) +
  scale_fill_gradient(high="deeppink", low="black") + 
  # 同步设置边缘色的渐变规则,与填充色保持一致
  scale_colour_gradient(high="deeppink", low="black") +
  theme_void() +
  theme(legend.position = "none")

# 保持白色背景
kaart <- kaart + theme(panel.background = element_rect(fill="white", color="white"),        
                       plot.background = element_rect(fill = "white", color="white"))

plot_gg(kaart, width = 3, height = 3, multicore = TRUE, 
        zoom = .7, theta = 0, phi = 90, windowsize = c(800, 800)) 

方法二:栅格化后渲染

将sf多边形转换为栅格数据,从根源上避免矢量多边形的边缘问题:

library(ggplot2)
library(rayshader)
library(sf)
library(raster)

temp <- tempfile()
download.file("https://www.cbs.nl/-/media/cbs/dossiers/nederland-regionaal/vierkanten/500/2022-cbs_vk500_2021_v1.zip", temp)
NLD <- read_sf(utils::unzip(temp, "cbs_vk500_2021_v1.gpkg"))

NLD <- NLD[-c(99:nrow(NLD)),]
NLD$aantal_inwoners <- ifelse(NLD$aantal_inwoners < 0, 1, NLD$aantal_inwoners)

# 将sf数据转换为500米分辨率的栅格
r <- raster(NLD, res=500)
r <- rasterize(NLD, r, field="aantal_inwoners")

# 转换为rayshader可用的矩阵格式
r_mat <- matrix(raster::extract(r, raster::extent(r), buffer=1), 
                nrow=nrow(r), ncol=ncol(r))

# 渲染栅格数据
r_mat %>%
  height_shade(texture = gradient_texture("black", "deeppink")) %>%
  add_overlay(generate_altitude_overlay(r_mat, texture = gradient_texture("black", "deeppink"))) %>%
  plot_3d(r_mat, zscale=10, windowsize=c(800,800), phi=90, theta=0, zoom=0.7)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 03:05:46