2016-08-30 66 views
-1

我打算用一个二元结果变量(0或1)绘制多个连续变量(大约20个变量)来绘制(箱线图)。Ggplot:将多个连续变量与一个二元变量进行比较

数据:

ID outcome var1 var2 var3 var4 var5 
1  0  62 2.01 13  1.94 8 
2  0  150 4.32 9   99 6 
3  0  18 1.86 0.6  99 22 
4  0  60 4.08 3  -99 6 
5  1  20 1.96 1   99 14 
6  1  100 1.64 19  -99 3 

我的代码:

tmp <- melt(data, id.vars=c("ID", "outcome")) 

p <- ggplot(data = tmp, aes(x=outcome, y= value)) + 
    geom_boxplot(aes(fill=Label)) 
p + facet_wrap(~ variable, scales="free") 

这个代码显示了以下错误:

Error in layout_base(data, vars, drop = drop) : At least one layer must contain all variables used for facetting

任何帮助将不胜感激。

+1

它将帮助,如果你在你的问题有你的数据集的一个例子。有关如何添加示例数据集的想法,请参见[此链接](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)。 – aosmith

回答

0

这里有几个问题。

1)您没有名为Label的变量。

2)outcome是一个连续变量。

删除Label,使outcome到的一个因素,代码工作

ggplot(data = tmp, aes(x=as.factor(outcome), y= value)) + 
    geom_boxplot() + 
    facet_wrap(~ variable, scales="free") 

数据:

tmp <- structure(list(ID = c(1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L, 4L, 
5L, 6L, 1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 
3L, 4L, 5L, 6L), outcome = c(0L, 0L, 0L, 0L, 1L, 1L, 0L, 0L, 
0L, 0L, 1L, 1L, 0L, 0L, 0L, 0L, 1L, 1L, 0L, 0L, 0L, 0L, 1L, 1L, 
0L, 0L, 0L, 0L, 1L, 1L), variable = structure(c(1L, 1L, 1L, 1L, 
1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 
4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L, 5L), .Label = c("var1", "var2", 
"var3", "var4", "var5"), class = "factor"), value = c(62, 150, 
18, 60, 20, 100, 2.01, 4.32, 1.86, 4.08, 1.96, 1.64, 13, 9, 0.6, 
3, 1, 19, 1.94, 99, 99, -99, 99, -99, 8, 6, 22, 6, 14, 3)), row.names = c(NA, 
-30L), .Names = c("ID", "outcome", "variable", "value"), class = "data.frame") 
相关问题