Search code examples
rmemory-managementannotationsggplot2raster

using ggplot's "annotation_raster" and reached R's "memory ceiling"


I am using R to create a floorplan of a house with several layers like below, starting from the bottom layer:

  • basemap: a scanned version of the floorplan which I put it at the bottom layer to aid the reading
  • bed: the house have several dozens of beds, scattered in different rooms of the house, they have different colours based on the characteristics of the residents
  • piechart: each bed has a piechart of top of it, again the piecharts are created based on the residents' other set of characteristics, some beds have piecharts, some don't.

The bed and piechart were created based on the shp file created based on the basemap (i.e. I use Mapwindow the create a vector layer, import the basemap as raster layer and put it at the bottom, then draw the beds one by one. The bed shp file is then imported into R, the bed polygons' centroid are calculated and that centroid helps to position the piecharts)

I used read.jpeg to import the basemap to imagematrix object, then use the new annotation_raster function in ggplot2 0.9 to put the basemap at the bottom map layer, since the bed layer is created based on the basemap also, the bed layer superimpose on the basemap layer perfectly in ggplot2.

I can create the map without problem - if the basemap is small enough (3000 x 3000 pixels), now I have a basemap of 8000+ x 3000+ pixels (object.size 241823624 bytes), I did not aware of the R memory issue when I was creating the shp file, the ggplot object can be compiled if I have the annotation_raster disabled, but R keeps saying that I can allocate memory with xxxMB when I try to include the basemap into the ggplot object.

I think this is nothing to do with the compression of the jpg files, as the dimension is not changed even I further compress the jpg file. But I can't resize the jpg file as my bed layer is created based on the original jpg file's dimension.

Can anyone help to shrink the size of the basemap's imagematrix, without changing the jpeg's dimension, or some other tricks to deal the R's memory limitation? Thanks.


Solution

  • I fixed it.

    I first created a new basemap image file with width and height halved, then in the annotation_raster I did the following:

    chart <- chart + annotation_raster(db$temp.basemap,
                                       xmin=0,
                                       xmax=basemap.xlength*2,  # I stretched the image in R
                                       ymin=0,
                                       ymax=basemap.ylength*2)  # I stretched the image in R
    

    Now the map can be compiled within R's memory limit, the drawback I can think of is the reduce in image quality, but that is bearable, as it was 8000 x 3000 originally.