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

时间:2017-07-22 06:50:40

标签: boxplot

如何修改此代码以在框图上创建第二和第三级之间的空间。我的意思是,我想将箱形图分为两个部分,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)

1 个答案:

答案 0 :(得分:0)

尝试在ggplot

中为facetting添加新变量
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)

如果您的问题已得到解答,请务必接受答复以供进一步参考。