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

R语言terra包绘图:调整轴标签位置、刻度与图例

Terra包SpatRaster绘图布局调整问题解决方案

问题描述

我是R语言terra包的新手,正在使用该包的plot函数绘制SpatRaster对象,但想要调整多项布局特征却未在网上找到相关信息。示例代码如下:

# Example data 
library(terra)
f <- system.file("ex/elev.tif", package="terra")
r <- rast(f)

## Define colours
colfunc <- colorRampPalette(c("#08306b", "#f7fbff"))

# list with details for legend
plg = list(
        title = expression(bold("Depth [m]")),
        title.cex = 0.9,
        cex = 0.7,
        shrink=0
        )

# list with details for axes
pax = list( 
     sides = c(1,2,3,4),
     labels = T
)
   

plot(r, mar=c(3.1, 3.1, 2.1, 7.1), plg=plg, pax=pax, las=1, col=colfunc(20))

我想实现以下需求:

  • a) 增大图例与坐标轴之间的距离;
  • b) 四个轴均显示刻度,但仅在两个轴上标注刻度标签;
  • c) 生成包含经纬度信息(如N、W)的刻度;
  • d) 修改刻度的位置与标签。

我知晓plot()函数中的plg和pax参数,但未找到这两个参数的完整参数列表,且它们与常规axis函数的参数不同。


解决方案

a) 增大图例与坐标轴之间的距离

可以通过调整plg列表的x参数手动偏移图例位置,同时配合调整右侧边距(mar的第四位数值)来实现:

plg = list(
        title = expression(bold("Depth [m]")),
        title.cex = 0.9,
        cex = 0.7,
        shrink=0,
        x = 1.05  # 向右移动图例,拉开与坐标轴的距离
)
# 调大右侧边距给图例留出空间
plot(r, mar=c(3.1, 3.1, 2.1, 8.1), plg=plg, pax=pax, las=1, col=colfunc(20))

b) 四个轴均显示刻度,但仅在两个轴上标注刻度标签

在pax列表中,将labels设置为对应侧边的逻辑值向量,指定哪些轴显示标签:

pax = list( 
     sides = c(1,2,3,4),  # 四个轴都显示刻度
     labels = c(TRUE, TRUE, FALSE, FALSE)  # 仅底部(1)、左侧(2)显示标签
)
plot(r, mar=c(3.1, 3.1, 2.1, 7.1), plg=plg, pax=pax, las=1, col=colfunc(20))

c) 生成包含经纬度信息(如N、W)的刻度

有两种方式实现:

  1. 手动构建带方向的标签,结合pax的at和labels参数:
# 获取栅格的坐标范围
x_ext <- ext(r)[1:2]
y_ext <- ext(r)[3:4]

# 生成带方向的标签
x_labels <- paste0(round(x_ext, 2), "W")
y_labels <- paste0(round(y_ext, 2), "N")

pax = list(
     sides = c(1,2,3,4),
     at = list(x = x_ext, y = y_ext),  # 指定刻度位置
     labels = list(x = x_labels, y = y_labels)  # 指定带方向的标签
)

plot(r, mar=c(3.1, 3.1, 2.1, 7.1), plg=plg, pax=pax, las=1, col=colfunc(20))
  1. 直接使用degAxis参数自动生成带经纬度方向的轴:
plot(r, mar=c(3.1, 3.1, 2.1, 7.1), plg=plg, degAxis=TRUE, las=1, col=colfunc(20))

d) 修改刻度的位置与标签

通过pax列表的at参数指定自定义刻度位置,labels参数设置对应标签:

# 自定义x轴刻度位置和标签
x_at <- c(6.0, 6.1, 6.2)
x_labels <- c("6°0'E", "6°6'E", "6°12'E")
# 自定义y轴刻度位置和标签
y_at <- c(49.0, 49.1, 49.2)
y_labels <- c("49°0'N", "49°6'N", "49°12'N")

pax = list(
     sides = c(1,2,3,4),
     at = list(x = x_at, y = y_at),
     labels = list(x = x_labels, y = y_labels)
)

plot(r, mar=c(3.1, 3.1, 2.1, 7.1), plg=plg, pax=pax, las=1, col=colfunc(20))

关于plg和pax参数的文档

查看?terra::plot帮助文档,在Arguments章节可找到plg和pax的完整参数说明。这两个参数的设计参考了graphics::legend()和graphics::axis()的参数,部分做了适配以适配栅格绘图的布局逻辑。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 07:20:30