Insert a map using ggplot2

I'm just trying to create a simple map of a study area that also contains an insertion of the state in which I work (North Carolina). I would like to convert the insert map to a grob object to build it within the main map of the study area, and then use ggsave to save the map as an image, pdf, etc. I use shapefiles for my actual map, but I will show that I'm trying to use map_data:

library(ggplot2)
library(ggmap)
library(maps)
library(mapdata)
library(gridExtra)
library(grid)

# get the NC data:
states <- map_data("state")
nc_df <- subset(states, region == "north carolina")

# study area map:
nc_base <- ggplot() + 
geom_polygon(data = nc_df, aes(x = long, y = lat, group = group), fill="grey", color="black") +
coord_fixed(xlim=c(-80, -77.5), ylim=c(33.5, 34.9), ratio = 1.3) +
theme_bw()
nc_base

# inset map:
insetmap<-ggplot() + 
geom_polygon(data = nc_df, aes(x = long, y = lat, group = group), fill="grey", color="black")  + # get the state border back on top
coord_fixed(ratio = 1.3) +
annotate(geom = "rect", ymax = 34.9, ymin = 33.5, xmax = -77.5, xmin = -80, colour = "red", fill = NA) +
ylab("") +
xlab("") +
theme_nothing()
insetmap

insetmap.grob <- ggplotGrob(insetmap)

final_map <- nc_base + annotation_custom(insetmap.grob, xmin=-79.5, xmax=-79, ymin=33.75, ymax=34)
final_map

script , . , ggplotGrob, - ? , , annotation_custom , cop_cartesian ggplot2 ( cop_fixed). , , Coord_ ?

,

+4
1

, grid:: viewport ... , ggsave, , ggsave . :

nc_base <- ggplot() + 
  geom_polygon(data = nc_df, aes(x = long, y = lat, group = group), fill="grey", color="black") +
  coord_fixed(xlim=c(-80, -77.5), ylim=c(33.5, 34.9), ratio = 1.3) +
  theme_bw()
print(nc_base)

# inset map:
insetmap <- ggplot() + 
  geom_polygon(data = nc_df, aes(x = long, y = lat, group = group), fill="grey", color="black")  + # get the state border back on top
  coord_fixed(ratio = 1.3) +
  annotate(geom = "rect", ymax = 34.9, ymin = 33.5, xmax = -77.5, xmin = -80, colour = "red", fill = NA) +
  ylab("") +
  xlab("") + 
# used theme_inset instead of theme_nothing
  theme_inset()
print(insetmap)

# save where you want to with filename arg in png(). Currently saves 'map.png' to your working directory
# set resolution, width, height
png(filename = "map.png", width = 1150, height = 800, res = 300)
# create a viewport for inset
# vp_inset width/height arguments set the size of the inset; x and y arguments set the position (from 0 to 1) of the left, top corner of the inset along each axis (i.e. not map coordinates as you have in your annotation custom). You can adjust these as you see fit.
vp_inset <- grid::viewport(width = 0.35, height = 0.35, x = 0.2, y = 0.5, just = c("left", "top"))
print(nc_base)
print(insetmap, vp = vp_inset)
dev.off()

enter image description here

+1

Source: https://habr.com/ru/post/1619743/


All Articles