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

使用scales::pretty_breaks搭配geom_spatraster报错的解决方法

Solution

The error occurs because scale_x_continuous and scale_y_continuous aren't optimized to work with geom_spatraster's coordinate system handling. Instead, use tidyterra's raster-specific scale functions: scale_x_raster() and scale_y_raster(), which are designed to properly interface with the spatial coordinates of your raster data.

Corrected Code

library(terra)
library(ggplot2)
library(tidyterra)

r1 <- rast(system.file("ex/elev.tif", package="terra"))
r2 <- r1 

r <- c(r1, r2)

names(r) <- c("R1", "R2")

p <- ggplot() +
  geom_spatraster(data = r) +
  facet_wrap(~lyr, ncol = 2)+
  scale_fill_viridis_c(na.value = "transparent", name = "Elevation",
                       option = "viridis", direction = -1) +
  theme(text=element_text(family = "serif", size=15), 
        axis.text.x = element_text(colour="black"), 
        axis.text.y = element_text(colour="black", angle = 90, hjust = 0.5))

# Use raster-specific scales instead of continuous scales
p + scale_x_raster(breaks = scales::pretty_breaks(n = 3)) +
  scale_y_raster(breaks = scales::pretty_breaks(n = 3))

Explanation

scale_x_raster and scale_y_raster handle the spatial coordinates from your SpatRaster correctly, ensuring that scales::pretty_breaks receives valid numeric limits (instead of a closure/function) to generate appropriate axis breaks. This resolves the invalid 'type' (closure) of argument error.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 13:34:59