【问题标题】:ggplot: arranging boxplots of multiple y-variables for each group of a continuous xggplot:为每组连续 x 排列多个 y 变量的箱线图
【发布时间】:2014-02-18 18:18:37
【问题描述】:

我想为连续 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)

这显示了彼此相邻的 y 变量,但不合并 x。

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

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

需要更改或添加什么?

【问题讨论】:

  • 请在代码中包含您正在使用的库。还有round_any 来自哪里?
  • @TylerRinker - 库是 ggplot2 和 plyr。

标签: r ggplot2 boxplot continuous r-factor


【解决方案1】:

不完全确定您在寻找什么。这么近了吗?

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

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

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

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

【讨论】:

  • 这看起来更好,但不是我想要的。对于 x 的每个 bin,我希望将相应的 y-boxplots 彼此相邻(y1 | y2| y3| y4 for x1 等等)。有什么想法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-07
相关资源
最近更新 更多