Home > Enterprise >  How do I add a ggplot map object under another ggplot map object?
How do I add a ggplot map object under another ggplot map object?

Time:10-05

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

CodePudding user response:

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)
  • Related