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

使用rayshader绘制ggplot2对象时路径偏移问题求助

问题:rayshader中路径与世界地图位置不匹配

我用rnaturalearth绘制世界地图转成ggplot2对象,再用rayshader的plot_gg渲染3D地图,但添加render_path绘制柏林到坎昆的路径后,路径位置偏高、长度过长。怀疑是ggplot2地图的白边导致坐标偏移,调整宽高比也没解决问题。原代码如下:

#load libraries
library(sf)
library(rayshader)
library(rayrender)
library(rnaturalearth)
library(rnaturalearthdata)
library(tidyverse)

#get ggplot object of world
world <- ne_countries(scale = "medium", returnclass = "sf")
ggData = ggplot(data = world) + geom_sf()

#latitudes, longitudes of Berlin and Cancun as list for render_path()
lats = list()
lats[1] = 52.5
lats[2] = 21.1

longs = list()
longs[1] = 13.4
longs[2] = -86.8
 
#Altitude of the path 
alts = list()
alts[1] = 100
alts[2] = 100

#plot with rayshader, width and height ratio of bbox of ggData
plot_gg(ggData, scale=10, width=3.6, height=1.7359854)
render_path(lat = unlist(lats), long = unlist(longs), zscale=50, color="red", antialias=TRUE, linewidth=3, extent=st_bbox(world), altitude=unlist(alts))

核心问题

render_path用了原始sf数据的st_bbox(world)作为extent,但ggplot2绘图会自动添加白边,导致实际渲染的坐标范围和原始数据的bbox不一致,路径就会错位。

修正方案

  1. 保存plot_gg的返回值,它包含了渲染时的实际坐标范围
  2. 用这个返回的extent替代st_bbox(world)
  3. 把list存储的坐标改成向量,代码更简洁

修正后的代码:

# 加载库
library(sf)
library(rayshader)
library(rayrender)
library(rnaturalearth)
library(rnaturalearthdata)
library(tidyverse)

# 获取世界地图并生成ggplot对象
world <- ne_countries(scale = "medium", returnclass = "sf")
ggData <- ggplot(data = world) + geom_sf()

# 柏林和坎昆的坐标(直接用向量,无需list)
lats <- c(52.5200, 21.1619)
longs <- c(13.4050, -86.8515)
alts <- c(100, 100)

# 执行plot_gg并保存返回结果,里面包含实际渲染的extent
plot_result <- plot_gg(ggData, scale=10, width=3.6, height=1.7359854)

# 使用渲染后的extent对齐路径
render_path(
  lat = lats, 
  long = longs, 
  zscale = 50, 
  color = "red", 
  antialias = TRUE, 
  linewidth = 3, 
  extent = plot_result$extent,  # 关键:用这个extent替代原始bbox
  altitude = alts
)

说明

  • plot_gg返回的plot_result$extent记录了ggplot2带白边的实际渲染范围,用它作为render_path的extent参数,就能让路径和地图完美匹配。
  • 把list换成向量,既简化代码,也更符合rayshader参数的输入规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 10:05:28