I'm astonished by the recurrent problem of size vector cannot be allocated
in geom_raster
function. This problem happens with small data set and in my case 1559 observations. I try to do:
# Read the raster in data frame format
ras_df<-read.csv("https://raw.githubusercontent.com/Leprechault/trash/main/myraster_df.csv")
str(ras_df)
#'data.frame': 1559 obs. of 3 variables:
# $ cc : num 65 85.6 82.7 85.6 89.4 ...
# $ longitude: num -50.6 -50.6 -50.6 -50.6 -50.6 ...
# $ latitude : num -24.2 -24.2 -24.2 -24.2 -24.2 ...
# Representation
ggplot() +
geom_raster(data = ras_df , aes(x = longitude, y = latitude, fill = cc)) +
scale_fill_gradientn(name="Canopy cover",colours = rev(terrain.colors(100)))+
xlab("longitude") + ylab("latitude") +
theme_bw() +
coord_quickmap() +
theme(panel.border = element_blank(), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"),
text=element_text(size=16, family="serif"),legend.position="bottom")
#
#
#Error: 20254.0 Gb size vector cannot be allocated
But if I use the normal plot()
function this does not occur, but I look for a more beautiful representation like ggplot2
output. And several posts with some solutions don't work very well for me (eg. SpatialPixelsDataFrame
conversion and tolerance control).
Please, any ideas for I fix it?
The warning that came with the error was informative
In addition: Warning messages:
1: Raster pixels are placed at uneven horizontal intervals and will be shifted. Consider using geom_tile() instead.
2: Raster pixels are placed at uneven vertical intervals and will be shifted. Consider using geom_tile() instead.
This happen when the data have spurious precision, so geom_raster
tries to make a very fine grid which uses insane amounts of memory.
The solution is simply to round the data to an appropriate amount of precision.
library(tidyverse)
ras_df <- ras_df %>% mutate(across(c(latitude, longitude), round, digits = 4))
The plot then works fine.