R - boxplot颜色根据因素

时间:2012-04-18 22:57:23

标签: r lattice

我有一个与此类似的数据,然后使用晶格生成一个箱线图:

mydata <- data.frame(Y = rnorm(3*1000),
                  INDFACT =rep(c("A", "B", "C"), each=1000),
                  CLUSFACT=factor(rep(c("M","F"), 1500)))
library(lattice)
bwplot(Y ~ INDFACT | CLUSFACT, data=mydata, layout=c(2,1))

我的问题是我希望每个因素A,B和C都有不同的颜色。我试过这个:

bwplot(Y ~ INDFACT | CLUSFACT, data=mydata, layout=c(2,1), col=c("red","blue","green"))

但它只是改变了点的颜色。我想要的是改变整个颜色(点,盒子和伞)。

有办法吗?

3 个答案:

答案 0 :(得分:8)

names(trellis.par.get())
 [1] "grid.pars"         "fontsize"          "background"        "panel.background"  "clip"             
 [6] "add.line"          "add.text"          "plot.polygon"      "box.dot"           "box.rectangle"    
[11] "box.umbrella"      "dot.line"          "dot.symbol"        "plot.line"         "plot.symbol"      
[16] "reference.line"    "strip.background"  "strip.shingle"     "strip.border"      "superpose.line"   
[21] "superpose.symbol"  "superpose.polygon" "regions"           "shade.colors"      "axis.line"        
[26] "axis.text"         "axis.components"   "layout.heights"    "layout.widths"     "box.3d"           
[31] "par.xlab.text"     "par.ylab.text"     "par.zlab.text"     "par.main.text"     "par.sub.text"   

所以你想改变伞,点和盒子,但没有说是否是矩形的填充。我猜它是矩形线,因为填充和点都没有意义。

bwp <- bwplot(Y ~ INDFACT | CLUSFACT, data=mydata, layout=c(2,1), 
               par.settings = list( box.umbrella=list(col= c("red", "green", "blue")), 
                                    box.dot=list(col= c("red", "green", "blue")), 
                                    box.rectangle = list(col= c("red", "green", "blue")) 
              )                    )
bwp

enter image description here

答案 1 :(得分:3)

尝试设置box.rectangle参数:

bwplot(Y ~ INDFACT | CLUSFACT, data=mydata, layout=c(2,1),
        par.settings = list(box.rectangle = list(fill= rep(c('red','blue','green'),2)))

enter image description here

同样,我认为有box.dotbox.umbrella个参数可以做你期望的事情。

答案 2 :(得分:1)

只是因为它有趣,这样做ggplot2看起来像:

library(ggplot2)
ggplot(mydata, aes(x=INDFACT, y=Y, fill=INDFACT))+ 
  geom_boxplot()+
  facet_wrap(~CLUSFACT)