Search code examples
rfilesizer-plotlyggplotly

Reduce file size of a plot (R) (plotly)


I've created a map in R using ggplotly. To create a link, it needs to be 524kb or under, but it currently is 1.2Mb. Are there any good ways of reducing file size so I can export it? Or is this totally unrealistic?


Solution

  • If your map has polygons, consider rmapshader::ms_simplify(), which uses the Visvalingam algorithm to reduce the number of points used to construct a polygon.

    Here's a reproducible example:

    p  <- raster::shapefile(system.file("external/lux.shp", package = "raster")) # load data
    p2 <- rmapshaper::ms_simplify(p, keep_shapes = TRUE) # simplify polygons
    

    Now visualize the result:

    par(mfrow = c(1,2))
    plot(p,  main = paste("before:", object.size(p),  "bytes"))
    plot(p2, main = paste("after:",  object.size(p2), "bytes"))
    dev.off()
    

    enter image description here

    You can edit the default settings on the keep argument, lowering the number of points to retain, and thus further reducing your object size. This comes at the cost of a coarser image.