在 x 轴上的离散组之间添加刻度

Ven*_*nca 5 r ggplot2 ggpubr

我想将我的一个分组箱线图(如下)替换为前后类型,但保持分组。这个是使用ggboxplot()from 制作的ggpubr。我知道也有,ggpaired()但我无法像这样分组。

分组箱线图

由于这个问题,我能够创建像这样的分组前后图。我现在想将轴从 4 个标记更改为 2 个(只是“是”和“否”,因为“之前”和“之后”仍在图例中。 分组点图与它们之间的线

这是我的带有虚拟数据的代码:

library(tidyverse)

set.seed(123)
data.frame(ID = rep(LETTERS[1:10], 2),
           consent = rep(sample(c("Yes", "No"), 10, replace = T), 2),
           height = sample(rnorm(20, 170, sd = 10)),
           ind = rep(c("before", "after"), each = 2)
           ) %>%
  ggplot(aes(x = interaction(ind, consent), y = height, color = ind))+
  geom_point()+
  geom_line(aes(group = interaction(ID, consent)), color = "black")+
  scale_x_discrete("response")
Run Code Online (Sandbox Code Playgroud)

甚至可以减少轴上的类别数量吗?或者我可以使用ggpaired(),但不使用构面创建分组图吗?

PoG*_*bas 2

解决方案可以是创建虚拟数值变量(在之前和之后之间)并将其放在 x 轴上。然后你可以更改它的名称。

# Generate OP data
library(tidyverse)
set.seed(123)
df <- data.frame(ID = rep(LETTERS[1:10], 2),
           consent = rep(sample(c("Yes", "No"), 10, replace = T), 2),
           height = sample(rnorm(20, 170, sd = 10)),
           ind = rep(c("before", "after"), each = 2)
           )
df$name <- paste(df$consent, df$ind)

# Generate dummy numeric variable for `name` combinations 
foo <- data.frame(name = c("Yes before", "Yes", "Yes after", 
                           "No before", "No", "No after"),
                  X = 1:6)
#         name X
# 1 Yes before 1
# 2        Yes 2
# 3  Yes after 3
# 4  No before 4
# 5         No 5
# 6   No after 6
Run Code Online (Sandbox Code Playgroud)

现在我们只需要映射nameX并将其放在 x 轴上:

df <- merge(foo, df)
ggplot(df, aes(X, height))+
    geom_point(aes(color = ind)) +
    geom_line(aes(group = interaction(ID, consent))) +
    scale_x_continuous(breaks = c(2, 5), labels = foo$name[c(2, 5)])
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述