使用ggplot2制作插图地图

7

我只是想制作一个简单的学习区域地图,其中还包含我正在工作的州(北卡罗来纳州)的插图。我想将插图转换为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

3
这个链接会有帮助吗?请看这个或者这个。 - eipi10
@Jason,你解决了这个问题吗?如果是的话,怎么解决的?我也遇到了完全相同的问题。谢谢。 - Cirrus
1个回答

5

我经常进行这种操作,发现使用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


请问您能否帮我解决一个问题,即如何在R中绘制多线图(四条线),并对图形进行缩放和插入?我非常感激,因为我遇到了困难! - Stackuser

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接