Search code examples
rrstudiointeractiveggvis

Creating US Map Including State Borders in ggvis


I'm attempting to make a US map that I can later add interactive layers to. Based on the polygon created, there seems to be an order issue, however; I've ordered them a few different ways, and none of them seemed to work properly. Any help would be appreciated.

library(ggplot2) 
library(ggvis) 
library(dplyr) 

mdat<-map_data("state") 

mdat %>% 
  arrange(group,order) %>% 
  ggvis(x=~long,y=~lat) %>% 
  layer_paths() 

Solution

  • I yanked a bit from the post I linked to for a more complete example (that includes using a much saner projection for the contiguous 48 US states):

    library(ggplot2)
    library(ggvis)
    library(dplyr)
    library(rgdal)
    library(httr)
    
    # decent US shapefile and httr lets us only d/l when needed
    stop_for_status(GET("http://eric.clst.org/wupl/Stuff/gz_2010_us_040_00_500k.json",
                    write_disk("us.geojson"), progress()))
    
    states <- readOGR("us.geojson", "OGRGeoJSON")
    states <- states[!states$NAME %in% c("Alaska", "Hawaii", "Puerto Rico", "District of Columbia"),]
    states_aea <- spTransform(states, CRS("+proj=laea +lat_0=45 +lon_0=-100 +x_0=0 +y_0=0 +a=6370997 +b=6370997 +units=m +no_defs"))
    
    states_map <- fortify(states_aea, region="NAME")
    
    states_map %>%
      group_by(group) %>%
      ggvis(~long, ~lat) %>%
      layer_paths(strokeOpacity := 0.5, strokeWidth := 0.5) %>%
      hide_axis("x") %>% hide_axis("y") %>%
      set_options(width=960, height=600, keep_aspect=TRUE)
    

    enter image description here