Search code examples
rgoogle-mapsggplot2ggplotly

Lay a region over all USA map in R


I want to plot a map of the following data, dt_plot, which has 2 unique counties in it.

fr      long        lat       group order    region       subregion    polyname
10   -121.031609 48.3060722  2894   85063  washington    chelan       washington,chelan
12   -121.054520 48.3289909  2894   85064  washington    chelan       washington,chelan
22   -121.054520 48.3461800  2894   85065  washington    chelan       washington,chelan
23   -121.037331 48.3519096  2894   85066  washington    snohomish    washington,chelan
34   -121.025871 48.3633690  2894   85067  washington    snohomish    washington,chelan
1    -121.065979 48.3977432  2894   85068  washington    snohomish    washington,chelan
5    -121.134743 47.9680252  2924   86403  washington    snohomish    washington,snohomish

I try the following code from (here):

ggplot(dt_plot, aes(long, lat, group = group)) + 
geom_polygon(aes(fill = fr), colour = rgb(1, 1, 1, 0.2))  +
coord_quickmap()

When I plot it, only the counties in the data set shows up. I want the plot to be laid over all USA. How can I do that? I can add missing sub-regions, however, since I use the column fr for color coding it, if I do that, then the legend will be messed up.


Solution

  • cnty <- map_data("county") # Load the county data from the maps package 
    cnty2<- cnty %>% 
             mutate(polyname = paste(region, subregion,sep=",")) %>% 
             left_join(county.fips, by="polyname") 
    

    and add geom_polygon(data = cnty2) as another layer:

    ggplot(dt_plot, aes(long, lat, group = group)) + 
    geom_polygon(data = cnty2, fill="lightgrey") + 
    geom_polygon(aes(fill = freq), colour = rgb(1, 1, 1, 0.2))  +
    geom_text(data=target_annotation, aes(long, lat, label = subregion)) + 
    coord_quickmap()