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

使用geom_raster绘制凸包遇slice(chull)空图问题求助

解决方案:保留凸包内的热力图栅格

问题根源

chull(X,Y)返回的是凸包顶点的行索引,直接用slice(chull(X,Y))只会保留凸包顶点对应的少数几个栅格,绝大多数栅格点被过滤,所以呈现空图。我们需要筛选的是所有落在凸包边界内的栅格点,而非仅顶点。


方法一:用sf包实现(推荐)

1. 生成凸包多边形

library(sf)
# 提取凸包顶点坐标
hull_vertices <- df[chull(df$X, df$Y), c("X", "Y")]
# 转换为sf多边形对象
hull_polygon <- st_polygon(list(as.matrix(hull_vertices)))

2. 筛选凸包内的栅格点

# 将原数据转为sf点对象
df_sf <- st_as_sf(df, coords = c("X", "Y"), crs = st_crs(hull_polygon))
# 判断每个点是否在凸包内
is_inside <- st_within(df_sf, st_sfc(hull_polygon), sparse = FALSE)[,1]
# 过滤得到凸包内的数据
df_filtered <- df[is_inside, ]

3. 绘制热力图

library(ggplot2)
ggplot(df_filtered) +
  geom_raster(aes(x = X, y = Y, fill = temp), show.legend = FALSE)

方法二:用sp包实现(无需sf依赖)

library(sp)
# 提取凸包顶点
hull_vertices <- df[chull(df$X, df$Y), c("X", "Y")]
# 判断点是否在凸包内(返回1表示在内部/边界)
is_inside <- point.in.polygon(df$X, df$Y, hull_vertices$X, hull_vertices$Y) == 1
# 过滤数据并绘图
df_filtered <- df[is_inside, ]

ggplot(df_filtered) +
  geom_raster(aes(x = X, y = Y, fill = temp), show.legend = FALSE)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 22:01:01