Search code examples
rggplot2data-analysischoroplethusmap

R:How to display city level data on map and how to ZOOM it on one specific region of the map


I am using usmap and ggplot to plot population on a map. My data has two columns - population and zipcodes.

Question: How can I display data on city level using the same libraries or if you know of other libraries that can do the job.

Question: I am plotting California map and I want to zoom on LA county and nearby counties.

Below code gives me a nice California map and population as a color.

library(usmap)
library(ggplot2)

usmap::plot_usmap("counties", 
              include = ("CA") )

plot_usmap(data = data, values = "pop_2015", include = c("CA"), color = "grey") + 
theme(legend.position = "right")+scale_fill_gradient(trans = "log10")

Solution

  • The tigris package makes downloading zip code tabulation areas fairly simple. You can download as a simple features dataframe so joining your data by zip code using dplyr functions is fairly easy. Here is a quick example:

    library(tigris)
    library(dplyr)
    library(ggplot2)
    
    df <- zctas(cb = TRUE,
                starts_with = c("778"), 
                class = "sf")
    
    ## generate some sample data that
    ## can be joined to the downloaded data
    sample_data <- tibble(zips = df$ZCTA5CE10,
                          values = rnorm(n = df$ZCTA5CE10))
    
    
    ## left join the sample data to the downloaded data
    df <- df %>%
      left_join(sample_data, 
                by = c("ZCTA5CE10" = "zips"))
    
    ## plot something
    ggplot(df) +
      geom_sf(aes(fill = values))
    

    sample plot