如何在ggplot2中显式指定分组以实现position_dodge偏移
问题:如何在ggplot2中指定偏移的分组变量?
需求
我想要生成的图表效果是:按gender分组对数据点和线条进行横向偏移,同性别下的不同subject线条保持对齐,不会额外偏移。
现有问题:position_dodge行为不符合预期
当使用position_dodge()时,线条层不仅会按gender偏移,还会按subject分组偏移,导致同性别下的线条分散开:
library(ggplot2) dat <- structure(list(subject = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 12L, 12L, 12L, 12L, 13L, 13L, 13L, 13L, 14L, 14L, 14L, 14L, 15L, 15L, 15L, 15L), levels = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27"), class = "factor"), gender = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), levels = c("F", "M"), class = "factor"), age = c(8, 10, 12, 14, 8, 10, 12, 14, 8, 10, 12, 14, 8, 10, 12, 14, 8, 10, 12, 14, 8, 10, 12, 14, 8, 10, 12, 14, 8, 10, 12, 14), y = c(21, 20, 21.5, 23, 21, 21.5, 24, 25.5, 20.5, 24, 24.5, 26, 23.5, 24.5, 25, 26.5, 26, 25, 29, 31, 21.5, 22.5, 23, 26.5, 23, 22.5, 24, 27.5, 25.5, 27.5, 26.5, 27)), row.names = c(NA, -32L), class = "data.frame") ggplot(dat, aes(x = age, y = y, color = gender)) + geom_point(position = position_dodge(width = 0.6)) + geom_line(aes(group = subject), position = position_dodge(width = 0.6))
临时解决方案:position_nudge,但扩展性差
用position_nudge可以实现需求,但当偏移因子有多个水平时,需要手动设置每个水平的偏移量,操作繁琐:
ggplot(dat, aes(x = age, y = y, color = gender)) + geom_point(position = position_nudge(x = ifelse(dat$gender == "M", 0.1, -0.1), y = 0)) + geom_line(aes(group = subject), position = position_nudge(x = ifelse(dat$gender == "M", 0.1, -0.1), y = 0))
期望的解决方案
有没有办法可以显式指定用于偏移的分组变量?比如类似以下的语法:
ggplot(dat, aes(x = age, y = y, color = gender)) + geom_point(position = position_dodge(width = 0.6, group = gender)) + geom_line(aes(group = subject), position = position_dodge(width = 0.6, group = gender))
感谢帮助。
内容的提问来源于Stack Exchange,提问作者retodomax
相关产品推荐
相关产品推荐

