R中stars::st_contour()与graphics::contour()等高线输出差异排查
问题描述
我持有一个UD栅格对象,对比base绘图体系与ggplot2绘图体系的等高线绘制结果时,发现ggplot2的等高线输出存在异常:base绘图结果中底部区域存在的2个50% UD等高线圈,在ggplot2输出中完全缺失。
base绘图得到的区域总面积与move包getVolumeUD()函数计算的体积面积结果完全匹配,同时也与fishtrack3d包输出的体积面积、UD等高线结果一致,结果可信度更高。
base绘图方案
实现代码
library(magrittr) library(ggplot2) library(stars) library(move) test <- stars::read_stars(file.path("All_Rasters_Scaled_Weighted.asc")) %>% sf::st_set_crs(4326) test %<>% starsExtra::trim2() test <- as(test, "Raster") test <- new(".UD", test) is.na(test[[1]]) <- test[[1]] == 0 plot(test, xlab="location_long", ylab="location_lat", asp = 1) contour(test, levels=c(.5, .95), col=c(6,2), add=TRUE, lwd=2)
输出结果

尽管该图等高线与底图的纵横比存在差异、显示效果不佳,但核心特征清晰,底部的2个50%等高线区域明确可见,该结果与fishtrack3d包的绘图输出一致,fishtrack3d包输出参考如下:
ggplot2绘图方案
实现代码
test <- stars::read_stars(file.path("All_Rasters_Scaled_Weighted.asc")) %>% sf::st_set_crs(4326) contour1colour = "red" # 95% UD等高线对应颜色 contour2colour = "orange" # 50% UD等高线对应颜色 legendtitle = "Percent UD Contours" ggplot() + geom_stars(data = test) + ggplot2::geom_sf( data = stars::st_contour(x = test, contour_lines = TRUE, breaks = max(test[[1]], na.rm = TRUE) * 0.05), fill = NA, inherit.aes = FALSE, ggplot2::aes(colour = "95% UD") ) + ggplot2::geom_sf( data = stars::st_contour(x = test, contour_lines = TRUE, breaks = max(test[[1]], na.rm = TRUE) * 0.5), fill = NA, inherit.aes = FALSE, ggplot2::aes(colour = "50% UD") ) + ggplot2::scale_colour_manual(name = legendtitle, values = c("50% UD" = contour2colour, "95% UD" = contour1colour))
输出结果

从输出结果可以明显看到,底部的等高线完全缺失。两种绘图方式使用的输入对象完全一致,需要定位二者等高线输出存在差异的具体原因。
已排查的相关线索
- ggplot2实现方案中,取栅格对象最大值的0.05、0.5比例作为
st_contour()的breaks参数值 - base R实现方案中,设置
contour()的levels参数为0.5、0.95 - 该栅格对象的原始最大值仅为0.008,按照
graphics::contour()的官方文档说明,levels参数应为栅格值的绝对数值而非相对比例,但实际运行时该参数却表现出相对值的特性,绘图结果与预期基本一致。
内容的提问来源于stack exchange,提问作者FlyingDutch
相关产品推荐
相关产品推荐

