You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在R语言的世界地图指定位置添加子图?

在世界地图指定位置嵌入子图的实现方案

没问题!我来帮你实现在世界地图指定位置嵌入子图的需求,下面分别用Base R和ggplot2两种方案来完成,完全贴合你的代码逻辑:

Base R 实现方法

Base R中我们可以通过调整绘图参数par(fig),在已绘制的地图上精准叠加子图。核心是把地理经纬度转换成绘图区域的归一化坐标,确保子图能准确定位到目标点位。

library(rworldmap)

# 准备子图所需的散点数据
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(worldmap[which(worldmap$REGION != "Antarctica"), ])

# 定义要嵌入子图的经纬度点位
site_lon <- c(3, 80)
site_lat <- c(10, 40)

# 循环为每个点位添加子图
for(i in 1:length(site_lon)){
  # 将经纬度转换为绘图设备的归一化坐标(范围0-1)
  x_coord <- grconvertX(site_lon[i], from = "user", to = "ndc")
  y_coord <- grconvertY(site_lat[i], from = "user", to = "ndc")
  
  # 设置子图的位置与尺寸,可按需调整width/height数值
  sub_width <- 0.15
  sub_height <- 0.15
  par(fig = c(x_coord - sub_width/2, x_coord + sub_width/2,
              y_coord - sub_height/2, y_coord + sub_height/2),
      new = TRUE)
  
  # 绘制子图,隐藏轴标签和标题避免杂乱
  plot(x_list[[i]], y_list[[i]], pch = 16,
       axes = FALSE, xlab = "", ylab = "", main = "")
  # 给子图添加边框,增强辨识度
  box()
}

# 恢复默认绘图参数,避免影响后续绘图
par(fig = c(0, 1, 0, 1), new = FALSE)

ggplot2 实现方法

如果习惯用ggplot2,我们可以借助annotation_custom()函数,将子图转换为图形对象(grob)后,直接指定经纬度位置嵌入主地图。

library(rworldmap)
library(ggplot2)
library(grid)

# 准备子图所需的散点数据
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)

# 将rworldmap的空间对象转换为ggplot兼容的数据框
world_df <- fortify(worldmap[which(worldmap$REGION != "Antarctica"), ])

# 绘制主地图
main_map <- ggplot() +
  geom_polygon(data = world_df, aes(x = long, y = lat, group = group),
               fill = "lightgray", color = "white") +
  coord_fixed() + # 保持地图的正确比例
  theme_minimal() +
  theme(axis.text = element_blank(), axis.title = element_blank(),
        panel.grid = element_blank())

# 定义要嵌入子图的经纬度点位
site_lon <- c(3, 80)
site_lat <- c(10, 40)
# 子图的尺寸(基于经纬度单位,可按需调整)
sub_size <- 5

# 循环创建子图并添加到主地图
for(i in 1:length(site_lon)){
  # 创建子图,仅保留散点和边框
  sub_plot <- ggplot() +
    geom_point(aes(x = x_list[[i]], y = y_list[[i]]), pch = 16) +
    theme_void() +
    theme(panel.border = element_rect(color = "black", fill = NA))
  
  # 将子图转换为grob对象
  sub_grob <- ggplotGrob(sub_plot)
  
  # 将子图嵌入主地图的指定位置
  main_map <- main_map +
    annotation_custom(grob = sub_grob,
                      xmin = site_lon[i] - sub_size/2,
                      xmax = site_lon[i] + sub_size/2,
                      ymin = site_lat[i] - sub_size/2,
                      ymax = site_lat[i] + sub_size/2)
}

# 显示最终的地图与子图组合
print(main_map)

内容的提问来源于stack exchange,提问作者P. Denelle

火山引擎 最新活动