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

terra绘图自定义图例位置异常:图例嵌入栅格范围求助

解决terra栅格绘图图例嵌入栅格的问题

问题原因

在terra::plot()中用plg=list(x="right")设置图例位置时,这里的"right"指的是栅格绘图区域的内部右侧,而非整个画布的外部右侧,因此会导致图例覆盖栅格内容。

解决方案

方法1:用inset参数将图例向外偏移

通过inset设置图例相对于绘图区域的偏移量,负数表示向外偏移,可将图例放到栅格外部:

library(terra)
r <- rast(system.file("ex/elev.tif", package="terra"))
x <- scale_linear(r, 0, 30)
bks <- c(0,0.4,0.8,1.3,2,4,8,15,30)
colors <- c('#3182BD', '#9ECAE1', '#DEEBF7', '#FEE5D9', '#FCAE91',
            '#FB6A4A', '#DE2D26', '#A50F15')

plot(x, col=colors, box=F, axes=F, breaks=bks, reverse=TRUE,
     plg=list(
       x="right",
       title = "Title",
       title.cex = 1.2,
       cex = 1.2,
       inset = -0.2  # 负数向外偏移,可根据图例宽度调整数值
     ))

方法2:手动指定图例绝对坐标

用归一化坐标(范围0-1)直接指定图例位置,让其超出栅格区域:

plot(x, col=colors, box=F, axes=F, breaks=bks, reverse=TRUE,
     plg=list(
       x=1.05,  # 超出栅格的x轴位置
       y=0.5,   # 垂直居中
       title = "Title",
       title.cex = 1.2,
       cex = 1.2
     ))

方法3:用layout拆分绘图区域

预先划分画布为栅格区和图例区,彻底分离两者:

# 拆分画布:左侧80%放栅格,右侧20%放图例
layout(matrix(c(1,2), nrow=1), widths=c(4,1))

# 绘制栅格,关闭默认图例
plot(x, col=colors, box=F, axes=F, breaks=bks, reverse=TRUE, legend=FALSE)

# 在右侧区域单独绘制图例
plot(x, legend.only=TRUE, col=colors, breaks=bks, reverse=TRUE,
     plg=list(
       title = "Title",
       title.cex = 1.2,
       cex = 1.2
     ))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 19:36:01