这是我面临的问题的可复制示例。我试图在多个阶段使用ggplot2创建地图。这是我面临的问题。
考虑数据border
,其中美国处于墨西哥边界的州的多边形,border.county
中具有这些州中的县的多边形。以下代码可让您获取数据:
library(maps)
library(ggmap)
library(ggplot2)
USA <- get_googlemap(center = 'usa', zoom = 4,
style = 'administrative|element:labels|visibility:off')
us.df <- map_data("state")
border <- subset(us.df,
region %in% c("california","arizona","new mexico","texas"))
counties <- map_data("county")
border.county <- subset(counties,
region %in% c("california","arizona","new mexico","texas"))
现在,我要创建一个地图,并以Google Maps中的地图为背景,并使用州多边形和县边界。如果我执行以下操作,它将正常工作:
Allmap <- ggmap(USA) +
geom_polygon(aes(x = long, y = lat, fill = region, group = group),
data=border, color = "white") +
geom_polygon(aes(x = long, y = lat, group = group),
data=border.county, fill=NA, color="red")
现在,如果我想分多个阶段创建此地图,则会遇到问题。我只需要县边界作为背景信息(作为一种“经常性主题”),并且我将在州一级创建具有变化信息的多个地图。因此,我与县一起创建了“背景地图”,效果很好:
Countmap <- ggmap(USA) +
geom_polygon(aes(x = long, y = lat, group = group),
data=border.county, fill=NA, color="red")
现在我尝试将其与状态图结合:
Statmap <- ggmap(USA) +
geom_polygon(aes(x = long, y = lat, fill = region, group = group),
data=border, color = "white") +
Countmap
这给了我错误:
Error: Don't know how to add o to a plot
我该如何解决?我可以用其他方式组合地图(例如:Statmap <- Countmap + geom_polygon(aes(x = long, y = lat, fill = region, group = group), data=border, color = "white")
);但是,这使各县处于州界之下。
我也知道,这个特定的问题很容易解决,只需先绘制一张带有州的地图,然后再将其与各县合并即可。但是,在我的实际情况中,这不是一个选择,因为地图的重复主题需要绘制在第二位:城市和地理边界(例如此处的县边界)。
这是我要创建的地图:
答案 0 :(得分:4)
如果我正确理解了您的描述,就不想合并地图。您想结合图层,具体地说,是在不断变化的州级地图上覆盖县轮廓。
尝试一下:
# define county outlines as a geom_polygon layer
county.layer <- geom_polygon(aes(x = long, y = lat, group = group),
data = border.county, fill = NA, color = "red")
# add county.layer as the last layer to your state-level map
Statmap <- ggmap(USA) +
geom_polygon(aes(x = long, y = lat, fill = region, group = group),
data=border, color = "white") +
county.layer
Statmap
根据评论进行编辑
如果要绘制多个县图层,请将它们放在列表中:
border.county2 <- subset(counties, region %in% c("montana"))
layer2 <- list(geom_polygon(aes(x = long, y = lat, group = group),
data = border.county2, fill = NA, color = "blue"),
geom_polygon(aes(x = long, y = lat, group = group),
data = border.county, fill = NA, color = "red"))
Statmap <- ggmap(USA) +
geom_polygon(aes(x = long, y = lat, fill = region, group = group),
data=border, color = "white") +
layer2