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

ggplot绘制经纬度年度分布图时多类警告问题求助

按年份划分的经纬度分布图复刻问题

复刻按年份划分的经纬度分布图时,运行ggplot代码后出现多类警告:

  • stat_contour(): Zero contours were generated
  • In min(x) : no non-missing arguments to min; returning Inf
  • In max(x) : no non-missing arguments to max; returning -Inf
  • ...
  • Raster pixels are placed at uneven horizontal intervals and will be shifted
    ℹ Consider using geom_tile() instead.

试过替换geom_raster为geom_tile的方案,但警告仍未消除。

数据示例

> dput(sms2[1:5,])
structure(list(smooth = c("ti(CYR,Longitude,Latitude)","ti(CYR,Longitude,Latitude)", 
"ti(CYR,Longitude,Latitude)","ti(CYR,Longitude,Latitude)","ti(CYR,Longitude,Latitude)"
), type = c("Tensor product int.","Tensor product int.","Tensor product int.", 
"Tensor product int.","Tensor product int."), by = c(NA_character_, 
NA_character_, NA_character_, NA_character_, NA_character_), 
    est = c(0.117025782747128, 0.113479508095921, 0.0933787695695134, 
    0.0895995641580288, 0.0755531029189105), se = c(0.185913143579915, 
    0.181005541009251, 0.152005779645215, 0.142402142342131, 
    0.119622723237741), CYR = c(2008L, 2008L, 2008L, 2008L, 2008L
    ), Longitude = c(-80.3026, -80.3034, -80.3075, -80.3076, 
    -80.31), Latitude = c(25.5694, 25.5684, 25.5618, 25.558, 
    25.5519)), row.names = c(NA, -5L), class = c("smooth_estimates", 
"tbl_df", "tbl", "data.frame"), tensor_term_order = list(`ti(CYR,Longitude,Latitude)` = c("Longitude", 
"Latitude", "CYR")))

运行代码

iest_lim <- c(-1, 1) * max(abs(sms2[["est"]]), na.rm = TRUE)

sms2 |> 
  mutate(fCYR = factor(CYR)) |> 
  ggplot(aes(x = Longitude, y = Latitude, fill = est, group = fCYR)) + 
  geom_raster(aes(x = Longitude, y = Latitude, fill = est, group = fCYR)) +
  geom_contour(aes(z = est, group = fCYR, fill = NULL), colour = "black") +
  facet_wrap(~ fCYR) +
  scale_fill_distiller(palette = "RdBu", type = "div") +
  expand_limits(fill = est_lim)

生成的图

按年份划分的经纬度分布图


问题解决办法

  1. 等高线生成失败警告
    这是因为est值波动太小或数据点稀疏,geom_contour找不到合适的等高线阈值。可以手动指定断点:

    geom_contour(aes(z = est, group = fCYR, fill = NULL), colour = "black", breaks = seq(-0.5, 0.5, 0.1))
    

    若不需要等高线,直接删掉该图层即可。

  2. min/max返回Inf/-Inf警告
    检查是否有年份的子数据集为空,或经纬度存在缺失值:

    sms2 |> count(CYR)  # 查看各年份数据量
    sms2 |> filter(is.na(Longitude) | is.na(Latitude))  # 检查缺失值
    

    过滤空年份或补全缺失值后,警告会消失。

  3. Raster像素间隔不均警告
    geom_raster要求数据是规则网格,但你的经纬度是离散不规则点。换成geom_tile时需指定像素尺寸:

    geom_tile(aes(width = 0.001, height = 0.001))
    

    若数据是散点,用stat_summary_2d生成热力图更合适:

    ggplot(sms2, aes(x = Longitude, y = Latitude, z = est)) +
      stat_summary_2d(bins = 20) +
      facet_wrap(~factor(CYR))
    

内容的提问来源于stack exchange,提问作者Nate

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 20:47:50