(自用)R语言绘图小技巧,如何批量循环查看物种分布点是否在分布区内部并且导出图片

 library(sf)
  library(ggplot2)
  
  mypath0 <- "E:/SDM/IUCN_OCC"
  setwd(mypath0)
  
  # 读取物种列表
  sp.lst <- read.csv(file.path(mypath0, "niche_overlap_crab_v2.csv"))
  sp.lst$crab <- gsub(" ", "_", sp.lst$species)
  sp.lst$coral.accepted <- gsub(" ", "_", sp.lst$species)
  crab.names <- unique(sp.lst$crab)
  
  # 循环绘制图形
  for (m in 1:nrow(sp.lst)) {
    target.species <- sp.lst[m, "species"]
    
    # 读取多边形
    shp <- st_read(file.path(mypath0, "IUCN_polygon", paste0(target.species, ".shp")))
    
    # 读取点数据
    point <- read.csv(file.path(mypath0, "Point", paste0(target.species, ".csv")), header = TRUE, sep = ",")
    point <- st_as_sf(point, coords = c("lon", "lat"), crs = st_crs(shp))  # 转换为sf对象
    
    # 绘制图形
    gg <- ggplot() +
      geom_sf(data = shp, fill = "transparent", color = "blue") +
      geom_sf(data = point, color = "red", size = 2) +
      labs(title = target.species) +
      theme_minimal() +
      theme(panel.background = element_rect(fill = "white"))  # 设置背景色为白色
    
    # 保存图形为PNG文件
    ggsave(paste0(mypath0, "/Plots/", target.species, "_plot.png"), plot = gg, width = 6, height = 4, units = "in")
  }

这篇文章主要记载如何批量导出图片,另外这是被chatgtp优化版本,太牛啦

更新一个版本,如果你想让polygon和point在世界地图上显示,并且输出最终tif格式可以采用这个版本的代码

library(sf)
library(ggplot2)

mypath0 <- "E:/SDM/IUCN_OCC"
setwd(mypath0)

# 读取物种列表
sp.lst <- read.csv(file.path(mypath0, "species_list.csv"))
sp.lst$crab <- gsub(" ", "_", sp.lst$species)
sp.lst$coral.accepted <- gsub(" ", "_", sp.lst$species)
crab.names <- unique(sp.lst$crab)

# 循环绘制图形
for (m in 1:nrow(sp.lst)) {
  target.species <- sp.lst[m, "species"]
  
  # 读取多边形
  shp <- st_read(file.path(mypath0, "IUCN_polygon", paste0(target.species, ".shp")))
  shp <-shp$geometry
  # 读取点数据
  point <- read.csv(file.path(mypath0, "Point", paste0(target.species, ".csv")), header = TRUE, sep = ",")
  point <- st_as_sf(point, coords = c("lon", "lat"), crs = st_crs(shp))  # 转换为sf对象
  
  tiff(filename = paste0("E:/SDM/IUCN_OCC/check/",target.species,".tif"), res = 200, width = 3000, height = 1500, compression = "lzw")
  par(mar=c(0,0,0,0), mgp=c(3,1,0))
  maps::map('world', col = 'grey85', fill = T, border = 'grey85', ylim = c(-82, 90),xlim = c(-180, 180))
  axis(1); axis(2); box()
  plot(shp, add = T, col = "red", pch = 0, border = NA)
  plot(point, add = T, col = "black", pch = 19,lwd = 0.4)
  
  
  legend("topright", legend = c("Polygon", "Point"), col = c("red", "black"), pch = c(0, 19), lwd = 2)
  
  dev.off()
  
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值