如何在R中创建样本量教学演示用的带填充点网格图?
这个需求完全可以在R中通过ggplot2包实现,无需借助其他工具。
实现思路为:先为每组testid+source的组合生成对应数量的网格点坐标,标记前p个点为填充状态,再通过分面绘图即可匹配你需要的效果。完整可运行代码如下:
# 加载依赖包 library(ggplot2) library(dplyr) library(tidyr) # 你的原始示例数据 testid <- c(1, 1, 2, 2, 3, 3) source <- rep(c("A", "B"), 3) n <- c(1, 1, 100, 100, 100, 100) p <- c(1, 0, 1, 2, 50, 51) df <- data.frame(testid, source, n, p) # 加工生成绘图用的网格点数据 plot_df <- df %>% rowwise() %>% mutate( point_id = list(1:n), # 标记前p个点为填充状态 filled = list(point_id <= p), # 计算网格坐标,支持n为完全平方数的场景,适配你给出的1、100的取值 side_len = sqrt(n), x = list(as.integer((point_id - 1) %% side_len) + 1), y = list(as.integer((point_id - 1) %/% side_len) + 1) ) %>% unnest(cols = c(point_id, filled, x, y)) %>% # 生成分面用的分组标签,和你预期的1A、1B等命名一致 mutate(group = paste0(testid, source)) # 绘图 ggplot(plot_df, aes(x = x, y = y)) + geom_point(aes(fill = filled), shape = 21, size = 5, color = "black") + # 按分组分面,3行2列排列6张子图 facet_wrap(~group, nrow = 3, ncol = 2, scales = "free") + # 自定义填充色:填充状态为黑色,空心为白色 scale_fill_manual(values = c("TRUE" = "black", "FALSE" = "white")) + # 隐藏多余坐标轴、背景,适配演示场景 theme_void() + theme( legend.position = "none", strip.text = element_text(size = 12, face = "bold") )
运行代码后输出的6张子图完全匹配你的预期:
- 1A:1个黑色填充圆点
- 1B:1个白色空心圆点
- 2A:10×10网格共100个圆点,1个填充
- 2B:10×10网格共100个圆点,2个填充
- 3A:10×10网格共100个圆点,50个填充
- 3B:10×10网格共100个圆点,51个填充
你可以根据需要调整geom_point的size参数修改圆点大小,修改facet_wrap的nrow/ncol参数调整子图排列方式,修改scale_fill_manual的色值自定义填充颜色。
内容的提问来源于stack exchange,提问作者markyoung
相关产品推荐
相关产品推荐

