我只是想制作一个简单的学习区域地图,其中还包含我正在工作的州(北卡罗来纳州)的插图。我想将插图转换为grob对象,以便在主学习区域地图中绘制它,然后使用ggsave将地图保存为图像、pdf等格式。我正在使用实际地图的shapefiles,但我会向您展示我正在尝试使用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
当我运行脚本以生成最终地图时,仅生成了研究区域地图。我想知道我是否错误地使用了ggplotGrob,或者是其他原因?我可能已经在其他地方读到过,annotation_custom函数只有在使用ggplot2中的coord_cartesian函数时才起作用(而我正在使用coord_fixed)。如果是这种情况,我是否可以使用该函数进行类似的缩放,或者是否存在另一个coord_函数以缩小我的研究区域地图?
谢谢, Jay