首页 文章

ggplot:为连续x的每个组排列多个y变量的箱线图

提问于
浏览
14

我想为连续x变量的组创建多个变量的箱线图 . 对于每组x,箱形图应该彼此相邻排列 .

数据如下所示:

require (ggplot2)
require (plyr)
library(reshape2)

set.seed(1234)
x   <- rnorm(100)
y.1 <- rnorm(100)
y.2 <- rnorm(100)
y.3 <- rnorm(100)
y.4 <- rnorm(100)

df <- as.data.frame(cbind(x,y.1,y.2,y.3,y.4))

然后我融化了

dfmelt <- melt(df, measure.vars=2:5)

这个解决方案中显示的facet_wrap(Multiple plots by factor in ggplot (facets))给出了单个图中的每个变量,但是我希望每个变量的箱图在一个图中为x的每个bin都相邻 .

ggplot(dfmelt, aes(value, x, group = round_any(x, 0.5), fill=variable))+
geom_boxplot() + 
geom_jitter() + 
facet_wrap(~variable)

fig1

这显示了y变量彼此相邻但不是bin x .

ggplot(dfmelt) +
geom_boxplot(aes(x=x,y=value,fill=variable))+
facet_grid(~variable)

fig2

现在我想为x的每个bin生成这样的图 .

什么必须改变或添加?

1 回答

  • 29

    不完全确定你在寻找什么 . 这很接近吗?

    enter image description here

    library(ggplot2)
    library(plyr)
    ggplot(dfmelt, aes(x=factor(round_any(x,0.5)), y=value,fill=variable))+
      geom_boxplot()+
      facet_grid(.~variable)+
      labs(x="X (binned)")+
      theme(axis.text.x=element_text(angle=-90, vjust=0.4,hjust=1))
    

    EDIT (对OP评论的回应)

    你可以通过取出 facet_grid(...) 来调用每个箱子中的Y彼此相邻,但我不推荐它 .

    ggplot(dfmelt, aes(x=factor(round_any(x,0.5)), y=value, fill=variable))+
      geom_boxplot()+
      labs(x="X (binned)")+
      theme(axis.text.x=element_text(angle=-90, vjust=0.4,hjust=1))
    

    如果你必须这样做,使用方面仍然更清晰:

    dfmelt$bin <- factor(round_any(dfmelt$x,0.5))
    ggplot(dfmelt, aes(x=bin, y=value, fill=variable))+
      geom_boxplot()+
      facet_grid(.~bin, scales="free")+
      labs(x="X (binned)")+
      theme(axis.text.x=element_blank())
    

    请注意, bin 列添加到 dfmelt . 这是因为在 facet_grid(...) 公式中使用 factor(round_any(x,0.5)) 不起作用 .

相关问题