You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ggplot中Shapefile与物种分布数据颜色映射异常求助

排查物种分布地图颜色映射异常的建议

问题背景:基于自定义Shapefile与物种分布数据交集处理后制作地图,地图可正常绘制但颜色映射不符合预期——数据表显示仅1个点位应为紫色,但实际渲染结果不符。当前使用的代码如下:

library(viridis) 
# Plot with labels
oslo_map <- ggplot() +
  geom_sf(data = shp2_oslo, color = "gray30", size = 0.2, fill = "lightblue1") +
  geom_sf(data = intersect3_oslo, aes(color = occurrences), size = 1.5, fill = NA) +
  scale_color_viridis(option = "plasma", begin = 0, end = 1, direction = -1) +  # Adding color scale for points
  ggtitle("Oslo") +
  theme_bw() +
  theme(axis.title.x = element_blank(),  # Remove x-axis title
        axis.title.y = element_blank(),  # Remove y-axis title
        plot.title.position = "panel",  # Position the title centered above the plot
        plot.title = element_text(hjust = 0.5)  # Center the title text
)

print(oslo_map)

以下是具体排查步骤:

  • 检查occurrences字段的属性与值分布

    • 运行summary(intersect3_oslo$occurrences)查看统计信息,确认是否存在超出预期的极值、重复值或缺失值
    • 用class(intersect3_oslo$occurrences)验证字段类型:如果是因子型而非数值型,会导致色阶映射逻辑错误,需转换为数值型(as.numeric(as.character(intersect3_oslo$occurrences)))
  • 验证交集后空间数据的完整性

    • 执行nrow(intersect3_oslo)确认点位数量与数据表一致,避免交集操作生成重复的几何对象
    • 用st_geometry_type(intersect3_oslo)检查几何类型,确保所有要素都是POINT,无MULTIPOINT等异常类型导致的渲染偏差
  • 调整颜色映射参数进行测试

    • 暂时移除direction = -1参数,默认方向的plasma色阶是否能匹配预期值(反转可能造成视觉判断混淆)
    • 添加limits参数强制限定色阶范围,例如已知最大值为X,设置scale_color_viridis(..., limits = c(min(intersect3_oslo$occurrences), X)),避免隐藏的极值拉伸色阶导致颜色偏差
  • 排查图层映射与渲染逻辑

    • 确认aes(color = occurrences)仅在目标geom_sf图层中设置,无全局映射干扰
    • 若occurrences为分类值,尝试改用离散色阶测试:scale_color_viridis(discrete = TRUE),观察是否能正确区分预期的紫色点位
  • 提取渲染数据定位异常

    • 运行ggplot_build(oslo_map)$data[[2]](第二个图层为点位图层),查看每个点位对应的colour值和occurrences数值,直接定位异常点位的来源

内容的提问来源于stack exchange,提问作者gn-gia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 23:32:20