在ggplot2中明确定义要躲避的组

问题描述 投票:0回答:1

我想要像下面这样的情节

但是,如果我尝试使用

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
来实现它,但是如果我的闪避系数超过两个级别,这就会变成大量的手工工作。

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))

感谢您的帮助。

r ggplot2
1个回答
2
投票

嗯,

group
aes 是决定位置如何躲避或堆叠或......的“因素”。但在某些情况下(主要与线路有关),TBMK 无法使用
group
aes 和
position
达到预期结果,即您想通过
gender
并在同一组中闪避(又称组)通过
subject
连接线路。

相反,我会通过适当设置线条的

x
位置来进行手动躲避(类似于您的
position_nudge
方法)。为此,我首先将
gender
转换为数字,然后使用
scales::rescale
重新缩放到
c(-.5, .5)
的范围,最后考虑闪避宽度。仍然有一些手动工作,但不需要以
gender
的类别为条件,原则上可以推广到更多因子级别:

library(ggplot2)
library(scales)

dwidth <- .6

ggplot(dat, aes(x = age, y = y, color = gender)) +
  geom_point(position = position_dodge(width = dwidth)) +
  geom_line(aes(
    x = age + dwidth / 2 * scales::rescale(
      as.numeric(gender),
      to = c(-.5, .5)
    ),
    group = subject
  ))

© www.soinside.com 2019 - 2024. All rights reserved.