箱线图多个y含组怎么画_ggplot:为每个连续的x组排列多个y变量的箱形图

I would like to create boxplots of multiple variables for groups of a continuous x-variable. The boxplots should be arranged next to each other for each group of x.

The data looks like this:

require (ggplot2)

require (plyr)

library(reshape2)

set.seed(1234)

x

y.1

y.2

y.3

y.4

df

which I then melted

dfmelt

The facet_wrap as shown in this solution (

Multiple plots by factor in ggplot (facets))

gives me out each variable in an individual plot, but I would like to have the boxplots of each variable next to each other for each bin of x in one diagram.

ggplot(dfmelt, aes(value, x, group = round_any(x, 0.5), fill=variable))+

geom_boxplot() +

geom_jitter() +

facet_wrap(~variable)

This shows the y-variables next to each other but does not bin x.

ggplot(dfmelt) +

geom_boxplot(aes(x=x,y=value,fill=variable))+

facet_grid(~variable)

Now I would like to produce such a plot for each bin of x.

What has to be changed or added?

解决方案

Not exactly sure what you're looking for. Is this close?

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 (response to OP's comment)

You can put the Y's next to each other in each bin by just taking out the facet_grid(...) call, but I don't recommend it.

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

If you have to do it this way, it's still clearer using facets:

dfmelt$bin

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

Note the addition of a bin column to dfmelt. This is because using factor(round_any(x,0.5)) in the facet_grid(...) formula doesn't work.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值