R Boxplot:在中位数的上方和下方使用不同的颜色

时间:2016-08-30 13:48:51

标签: r

我试图在一个Boxplot中使用两种不同的颜色。我的目标是将中间部分的颜色涂成红色,中间部分的部分涂成绿色。 目前我正在转换数据并在一个图中组合两个箱图。我认为这不是一个优雅的解决方案。也许有人可以帮助我? 这是我的R代码:

x <- rnorm(100)
x_l <- x
x_l[x_l > median(x)] <- median(x)
boxplot(x_l, whiskcol = "darkgreen", staplecol = "darkgreen", 
        boxcol = "darkgreen", col = "darkgreen", ylim = c(-3, 3), 
        outcol="darkgreen", lwd = 2, medcol="black")
x_u <- x
x_u[x_l < median(x)] <- median(x)
boxplot(x_u, whiskcol = "red", staplecol = "red",  boxcol = "red", col = "red",
        ylim = c(-3, 3), outcol="red", lwd = 2, medcol="black", add = TRUE)

desired output image

感谢您的帮助, 亲切的问候,  cawi

1 个答案:

答案 0 :(得分:1)

正如您所发现的,您的方法会创建两个中位数,每半个数据一个。相反,计算一个箱线图,而不绘制它,然后在使用bxp()绘制之前修改对象的相应元素:

set.seed(0)
x <- rnorm(100)
top <- bottom <- boxplot(x,plot=FALSE)
top$stats[1:2] <- top$stats[3]
top$out <- top$out[top$out >= top$stats[3]]
bottom$stats[4:5] <- bottom$stats[3]
bottom$out <- bottom$out[bottom$out <= bottom$stats[3]]
bxp(top, whiskcol = "darkgreen", staplecol = "darkgreen", 
        boxcol = "darkgreen", col = "darkgreen", ylim = c(-3, 3), 
        outcol="darkgreen", lwd = 2, medcol="black")
bxp(bottom, whiskcol = "red", staplecol = "red",  boxcol = "red", col = "red",
        ylim = c(-3, 3), outcol="red", lwd = 2, medcol="black", add = TRUE)