Faceted Boxplot数据结构适配求助:实现预期分面箱线图效果
求助:ggplot2绘制分面箱线图数据匹配问题
预期展示效果
- tumor分面:
- Case 1,4(原group x):数值2.97、2.97
- Case 2,3(原group y):数值2.9、2.97
- Case 5(原group z):仅数值2.6(显示为一条线)
- adjacent lung分面:
- Case 1,4:数值1.5、2.25
- Case 2,3:数值2.97、2.5
- Case 5:仅数值2.37
- tissue far from tumor分面:
- Case 1,4:数值2.5、2.8
- Case 2,3:数值2.5、2.1
- Case 5:仅数值3
当前问题
绘制出的分面箱线图不符合预期,已添加抖动点查看数据分布,但仍未定位问题,不确定正确的数据结构应该如何构造。曾尝试加入数值10测试,仍未明确问题根源。
当前使用的R代码
x <- c(2.97, 2.97, 1.5, 2.25, 2.5, 2.8) y <- c(2.9, 2.97, 2.97, 2.5, 2.5, 2.1) z <- c(2.6, 2.97, 3) data <- data.frame( values = c(x, y, z), group = factor( c(rep("y", length(y)), rep("x", length(x)), rep("z", length(z))), levels = c("x", "y", "z") ), position = factor( rep(c("tumor", "adjacent lung", "tissue far from tumor"), length(x) + length(y) + length(z)), levels = c("tumor", "adjacent lung", "tissue far from tumor") ) ) library(ggplot2) ggplot(data, aes(x = group, y = values, fill = position)) + geom_boxplot() + geom_point(aes(fill=group), size=5, shape=21, colour="grey20", position=position_jitter(width=0.2, height=0.1)) + scale_x_discrete(labels = c("x" = "Case 1, 4", "y" = "Case 2, 3", "z" = "Case 5")) + labs(title = "IL-13 Receptor alpha 1 positivity scores", x = "Patient Cases", y = "Positivity scores") + theme(axis.text.x = element_text(face = "bold", color = "black", size = 12, angle = 45), axis.text.y = element_text(face = "bold", color = "black", size = 12, angle = 45)) + facet_wrap(~ position)
问题根源与修正方案
问题出在数据结构构造错误:原代码中position列是重复循环三个分面标签,导致每个数据点被错误分配到所有分面中,完全打乱了数据与分面的对应关系。
正确的做法是,要为每个分面下的每个group单独指定对应的数据,构造出每行数据都唯一对应position(分面)、group(病例组)和values(数值)的结构。
修正后的代码
library(ggplot2) # 按预期构造正确的数据框 data <- data.frame( position = rep(c("tumor", "adjacent lung", "tissue far from tumor"), each = 6), group = rep(c("x", "x", "y", "y", "z", "z"), 3), values = c(2.97, 2.97, 2.9, 2.97, 2.6, 2.6, # tumor分面数据 1.5, 2.25, 2.97, 2.5, 2.37, 2.37, # adjacent lung分面数据 2.5, 2.8, 2.5, 2.1, 3, 3) # tissue far from tumor分面数据 ) # 调整group的因子顺序和标签 data$group <- factor(data$group, levels = c("x", "y", "z")) ggplot(data, aes(x = group, y = values)) + geom_boxplot(fill = "#69b3a2") + geom_point(size=5, shape=21, colour="grey20", fill="white", position=position_jitter(width=0.2, height=0.1)) + scale_x_discrete(labels = c("x" = "Case 1, 4", "y" = "Case 2, 3", "z" = "Case 5")) + labs(title = "IL-13 Receptor alpha 1 positivity scores", x = "Patient Cases", y = "Positivity scores") + theme(axis.text.x = element_text(face = "bold", color = "black", size = 12, angle = 45), axis.text.y = element_text(face = "bold", color = "black", size = 12, angle = 45)) + facet_wrap(~ position)
说明
- 对于单个数值的组(比如tumor分面的z组),需要重复一次数值才能让箱线图正确显示为一条线(否则ggplot2会因数据点不足跳过该箱线)
- 修正后的数据框中,每个分面下的三个group都对应了正确的数值,保证分面和数据的对应关系准确
- 移除了不必要的
fill = position映射,因为分面已经区分了不同组织类型,箱线图可以统一填充色或按group设置填充色
内容的提问来源于stack exchange,提问作者kakashi1992
相关产品推荐
相关产品推荐

