如何将geom_hex生成的六边形映射回原始数据点?
如何将geom_hex生成的六边形映射回原始数据点
ggplot_build返回的六边形数据仅包含分箱计数和坐标范围,没有直接关联原始数据的字段。要找到对应的数据点,需通过六边形的x/y区间手动匹配原始数据,步骤如下:
1. 提取六边形的区间信息
先获取ggplot构建后的六边形元数据,其中包含每个六边形的xmin/xmax(x轴范围)和ymin/ymax(y轴范围):
data("iris") rownames(iris) <- paste0("R", 1:nrow(iris)) plt <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_hex(bins=20, color = "white") # 获取六边形数据 g <- ggplot_build(plt) hex_data <- g$data[[1]]
2. 匹配目标六边形的原始数据点
假设你要找的是高亮红圈标记的六边形(示例中用count最大的六边形模拟),筛选原始数据中坐标落在该六边形区间内的点:
# 定位目标六边形(替换成你实际需要的,比如通过x/y坐标筛选) target_hex <- hex_data[which.max(hex_data$count), ] # 匹配原始数据 matched_points <- iris[ iris$Sepal.Length >= target_hex$xmin & iris$Sepal.Length <= target_hex$xmax & iris$Sepal.Width >= target_hex$ymin & iris$Sepal.Width <= target_hex$ymax, ] # 查看结果 print(matched_points)
3. 批量关联所有六边形与原始数据
如果需要给每个六边形都匹配对应的原始数据行,可以用dplyr批量处理:
library(dplyr) hex_data_with_matches <- hex_data %>% rowwise() %>% mutate( # 存储每个六边形匹配的原始数据行名 matched_rows = list( rownames(iris)[ iris$Sepal.Length >= xmin & iris$Sepal.Length <= xmax & iris$Sepal.Width >= ymin & iris$Sepal.Width <= ymax ] ) ) %>% ungroup() # 查看任意六边形的匹配行名 hex_data_with_matches$matched_rows[1]
原理说明
geom_hex基于指定的bins参数对x/y轴进行分箱,每个六边形对应唯一的x/y区间。只要原始数据点的坐标落在该区间内,就属于这个六边形。由于ggplot_build仅保留分箱后的统计结果,因此需要通过区间匹配重建关联。
内容的提问来源于stack exchange,提问作者Anna
相关产品推荐
相关产品推荐

