R语言 箱线图和geom_path的单独位置

xytpbqjk  于 2023-04-09  发布在  其他
关注(0)|答案(1)|浏览(134)

对于该说明性数据:

set.seed(123)
df <- data.frame(
  ID = 1:50,
  Q = rnorm(50),
  A = rnorm(50,1)
)

我想连接ID上的成对点,这可以通过下面的答案Connect jittered points by group来实现:

pj <- position_jitter(seed = 1, width = .1, height = 0)

df %>%
  pivot_longer(-ID) %>%
  ggplot(aes(x = factor(name), y = value, fill = factor(name))) +

  # boxplot:
  geom_boxplot(
    width = 0.12,
    outlier.color = NA,
    alpha = 0.5
  ) +
  
  # data points:
  geom_point(
    alpha = 0.5, col = "blue",
    position = pj
  ) +
  
  # connecting lines:
  geom_path(aes(group = ID),
            alpha = 0.5,
            position = pj
  )

让我烦恼的是,这些点覆盖了箱线图。我希望它们与箱线图分开。具体来说,它们应该移动到箱线图之间的空间,就像下面的图:

如何才能做到这一点呢?在此提前表示感谢。

9lowa7mx

9lowa7mx1#

一个选项是移动或微移点和线的位置,这需要将name转换为数字并考虑箱形图和抖动宽度:

library(tidyr)
library(dplyr, warn = FALSE)
library(ggplot2)

box_width <- .12
jitter_width <- .1

pj <- position_jitter(seed = 1, width = jitter_width, height = 0)

df %>%
  pivot_longer(-ID) %>%
  mutate(
    name_num = as.numeric(factor(name)),
    name_num = name_num + (box_width + jitter_width / 2) * if_else(name == "A", 1, -1)
  ) |>
  ggplot(aes(x = factor(name), y = value, fill = factor(name))) +
  geom_boxplot(
    width = box_width,
    outlier.color = NA,
    alpha = 0.5
  ) +
  geom_point(
    aes(x = name_num),
    alpha = 0.5, col = "blue",
    position = pj
  ) +
  geom_path(aes(x = name_num, group = ID),
    alpha = 0.5,
    position = pj
  )

编辑要切换name类别的位置,请在转换为factor时以所需的顺序设置级别。当然,我们必须考虑到ifelse中的情况。

library(tidyr)
library(dplyr, warn = FALSE)
library(ggplot2)

box_width <- .12
jitter_width <- .1

pj <- position_jitter(seed = 1, width = jitter_width, height = 0)

df %>%
  pivot_longer(-ID) %>%
  mutate(
    name = factor(name, levels = c("Q", "A")),
    name_num = as.numeric(factor(name)),
    name_num = name_num + (box_width + jitter_width / 2) * if_else(name == "Q", 1, -1)
  ) |>
  ggplot(aes(x = name, y = value, fill = name)) +
  geom_boxplot(
    width = box_width,
    outlier.color = NA,
    alpha = 0.5
  ) +
  geom_point(
    aes(x = name_num),
    alpha = 0.5, col = "blue",
    position = pj
  ) +
  geom_path(aes(x = name_num, group = ID),
    alpha = 0.5,
    position = pj
  )

相关问题