I downloaded raster data of world elevation from here: https://www.naturalearthdata.com/downloads/10m-raster-data/10m-cross-blend-hypso/ --> Cross Blended Hypso with Relief, Water, Drains, and Ocean Bottom --> Shaded Relief, Water, Drainages, and Ocean Bottom Land coloring based on elevation. Download large size (385.56 MB) version 3.2.0.
I used code below to plot the raster file:
library(terra)
library(tidyterra)
library(tidyverse)
library(viridis)
globRaster <- terra::rast("E:\\Research\\Study\\calvarium\\Maps\\globRaster\\HYP_HR_SR_OB_DR.tif")
pp <- ggplot() + geom_spatraster_rgb(data = globRaster, maxcell = 1e+06, alpha = 1)
# Clear memory
gc()
ggsave("globRaster.pdf", pp,
width = 90, height = 45, units = "mm", bg = "white")
I then tried to convert the raster image to hatano projection style following this:
globRaster2 <- project(globRaster, method = "near", "+proj=hatano", mask=TRUE)
pp2 <- ggplot() + geom_spatraster_rgb(data = globRaster2, maxcell = 1e+06, alpha = 1)
gc()
ggsave("globRaster2.pdf", pp2,
width = 90, height = 45, units = "mm", bg = "white")
Here is some information:
> globRaster
class : SpatRaster
size : 10800, 21600, 3 (nrow, ncol, nlyr)
resolution : 0.01666667, 0.01666667 (x, y)
extent : -180, 180, -90, 90 (xmin, xmax, ymin, ymax)
coord. ref. : lon/lat WGS 84 (EPSG:4326)
source : HYP_HR_SR_OB_DR.tif
colors RGB : 1, 2, 3
names : HYP_HR_SR_OB_DR_1, HYP_HR_SR_OB_DR_2, HYP_HR_SR_OB_DR_3
> globRaster2
class : SpatRaster
size : 13634, 28140, 3 (nrow, ncol, nlyr)
resolution : 1210.47, 1210.513 (x, y)
extent : -17031882, 17030741, -8143807, 8360326 (xmin, xmax, ymin, ymax)
coord. ref. : +proj=hatano +datum=WGS84 +units=m +no_defs
source : spat_2fa413487c42_12196_80Q6udnsxVen2Mq.tif
colors RGB : 1, 2, 3
names : HYP_HR_SR_OB_DR_1, HYP_HR_SR_OB_DR_2, HYP_HR_SR_OB_DR_3
min values : 60, 124, 112
max values : 237, 243, 252
> hasValues(globRaster)
[1] TRUE
> hasValues(globRaster2)
[1] TRUE
Why after projection, the raster image is blank but globRaster2 still has values? How to solve it?
The issue you are observing is related to this and this. For some reason, calling mask =
inside some terra
functions can cause unexpected issues for large SpatRasters.
The fix in your case is to create a SpatVector and use it in a separate mask()
call:
library(terra)
library(tidyterra)
library(ggplot2)
# Load data
r <- rast("HYP_HR_SR_OB_DR.tif")
# Create mask (increase densify() value for smoother curves at min/max longitude)
v <- vect(ext(-180, 180, -90, 90), crs = "EPSG:4326") |>
densify(1e4) |>
project("+proj=hatano")
# project(), then mask()
r1 <- project(r, method = "near", "+proj=hatano")
r1 <- mask(r1, v)
ggplot() +
geom_spatraster_rgb(data = r1, maxcell = 1e+06, alpha = 1)
It works writing to PDF too, but the above image is a JPEG to keep the file size small.