如何自定义ggplot2中geom_tile图层符合阈值要求的轮廓线形状
问题原因
stat_contour 基于连续Z值插值生成等值线,你使用的是离散3×3网格数据,插值得到的Z=2等值线会穿过网格内部,无法匹配离散瓦片的外围边界。
解决方案
方案1:简易瓦片边框实现
如果可以接受每个符合条件的瓦片单独显示边框,直接新增筛选后的geom_tile图层即可:
library(ggplot2) X <- 1:3 Y <- seq(0,20,10) df <- expand.grid(X = X, Y = Y) df$Z <- c(5,4,9,2.1,1.5,1.2,6,7,1.9) ggplot(df, aes(X, Y)) + geom_tile(aes(fill = Z)) + scale_fill_distiller(palette = "RdYlGn") + # 仅为Z<=2的瓦片添加边框 geom_tile(data = ~ subset(.x, Z <= 2), fill = NA, color = "black", size = 2)
方案2:精准整体外围轮廓实现
如果需要所有Z<=2的瓦片合并为一个整体、仅绘制最外层轮廓,可以借助sf包处理多边形后再绘图:
library(ggplot2) library(sf) library(dplyr) X <- 1:3 Y <- seq(0,20,10) df <- expand.grid(X = X, Y = Y) df$Z <- c(5,4,9,2.1,1.5,1.2,6,7,1.9) # 将离散网格转为正方形多边形,筛选Z<=2的区域后合并 df_sf <- st_as_sf(df, coords = c("X", "Y")) %>% st_buffer(dist = 0.5, endCapStyle = "SQUARE") %>% filter(Z <= 2) %>% st_union() ggplot(df, aes(X, Y)) + geom_tile(aes(fill = Z)) + scale_fill_distiller(palette = "RdYlGn") + geom_sf(data = df_sf, fill = NA, color = "black", size = 2)
内容的提问来源于stack exchange,提问作者Daniel Valencia C.
相关产品推荐
相关产品推荐

