简体   繁体   中英

R - boxplot color according to factor

I have a data similar to this and then produce a boxplot using 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))

My question is that I want to have a different color for each factor A, B and C. I have tried this:

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

But it just changes the color of the dots. What I want is to change the whole color (of the dot, the box and the umbrella).

Is there a way to do that?

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"   

So you wanted to change the umbrella and the dot and the box, but didn't say whether it was the fill of the rectangle. I'm going to guess it was the rectangle line, because doing both the fill and the dot wouldn't make sense.

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

在此输入图像描述

Try setting the box.rectangle parameter:

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

在此输入图像描述

Similarly, there are box.dot and box.umbrella parameters that I presume do what you'd expect.

Just cause its interesting, doing this is ggplot2 would look something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM