由于变量(堆叠箱线图),箱内的 R 着色箱线图

R colouring boxplots within the box due to variables (stacked boxplot)

我想知道如何创建一个箱内有两种不同颜色的箱线图。 例如我正在绘制的变量 d 是变量 b 和 c 的总和。因此,在每个方框内,颜色可以表示变量 b 和 c 创建 d 的比例。 我希望这是可以理解的。

这是我的例子:

    a<-c("A","A","B","B","B","C","C","C","B","A")
    b<-c(1,2,3,4,3,4,5,6,3,4)
    c<-c(5,6,4,5,2,1,2,1,5,8)
    d<-c(6,8,7,9,5,5,7,7,8,12)
    df<-data.frame(a,b,c,d)

    boxplot(d~a)

现在我想根据变量b和c给每个方框上色,这样比例就显示出来了。

这是一张显示用 Excel 制作的情节的图片。 example http://www.real-statistics.com/wp-content/uploads/2012/11/box-plot-excel.png

你有什么想法可以实现吗? 谢谢!

你可以试试:

# First the boxplot
n <- boxplot(d ~ a)
# check the x values for the boxes, here it is for A 0.6 and 1.4
axis(1, seq(0, 5, 0.1))

# proportions for the b values depended on a

# the mean values calculated using another approach you mentioned in the comment
ratio <- aggregate(df[ , -1], list(df$a), mean)
# get the percentages
ratio <- ratio$b/ratio$d

# your approach:
ratio <- c(by(df, INDICES = df$a, FUN = function(x) mean(x$b/x$d)))
ratio    
A         B         C 
0.2500000 0.4620040 0.7904762

# caculate the y values for the rectangles, no matter which mean-calculation method you used
low <- diff(n$stats[c(2, 4), ])*ratio
high <- diff(n$stats[c(2, 4),])*(1-ratio)

# the final plot
n <- boxplot(d ~ a)
rect(xleft = c(0.6) + seq_along(n$n)-1, xright = 1.4 + seq_along(n$n)-1, ybottom = n$stats[2, ], ytop = n$stats[2, ]+low, col = rgb(1, 1,0 ,0.4))
rect(xleft = c(0.6) + seq_along(n$n)-1, xright = 1.4 + seq_along(n$n)-1, ybottom = n$stats[4, ], ytop = n$stats[4, ]-high, col = rgb(0, 1, 1, 0.4))

想法是使用 rect() 将矩形绘制到方框中。您必须分别为开始和结束提供 x 和 y 值。通过使用 axis 添加更多连续的 x 轴,您可以轻松地从箱线图中读取 x 值。 y 值取决于 bcd 相比的比例。因此,您使用 aggregateby 计算一个向量(此处 b)的比率,并在 rect() 内生成 y 值。最后,rgb() 函数计算颜色并添加透明度的 alpha 参数。

You can do a pie chart to show the share of vectors b and c in d (cf. image in link)

下面的代码展示了如何做到这一点:

c_share = sum(c)/sum(d)
b_share = sum(b)/sum(d)
mat = cbind(c_share, b_share)
pie(mat, labels=c("Share of C", "Share of B"))