0

I want to add a background map (stored as a ggplot object) to another ggplot map because some states have NA's that I removed, so they are left out of the map. I used patchwork to try to combine, but it only puts them side by side. I want the back_map to go "under" p.

library(ggplot2)
library(tidyverse)
library(mapdata)
library(patchwork)
library(dplyr)

MainStates <- map_data("state")
State_Name <- c("alabama","arkansas","arizona","california","colorado")
Sales <- c(100,200,250,275,310)
df2 <- data.frame(State_Name,Sales)
MergedStates <- inner_join(MainStates, df2, by = c("region" = "State_Name"))
back_map <- ggplot() + geom_polygon(data=MainStates, aes(x=long, y=lat, group=group),
                       color="black", fill="white")

p <- ggplot() + geom_polygon(data = MergedStates,
                             aes(x=long, y=lat, group=group),
                             fill = ifelse(MergedStates$Sales <= 
                                      mean(MergedStates$Sales),"red","green"), size = 0.2) 
                                      + back_map
p
Vinícius Félix
  • 8,448
  • 6
  • 16
  • 32
Rob Rosene
  • 15
  • 2
  • I haven't run your code yet, but usually when I'm making maps with missing data, I make sure to use a join type that will include missing data, such as a left join with my areas (states, etc) on the left. That way the shape will be drawn but have a NA value – camille Oct 01 '21 at 18:47
  • Also you can ([and probably should](https://stackoverflow.com/q/32543340/5325862)) use your `ifelse` statement to assign the fill *inside* `aes`, without using the `$` – camille Oct 01 '21 at 18:48
  • Besides the comments by camille: There is no need for patchwork. You could plot your second map on top of. the first using `ggplot() + geom_polygon() + geom_polygon()` – stefan Oct 01 '21 at 19:04

1 Answers1

0

Don't need to make a separate back_map object. Background map goes first in the code like such:

    p <- ggplot() + geom_polygon(data = MainStates, aes(x=long, y=lat, 
    group=group),
           color = "black", fill = "white") +
      geom_polygon(data = MergedStates,
           aes(x=long, y=lat, group=group), 
           fill = ifelse(MergedStates$sngIYA <= 
    mean(MergedStates$sngIYA),"red","green"), 
           color = "black", size = 0.2)
Rob Rosene
  • 15
  • 2