在x轴

时间:2018-04-20 22:35:01

标签: r ggplot2 ggpubr

我想将我的一个分组箱图(下图)替换为之前的类型,但要将其保持分组。这是使用ggboxplot()中的ggpubr制作的。我知道还有ggpaired(),但我无法将其归类为此类。

grouped boxplot

感谢this question我能够像这样创建分组前后图。我现在想将轴从4个标记改为2个(只是“是”和“否”,因为“之前”和“之后”仍然在图例中。 grouped dotplots with lines between them

这是我的虚拟数据代码:

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()创建分组绘图,但不使用构面吗?

2 个答案:

答案 0 :(得分: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

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

enter image description here

答案 1 :(得分:1)

@cicille让我想到了狡猾的解决方案。显然,可以将小平面标签不仅放在图的底部,甚至放在轴下。这解决了我的问题,而无需修改我的数据帧:

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

结果来自问题的数据框:

Resulting image