2016-03-19 33 views
0

我试图有条件地对箱子颜色代码进行颜色编码,但它不一致。我希望有人能够确定问题所在。我希望不能使用ggplot,因为我对R很新,并且想坚持我所知道的(现在)。R - 箱子情节有条件的颜色不工作

本质上,我制作了一系列箱形图,其中9个箱子中的2个需要不同的颜色。我无法指定颜色模式,因为两个框的位置在每个图形的x轴上都会发生变化。我有一个标有“Control”的列,其值为0,2或4.我希望所有值为Control = 0的都是gray80,Control = 4是gray40,Control = 2是白色的。我试图通过两种方式来实现:

#BoxPlot with Conditional Coloring, ifelse statement 
boxplot(Y~X, ylab="y", 
xlab="x", 
col=ifelse(Control>=3, "gray40", ifelse(Control<=1, "gray80","white"))) 

#Colors 
colors <- rep("white", length(Control)) 
colors[Control=4] <- "gray40" 
colors[Control=0] <- "gray80" 

#BoxPlot with Conditional Coloring, "Colors" 
boxplot(Y~X, ylab="y", 
xlab="x", 
col=colors) 

在箱线图连接,只有前两个箱子应该在有色谁能告诉我我在做什么错? 1

+0

如果有机会的话,你可能会掀起[重复的例子(http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-可再现-例子)?在那之前,你可以尝试'ifelse(Control == 0,“gray80”,ifelse(Control == 2,“white”,“gray40”))''。 –

回答

0

这里有两种方法可以解决这个问题。如果它不适合你,一个可重复的例子就是要走的路(参见你的原始问题下的评论)。

xy <- data.frame(setup = rep(c(0, 2, 4), 50), value = rnorm(150)) 

boxplot(value ~ setup, data = xy) 

boxplot(value ~ setup, data = xy, col = ifelse(xy$setup == 0, "gray80", ifelse(xy$setup == 2, "white", "gray40"))) 

library(ggplot2) 

xy$setup <- as.factor(xy$setup) 


ggplot(xy, aes(y = value, fill = setup, x = setup)) + 
    theme_bw() + 
    geom_boxplot() + 
    # order of colors is determined by the order of levels of xy$setup 
    scale_fill_manual(values = c("gray80", "white", "gray40")) 

enter image description here