使用grid.newpage创建带有插图的ggplot贴图

时间:2015-07-24 21:53:52

标签: r ggplot2 rgdal r-raster sp

按照一个非常有用的例子here。我拼凑了一个用插图在ggplot中创建的地图的代码。

# Clear WD
rm(list=ls())

library(sp)
library(ggplot2)
library(raster)
library(rgeos)
library(gridExtra)

# Download the Level 0 Map for Inset
ind0 <- getData("GADM", country="IDN", level=0) 
    # Decrease Resolution of the National Map for the Inset
    ind01<- gSimplify(ind0, tol=.1)

# Download level 2 Map 
ind2 <- getData("GADM", country="IDN", level=2) # ucdavis site

jawa  <- (ind2[grep(x=ind2$NAME_1, pattern="Jawa"),]) # subset to island of Jawa

# Extent rectangle for inset map
pol <- data.frame(xmin=114,xmax=119, ymin=-6.5 ,ymax=-5)

batang <- jawa[which(jawa@data$NAME_2=="Batang"),]
    munnames <- coordinates(batang) # get center coordinates of 
    munnames <- data.frame(munnames) # convert matrix format munnames object to data.frame
    munnames$label <- batang@data$NAME_2


# Main Map
p1 <- ggplot() + geom_polygon(data=jawa, aes(long+0.008,lat-0.005, group=group), fill="#9ecae1") + coord_equal()+theme_bw() + xlab("")+ylab("") +  theme(axis.text.y =element_text(angle = 90, hjust=0.5)) + geom_polygon(data=batang, aes(long, lat, group=group), fill="coral1") + geom_text(data=munnames, aes(x=X1, y=X2+.3,label=label), size=3, colour="grey20", family="Times") + guides(fill=FALSE) + annotate("text", x=108.5, y=-5.5, label="Island of Java", family="Times") + scale_x_continuous(breaks=seq(104, 116, 2), labels=c(paste(seq(104, 116, 2),"°E", sep=""))) + scale_y_continuous(breaks=seq(-9, -5, 1), labels=c(paste(seq(-9, -5, 1),"°N", sep="")))

#Inset
p2 <- ggplot() + geom_polygon(data=ind0, aes(long,lat,group=group), fill="#9ecae1") + coord_equal() + theme_bw() + labs(x=NULL,y=NULL) + geom_rect(data = pol, aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax), alpha=0, colour="red", size = 1, linetype=1) + theme(axis.text.x =element_blank(),axis.text.y= element_blank(), axis.ticks=element_blank(),axis.title.x =element_blank(), axis.title.y= element_blank())

这是我遇到问题的地方。使用grid.newpage和viewport我的计算机在打印插图时会停止。我究竟做错了什么?你会注意到我甚至都在努力降低插入的国家形状文件的分辨率。

png(file="cj3.png",w=1800,h=1800, res=300, bg = "transparent")
grid.newpage()
    v1<-viewport(width = 1, height = 1, x = 0.5, y = 0.5) #plot area for the main map
    v2<-viewport(width = 0.3, height = 0.3, x = 0.80, y = 0.80) #plot area for the inset map
    print(p1,vp=v1) 
    print(p2,vp=v2)
dev.off()

提前致谢。

1 个答案:

答案 0 :(得分:0)

如果您正在寻找的是*this* image,请查看您的第一个块,以简化来源:

ind01<- gSimplify(ind0, tol=.1)

现在,看看p2块

p2 <- ggplot() + geom_polygon(data=ind0, ...

使用 un 简化版 ind0 而不是 ind01 。我的旧Mac Air挂在原件上,但在纠正p2中的数据参数后不到一分钟就完成了。