如何拆分具有多个级别的变量的箱线图

How to Split the box plot of a variable with several levels

我如何修改此代码以使 space 在箱形图的第二和第三水平之间。我的意思是,我想将箱线图分成两部分,右侧是 a 和 b,左侧是 c。

   library(ggplot2)
df <- data.frame(group=sample(c("a","b","c"),100,replace=T),x=rnorm(100),y=rnorm(100)*rnorm(100))
xlabs <- paste(levels(df$group),"\n(N=",table(df$group),")",sep="")
ggplot(df,aes(x=group,y=x,color=group))+geom_boxplot()+scale_x_discrete(labels=xlabs)

尝试在 ggplot.

中添加新的分面变量
df$facets <- ifelse(df$group == "a" | df$group == "b", "ab", "c")

现在用 facet_grid 绘制并修改 scale_x_dsicrete

ggplot(df,aes(x=group,y=x,color=group)) +
  geom_boxplot()+
  facet_grid(~ facets, scales = "free_x", space = "free_x") +
  scale_x_discrete(breaks = levels(df$group), labels = xlabs)

如果您的问题已得到解答,请确保接受答案以供进一步参考。