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

如何用rayshader的plot_gg()自定义或缩小3D图比例尺三角图例高度

问题描述

使用rayshader包的plot_gg()函数渲染3D地图时,增大scale参数(如scale = 300)后,比例尺图例栏会部分遮挡图表,如何自定义或缩小该图例栏的高度?

用户代码示例:

gg_mai = ggplot(mai_sff) +
  geom_sf(aes(fill = songuoi_km), lwd=0) +
  scale_fill_viridis("Mật độ người/km2", direction = -1, option = "viridis") +
  ggtitle("Họ Mai") +
  theme_bw()

plot_gg(gg_mai, multicore = TRUE, raytrace = TRUE, width = 7, height = 4, 
       scale = 300, windowsize = c(1400, 866), zoom = 0.6, phi = 30, theta = 30)
解决方法

方法1:在ggplot层面调整图例尺寸

通过theme()中的legend.key.height参数直接缩小图例高度,3D渲染时会沿用这个设置:

gg_mai = ggplot(mai_sff) +
  geom_sf(aes(fill = songuoi_km), lwd=0) +
  scale_fill_viridis("Mật độ người/km2", direction = -1, option = "viridis") +
  ggtitle("Họ Mai") +
  theme_bw() +
  theme(legend.key.height = unit(0.8, "cm"))  # 按需调整数值控制高度

plot_gg(gg_mai, multicore = TRUE, raytrace = TRUE, width = 7, height = 4, 
       scale = 300, windowsize = c(1400, 866), zoom = 0.6, phi = 30, theta = 30)

方法2:使用plot_gg的legend_height参数

plot_gg()内置了legend_height参数,可直接指定图例占图表高度的比例(范围0-1),比如设置为0.2:

plot_gg(gg_mai, multicore = TRUE, raytrace = TRUE, width = 7, height = 4, 
       scale = 300, windowsize = c(1400, 866), zoom = 0.6, phi = 30, theta = 30,
       legend_height = 0.2)  # 调整比例缩小图例

方法3:手动添加自定义图例(精细控制)

先隐藏ggplot的图例,再用add_legend()手动添加,自定义位置、高度和宽度:

# 隐藏ggplot中的图例
gg_mai = ggplot(mai_sff) +
  geom_sf(aes(fill = songuoi_km), lwd=0) +
  scale_fill_viridis("Mật độ người/km2", direction = -1, option = "viridis") +
  ggtitle("Họ Mai") +
  theme_bw() +
  theme(legend.position = "none")

# 渲染3D图后添加自定义图例
plot_gg(gg_mai, multicore = TRUE, raytrace = TRUE, width = 7, height = 4, 
       scale = 300, windowsize = c(1400, 866), zoom = 0.6, phi = 30, theta = 30)
add_legend(position = "right", height = 100, width = 20)  # 按需调整尺寸

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 07:31:16