2

I want to create a map using 'ggplot2'. My data contains shapefile (points data), polygons (European countries). Underneath the vector data, I wanted to place the raster showing extends of forests over Europe, available here. The raster size of disk is 150 MB, has dimension of 46000 and 65000. To use it in ggplot, I need to first convert it to dataframe: raster_df<-as.data.frame(raster).

But, I got an error: Error: cannot allocate vector of size 11.1 G. I do not understand why I got this error? How to make sure that I can plot my raster with vector data using ggplot2?

Dummy example:

# read raster
forest <- raster(paste(getwd(), "eea_r_3035_100_m_forest-area-2015_p_2015_v1_r1.tif", sep = "/"))

# convert to dataframe for ggplot2()
forest_df <- as.data.frame(forest, xy = TRUE) 

# Plot the raster data on top of European countries
ggplot(data = europe) + 
geom_fs() +
geom_raster(data = forest) 

EDIT:

I have increased my memory.limit(12000) and this allows me to create a dataframe or a stars object that I can both plot with ggplot2. But, the display still takes forewer. When I visualize the map in ArcGIS or QGIS, the plotting takes a second. Isn't there something as efficient to plot rasters and use them in a map in R? tmap::tm_raster() seems promissing but other suggestions are welcome!

1

It seems an error in allocating enough memory size. Check memory allocation by memory.limit():

memory.limit()
[1] 4002  

Then you can increase - let's say triple - the allocated memory size.

memory.limit(12000)
[1] 12000

I used stars package as below, but your code should work after increasing the memory allocation;

library(ggplot2)
library(stars)

f = "C:/Users/userr/Downloads/ForestArea2015/eea_r_3035_100_m_forest-area-2015_p_2015_v1_r1.tif"
forest = read_stars(f, NA_value = 65535)

ggplot() +
  geom_stars(data = forest, downsample = 10) +
  scale_fill_gradient(low= "white", high = "green")+
  coord_fixed()

enter image description here

3
  • thanks you for nice display and way how to use stars object within ggplot! I have discovered stars just recently, and I am still quite confuse about them...
    – maycca
    Feb 8 at 8:10
  • @Kazuito, still it takes forewer to run and plot it. Is there any other way how to effectively plot the raster data? One way is to simply crop it. It takes a second to plot it in ArcGIS or in QGIS. How to do it in R but with the same ease?
    – maycca
    Feb 8 at 16:32
  • @maycca Same here, when I use ggplot2. But plot(forest) will show the map instantly.
    – Kazuhito
    Feb 9 at 4:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.