Search code examples
rrasterggvis

Multiple layer in a map with ggvis package


I'm using ssplot multiple layers to plot color of provinces inside the regional borders in the italy map. This is my code:

library(raster)
library(latticeExtra)
setwd("c:\\temp")
gadm<-getData('GADM', country='Italy', level=2)
gadm2<-getData('GADM', country='Italy', level=1)

spplot(gadm, "ID_2",col=NA)+
layer(sp.polygons(gadm2, first=F))

Now I'd like to create a interactive map with the ggvis package. I started creating the main map with regional borders:

library(ggvis)
library(ggplot2)
library(rgeos)

#convert in a data frame
map2 <- fortify(gadm2, region="NAME_1")
map<- fortify(gadm, region="NAME_2")


map2%>%
  ggvis(~long, ~lat) %>%
  group_by(group, id) %>%
  layer_paths(strokeOpacity:=0.5, stroke:="#7f7f7f") %>%
   hide_axis("x") %>% hide_axis("y") %>%
  set_options(width=400, height=600, keep_aspect=TRUE)

Now I don't understand how to plot another layer with the provincial colors.


Solution

  • Two keys: layer_paths can take a fill argument to fill the inside of the polygon and you can specify a new dataset in the layer itself (similar to ggplot2).

    map2%>%
      ggvis(~long, ~lat) %>%
      group_by(group, id) %>%
      layer_paths(data = map %>% group_by(group, id), 
                  strokeWidth := 0, fill = ~id) %>%
      layer_paths() %>%
      hide_axis("x") %>% hide_axis("y") %>%
      set_options(width=400, height=600, keep_aspect=TRUE)
    

    (I got rid of strokeOpacity:=0.5, stroke:="#7f7f7f", because I thought that it made it unclear where the borders are, but you could add them back in if you want)