在R中的地图上添加绘图

时间:2018-05-31 13:15:43

标签: r

我想在几个地点的世界地图上添加地块。

使用此代码,我可以在地图上添加点:

# Worldmap with two sites
library(rworldmap)
plot(worldmap[which(worldmap$REGION != "Antarctica"), ])
points(c(3, 80), c(10, 40), cex = 3, pch = 16)

enter image description here

但不是这两点,我想添加以下两个图:

# Plots associated to these two sites
x_list <- list()
x_list[[1]] <- rnorm(12, 10, 1)
x_list[[2]] <- rnorm(12, 15, 1)

y_list <- list()
y_list[[1]] <- rnorm(12, 10, 1)
y_list[[2]] <- rnorm(12, 15, 1)

plot(x_list[[1]], y_list[[1]], pch = 16)
plot(x_list[[2]], y_list[[2]], pch = 16)

结果应该返回如下内容: enter image description here

如何实现此目标(使用base语法或使用ggplot2)?

1 个答案:

答案 0 :(得分:0)

您可以使用annotation_custom中的ggplot2插入插图:

library(ggplot2)
library(dplyr)
worldmap <- map_data("world") %>% 
  filter(region != "Antarctica")
g1 <- ggplotGrob(
    ggplot() +
      geom_point(aes(x = x_list[[1]], y = y_list[[1]])) +
      theme_void() +
      theme(plot.background = element_rect(fill = "white")))
g2 <- ggplotGrob(
    ggplot() +
      geom_point(aes(x = x_list[[2]], y = y_list[[2]])) +
      theme_void() +
      theme(plot.background = element_rect(fill = "white")))
p <- ggplot(worldmap, aes(x=long, y=lat, group=group)) +
  geom_map(map = worldmap,
           aes(map_id = region),
           fill = "white",
           colour = "#7f7f7f",
           size = 0.5) 
p + 
  annotation_custom(grob = g1, xmin = 0, xmax = 40, ymin = 20, ymax = 40) +
  annotation_custom(grob = g1, xmin = 80, xmax = 120, ymin = 0, ymax = 20)

enter image description here