首页 文章

使用ggplot2插入 Map

提问于
浏览
6

我只是想制作一个简单的研究区域 Map ,其中还包含我正在工作的州(北卡罗来纳州)的插图 . 我想将插图 Map 转换为grob对象以在主要研究区域 Map 中绘制它,然后使用ggsave将 Map 保存为图像,pdf等 . 我正在使用shapefile作为我的实际 Map ,但我会告诉你我正在尝试使用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

当我运行脚本以生成最终 Map 时,仅生成研究区域 Map . 我想知道我是否错误地使用ggplotGrob,或者它是其他什么?我可能在其他地方读过,除非你在ggplot2中使用coord_cartesian函数(这里我使用的是coord_fixed),否则annotation_custom函数不起作用 . 如果是这种情况,我可以使用该功能进行类似放大,还是有另一个coord_函数可以放大我的学习区域 Map ?

谢谢,杰伊

1 回答

  • 3

    我经常做这种事情,并且发现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

相关问题