r - 使用 ggplot 在绘图上绘制地图
问题描述
如果我想在情节上绘制地图,我这样做
library(ggplot2)
library(sf)
library(cowplot)
library(gridExtra)
library(raster)
df <- data.frame(x = 1980:1999, y = sample(1:20, 20, replace = T))
shp.dat <- getData('GADM', country='FRA', level=1)
shp.dat <- shp.dat %>% st_as_sf()
p <- ggplot(df, aes(x = x, y = y)) + geom_line() + ylim(0, 100)
p.shp <- ggplot() +
geom_sf(data = shp.dat, fill = ifelse(shp.dat$ID_1 == 1,"red", "grey"))
inset_map <- ggdraw() + draw_plot(p, 0, 0, 1, 1) + draw_plot(p.shp, 0.5, 0.52, 0.5, 0.4)
inset_map
现在我有四个像这样绘制的图
df <- data.frame(x = 1980:1999,
y1 = sample(1:20, 20, replace = T),
y2 = sample(1:20, 20, replace = T),
y3 = sample(1:20, 20, replace = T),
y4 = sample(1:20, 20, replace = T))
p1 <- ggplot(df, aes(x = x, y = y1)) + geom_line() + ylim(0, 100)
p2 <- ggplot(df, aes(x = x, y = y2)) + geom_line() + ylim(0, 100)
p3 <- ggplot(df, aes(x = x, y = y3)) + geom_line() + ylim(0, 100)
p4 <- ggplot(df, aes(x = x, y = y4)) + geom_line() + ylim(0, 100)
pp <- grid.arrange(p1, p2, p3, p4, ncol = 2)
对于每个情节,我想将地图添加为插图
inset_map <- ggdraw() + draw_plot(pp, 0, 0, 1, 1) + draw_plot(p.shp, 0.5, 0.52, 0.5, 0.4)
如何将地图分别显示为每个图中的插图?
解决方案
inset_map
在将结果传递给之前,您可以应用与生成单个 相同的代码逻辑grid.arrange()
:
plot.list <- list(p1, p2, p3, p4)
plot.list %>%
# add inset map to each plot in the list
lapply(function(p) ggdraw() +
draw_plot(p, 0, 0, 1, 1) +
draw_plot(p.shp, 0.5, 0.52, 0.5, 0.4)) %>%
# convert each plot in the list to grob
lapply(ggplotGrob) %>%
# arrange in grid, as before
grid.arrange(grobs = ., ncol = 2)
推荐阅读
- machine-learning - 如果重量不断增加,如何调试。Pytorch 程序
- javascript - 我无法在反应组件中正确访问 redux 存储
- php - 尝试使用 PHP Laravel 获取非对象的属性“标题”
- reactjs - 在 React 的数据库中显示存储为路径字符串的图像
- python - 如何访问 Github Actions Azure 函数部署的详细输出?
- sql - 在雪花中使用 if 条件
- azure-data-factory - Azure 数据工厂:数据集动态数据库表名称未在数据整理流中解析
- html - 如何在单击链接时获取相应的模态来自使用 ng bootstrap 角度 8 的循环
- tsql - 如何在 SQL Server 2014 中设置标识缓存
- android - Kotlin 与 JavaFXPorts 的兼容性