5

我想将我的一个分组箱线图(如下)替换为前后类型,但保持分组。这个是使用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")

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

4

2 回答 2

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

现在我们只需要映射nameXx 轴并将其放在 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)])

在此处输入图像描述

于 2018-04-21T08:54:53.860 回答
1

@camille 让我想到了有趣的解决方案。显然,不仅可以将构面标签放在图的底部,甚至可以放在轴下方。这解决了我的问题,而无需修改我的数据框:

library(ggpubr) #for theme_pubr and JCO palette

ggplot(df, aes(x = ind, y = height, group = ID))+
geom_point(aes(color = ind), size = 3)+
geom_line()+
labs(y = "Height")+
facet_wrap(~ consent, 
           strip.position = "bottom", ncol = 5)+   #put facet label to the bottom 
theme_pubr()+
color_palette("jco")+
theme(strip.placement = "outside",   #move the facet label under axis
      strip.text = element_text(size = 12),
      strip.background = element_blank(),
      axis.title.x = element_blank(),
      legend.position = "none")

来自问题的数据框的结果:

生成的图像

于 2018-04-24T08:15:57.080 回答