使用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
相关产品推荐
相关产品推荐

