2

I've got two ggplot maps which both use the same shapefile. One is the data and the other is the names of each country. Currently they are in seperate ggplots but how do I add the names over the top of my existing one (plot1)?

cnames <- aggregate(cbind(long, lat) ~ region, data=map, 
                    FUN=function(x)mean(range(x)))
names <-ggplot(map, aes(long, lat)) +  
    geom_polygon(aes(x = long, y = lat, group=group), colour='black', fill=NA) +
    geom_text(data=cnames, aes(long, lat, label = region), size=2) +
    coord_map()

plot1 <- ggplot(map, aes(x=long,y = lat, group = group, fill = map$`data`)) + geom_polygon(colour="black") + coord_map("polyconic") + labs(fill = "data") + theme(axis.title.x=element_blank(),axis.text.x=element_blank(),
        axis.ticks.x=element_blank(),axis.title.y=element_blank(),axis.text.y=element_blank(),axis.ticks.y=element_blank())
  plot1 <- plot1 + ggtitle("data")
  plot1 <- plot1 + scale_fill_gradient2(low = muted("grey"), high = muted("deepskyblue4"))
  • 1
    Like with your last question, can you add a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)? It's hard to know what you're working with, you have the error-prone `$` syntax I mentioned before, and we can't see any output so it's unclear what exactly you have and what you want to change – camille Feb 14 '20 at 15:49
  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions.. In general if you want one plot you should be adding layers to a single plot object rather than creating multiple plot objects. – MrFlick Feb 14 '20 at 15:49

1 Answers1

1

I suppose you can just add the layers together, like this:

invisible(lapply(c("ggplot2", "scales", "mapproj"), require, character.only = TRUE))
#> Loading required package: ggplot2
#> Loading required package: scales
#> Loading required package: mapproj
#> Loading required package: maps
map <- map_data("state")

cnames <- aggregate(cbind(long, lat) ~ region, data=map, 
    FUN=function(x)mean(range(x)))

    ggplot(map, aes(
        x = long,
        y = lat,
        group = group,
        fill = as.numeric(factor(map$region))
    )) + 
    scale_fill_gradient2(low = muted("grey"), high = muted("deepskyblue4"))+
    geom_polygon(colour = "black") +
    geom_text(data=cnames, aes(long, lat, label = region), size=2, inherit.aes = FALSE) +
    coord_map("polyconic") + 
    labs(fill = "region") + 
    theme(
        axis.title.x = element_blank(),
        axis.text.x = element_blank(),
        axis.ticks.x = element_blank(),
        axis.title.y = element_blank(),
        axis.text.y = element_blank(),
        axis.ticks.y = element_blank()
    ) + 
    ggtitle("data")

user12728748
  • 8,106
  • 2
  • 9
  • 14