Search code examples
rggplot2mapsdata-visualizationfacet

Data visualization: Maps using ggplot2 and facet layout


I would like to create a conditional micromap using R. Basically I would like to create a facet (grid layout) for four different variables in the example below p_1,p_2,q_1,q_2) and plot each states map with color coded 1 for blue and 0 for green.

Below is the sample code. The data that is to be used for color coding is "mydata", 0 for green and 1 for blow for each of the variable p_1,p_2,q_1,q_2 How would I accomplish this in using ggplot.

library(ggplot2)
library(maps)
library(scales) # for function alpha()
us.dat <- map_data("state")

ggplot(us.dat, aes(x=long, y=lat, group=group)) + geom_polygon(fill="grey65", colour = alpha("white", 1/2), size = 0.2) + 
  theme_bw() + theme(legend.position = "none", text = element_blank(), line = element_blank()) + coord_map("polyconic") 

# create random data

states <- unique(us.dat$region)
p_1 <- sample(0:1,49,replace=T)
p_2 <- sample(0:1,49,replace = T)
q_1 <- sample(0:1,49,replace=T)
q_2 <- sample(0:1,49,replace = T)

mydata <- as.data.frame(t(rbind(states,p_1,p_2,q_1,q_2)))

The chart layout below is what I would like to accomplish with one common legend. enter image description here


Solution

  • You need to reformat your data so it is in long format with your variables identified by a key. Then you need to merge it with the spatial data. Then use facet_wrap(~ key) to create the four panels.

    Try this:

    library(dplyr)
    library(tidyr)
    us.dat %>%
      dplyr::left_join(
        mydata %>% 
          tidyr::gather(key, value, -states),
        by = c("region" = "states")
      ) %>%
      ggplot(aes(x=long, y=lat)) + 
      geom_polygon(aes(group=group, fill = value),
                   colour = alpha("white", 1/2), 
                   size = 0.2) + 
      theme_bw() + 
      theme(# legend.position = "none", 
            line = element_blank(),
            axis.text = element_blank(),
            axis.title = element_blank(),
            strip.background = element_blank(),
            panel.border = element_blank()
            ) + 
      coord_map("polyconic") +
      facet_wrap(~ key)
    

    I added a few theme elements to get it to look similar to what you want. You will need to use a scale_fill_manual() to get the colors you want.