qdread / biodiversity-farm2fork

App for interactive visualization of food system biodiversity scenario model results
https://qdread.shinyapps.io/biodiversity-farm2fork/
1 stars 1 forks source link

Maps render veeery slowly #17

Open qdread opened 2 years ago

qdread commented 2 years ago

It's a case of ggplot2 geom_sf being lumberingly slow. It's not an issue for the world map which only has a couple hundred country polygons, but it is an issue for the US map with >3000 county polygons. @khondula any idea of how to speed that up?

khondula commented 2 years ago

I meant to ask, because yes this seems to be the biggest issue for responsiveness -- did you st_simplify the polygons?

qdread commented 2 years ago

No but I will give it a whirl

qdread commented 2 years ago

How bout this? https://www.r-bloggers.com/2021/03/simplifying-geospatial-features-in-r-with-sf-and-rmapshaper/

I noticed that st_simplify messes up the topology so there are gaps between the states. So I used rmapshaper::ms_simplify() instead. I simplified it down to retain only 2% of the original amount of vertices. I tried to do more but it was getting rid of entire counties. But it looks like now we can draw the map by a factor of 4x faster:

csimp2 <- ms_simplify(county_map, keep = 0.02, keep_shapes = F)
microbenchmark(print(ggplot() + geom_sf(data=st_geometry(county_map))), 
  print(ggplot() + geom_sf(data = st_geometry(csimp2))), 
  times = 5L)
Unit: seconds
                                                             expr      min       lq     mean   median       uq      max neval cld
 print(ggplot() + geom_sf(data = st_geometry(county_map))) 4.609019 5.104227 6.075904 6.784636 6.872914 7.008722     5   b
     print(ggplot() + geom_sf(data = st_geometry(csimp2))) 1.231378 1.421315 2.212951 1.497548 3.345961 3.568552     5  a 
qdread commented 2 years ago

The simplified map is now live as of commit 5d0e935 but I'll leave the issue open in case there are any more improvements.