R:将 map 绘制为条形图中的插图

标签 r ggplot2 raster shapefile gridextra

示例数据:

dat1 <- data.frame(month = 1:12, rain = sample(100:200,12, replace = T), temp = sample(20:30, 12,, replace = T))


par(mfrow=c(1,2))

with(dat1, barplot(rain), ylim = c(0,500))
par(new = TRUE)
with(dat1, plot(temp, type = "b", lwd = 2, col = "red",axes = F, bty = "n", xlab = "", ylab = "", ylim = c(12,30)))
axis(side = 4, las = 2)

该地 block 属于法国的一个地区,ID = 12

library(raster)
dat <- getData('GADM', country='FRA', level=1)
plot(dat, col = ifelse(dat$ID_1 == 12, "red","grey"))

enter image description here

有什么办法可以将这两个图形合二为一,这样就可以得到法国 map 了 作为插图?这与此处将条形图放入 map 内的问题相反 How to plot barchart onto ggplot2 map

我尝试过这个:

 dat1 <- data.frame(month = 1:12, rain = sample(100:200,12, replace = T), temp = sample(20:30, 12,, replace = T))

 layout(matrix(c(1,1,2,1), nrow = 2, ncol = 2, byrow = TRUE))
 with(dat1, barplot(rain), ylim = c(0,500))
 par(new = TRUE)
 with(dat1, plot(temp, type = "b", lwd = 2, col = "red",axes = F, bty = "n", xlab = "", ylab = "", ylim = c(12,30)))
      axis(side = 4, las = 2)

 library(raster)
 dat <- getData('GADM', country='FRA', level=1)
 plot(dat, col = ifelse(dat$ID_1 == 12, "red","grey"))

enter image description here

但这与我的条形图重叠。我怎样才能将它显示为右上角或左上角的小插图。

最佳答案

我看到 2 个选项。

1/使用透明背景:

...
par(bg=NA)
plot(dat, col = ifelse(dat$ID_1 == 12, "red","grey"))

enter image description here

2/增加布局矩阵:

dat1 <- data.frame(month = 1:12, rain = sample(100:200,12, replace = T), temp = sample(20:30, 12,, replace = T))
layout(matrix(c(2,1,1,1,1,1,1,1,1), nrow = 3, ncol = 3, byrow = TRUE))

with(dat1, barplot(rain), ylim = c(0,500))
par(new = TRUE)
with(dat1, plot(temp, type = "b", lwd = 2, col = "red",axes = F, bty = "n", xlab = "", ylab = "", ylim = c(12,30)))
  axis(side = 4, las = 2)

dat <- getData('GADM', country='FRA', level=1)
par(bg=NA)
plot(dat, col = ifelse(dat$ID_1 == 12, "red","grey"))

enter image description here

关于R:将 map 绘制为条形图中的插图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49068557/

相关文章:

regex - 使用带有字边界的 mgsub 函数作为替换值

r - 如何将 xtabs() 的结果转换为 R 中的数据框?

r - 对数据框的每一组进行线性拟合,检查异方差性

r - ggplot2 中的 geom_map 边框

r - 为什么当我将栅格 map 投影到新的 CRS(R 中的 projectRaster 函数)时,栅格 map 的值会发生变化?

r - 如何在栅格处理中保留栅格数据类型?

r - 在R中创建空的csv文件

r - 使用 dplyr 的 do 来执行引导复制

r - 在 ggplot 中指定 grid.layout 以在 2x2 图中粘贴 4 个图

python - 光栅到 ASCII - 在 Python 中添加处理多个文件的代码片段