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()
}