Half color box in R
Is there anyway for the built-in R boxplot function to create boxes with different colors for the top and bottom boxes? Something like that:
Here is the function I came up with:
h.boxplot <- function(..., col.top='orange', col.bottom='yellow', col.scheme='none'){
cols = c(col.top, col.bottom)
if(col.scheme != 'none'){
cs = list(blue=c('#0071c1', '#3198ff'), green=c('#008001', '#99cc00'), yellow=c('#ffcc00', '#cc9900'))
stopifnot(col.scheme %in% names(cs))
cols = cs[[col.scheme]]
}
bx<-boxplot(..., col = "white", lty=1, boxlwd=0.00001)
n = length(bx$names)
rect(1:n-.4, bx$stats[2,], 1:n+.4, bx$stats[3,], col=cols[2], border=NA)
rect(1:n-.4, bx$stats[3,], 1:n+.4, bx$stats[4,], col=cols[1], border=NA)
return(bx)
}
# Examples
data = list(A=1:10, B=20:50)
h.boxplot(data, col.scheme='green', outline=F, frame=F)
h.boxplot(data, col.scheme='blue', outline=F, frame=F)
Should give something like:
+3
source to share
1 answer
This is not a parameter that you can set on the base boxplot
to get this behavior, but you can fake it by drawing rectangles over the graph with different colors. for example
bx<-boxplot(count ~ spray, data = InsectSprays, col = "lightgray")
rect(1:6-.4, bx$stats[2,], 1:6+.4, bx$stats[3,], col="orange")
rect(1:6-.4, bx$stats[3,], 1:6+.4, bx$stats[4,], col="yellow")
You can continue customization as you like.
+5
source to share