如何在R语言Rayshader 3D地图中按地图形状添加标签
解决Rayshader 3D地图标签位置不符预期的问题
问题根源
- 代码中额外导出/导入质心数据属于冗余操作,还可能因数据分离导致标签与对应区域错位
geom_text直接调用外部point数据集的坐标,未与nc主数据集绑定,数据顺序变动时会出现匹配错误- 基于ggplot生成的2D标签在3D渲染时,会因透视变换产生位置偏移
解决方案
方案1:修正ggplot数据关联,减少透视影响
直接在nc数据集中计算质心并绑定,保证标签与区域一一对应,同时调整视角参数降低透视错位:
library(sf) library(ggplot2) library(rayshader) # 读取数据并计算质心,直接添加到nc数据框 nc = st_read(system.file("shape/nc.shp", package="sf"), quiet = TRUE) nc$centroid = st_centroid(nc) nc$X = st_coordinates(nc$centroid)[,1] nc$Y = st_coordinates(nc$centroid)[,2] # 构建ggplot,使用nc自身的坐标与名称,确保关联正确 gg_nc = ggplot(nc) + geom_sf(aes(fill = AREA)) + geom_text(aes(x = X, y = Y, label = NAME), size = 2, color = 'white') + ggtitle("Area of counties in North Carolina") + theme_bw() # 降低fov值减少透视对标签的影响 plot_gg(gg_nc, multicore = TRUE, width = 6, height = 2.7, fov = 40, scale = 100)
方案2:用Rayshader原生方法添加3D标签(推荐)
先渲染3D地形,再用render_label直接在3D场景中添加标签,标签会贴合地形位置,彻底避免透视错位:
library(sf) library(ggplot2) library(rayshader) nc = st_read(system.file("shape/nc.shp", package="sf"), quiet = TRUE) # 生成基础2D地图 gg_nc = ggplot(nc) + geom_sf(aes(fill = AREA)) + ggtitle("Area of counties in North Carolina") + theme_bw() # 渲染3D场景并返回场景对象 scene = plot_gg(gg_nc, multicore = TRUE, width = 6, height = 2.7, fov = 70, return_rayshader = TRUE) # 计算质心并转换为3D坐标 nc$centroid = st_centroid(nc) nc$X = st_coordinates(nc$centroid)[,1] nc$Y = st_coordinates(nc$centroid)[,2] coords = convert_xy_to_3d(nc$X, nc$Y, scene$heightmap, scene$extent) # 添加3D标签(z轴加偏移避免被地形遮挡) scene = render_label(scene, x = coords$x, y = coords$y, z = coords$z + 50, text = nc$NAME, text_size = 1, color = "white", clear_previous = FALSE) # 展示最终场景 render_scene(scene)
内容的提问来源于stack exchange,提问作者Eriza
相关产品推荐
相关产品推荐

