R lattice bwplot: Fill boxplots with specific color depending on factor level -


i have dataframe example:

>mydata <- rbind(data.frame(col1 = rnorm(2*1000),col2 =rep(c("a", "c"), each=1000),col3=factor(rep(c("yy","nn"), 1000))),data.frame(col1 = rnorm(1000),col2 =rep(c("b")),col3=factor(rep(c("yy","yn"), 500)))) 

that looks like:

>head(mydata)         col1 col2 col3 1 -0.1213684      yy 2  0.1846364      nn 3  0.4028003      yy 4  1.4065677      nn 5 -0.8669333      yy 6  0.3295806      nn 

being col3 of factor type 3 levels: nn yy yn

i want make boxplot using lattice bwplot , assign each level specific color:

# nn: red=rgb(249/255, 21/255, 47/255) # yn: amber=rgb(255/255, 126/255, 0/255) # yy: green=rgb(39/255, 232/255, 51/255) 

using bwplot function:

pl<-bwplot(mydata$col1~mydata$col3 | mydata$col2,data=mydata, ylab=expression(italic(r)),panel=function(...) {panel.bwplot(...,groups=mydata$col3, fill=c(red,amber,green))}) 

that results in following figure: example

clearly colors not related levels in dataframe yy box not green. there way assign yy:green, nn:red , yn:amber?

here i'd do:

## create named vector of fill colors red   <- rgb(249/255, 21/255, 47/255) # nn: amber <- rgb(255/255, 126/255, 0/255) # yn: green <- rgb(39/255, 232/255, 51/255) # yy: fillcols <- c(nn=red, yn=amber, yy=green)  ## create panel function that, access subset of points plotted ## in current panel, picks out levels/colors needed mypanel.bwplot <- function(x=x, y=y, ...) {     fill <- fillcols[intersect(levels(x), unique(x))]      panel.bwplot(x=x, y=y, ..., groups=col3, fill=fill) }  ## plot away bwplot(col1 ~ col3 | col2, data = mydata, panel = mypanel.bwplot) 

enter image description here


Comments

Popular posts from this blog

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - UML - How would you draw a try catch in a sequence diagram? -

c++ - No viable overloaded operator for references a map -