2016-08-03 90 views
1

我想知道如何创建箱子内有两种不同颜色的箱形图。 例如我的变量d,我正在处理的是变量b和c的和。因此,在每个框中,颜色可以指示变量b和c创建d的比例。 我希望这是可以理解的。R由于变量(堆积箱图),箱子内的着色箱形图

这是我的例子:

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

你有什么想法如何做到这一点? 谢谢!

+0

是紫色和绿色之间的边界* *也正中的位置? – tluh

+0

在我的情况下,它不一定如此,所以我会有一条显示中位数的附加线 – KikiRiki

+1

这使得IMO没有意义。请阅读“boxplot”,并在该图中显示哪些数据。在你的例子'df'中,'A'的boxplot范围从7到10。 'b'和'c'的部分是什么? – Jimbou

回答

1

你可以试试:

# 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值取决于bc比例与d相比较。因此,您使用aggregateby来计算一个向量(此处为b)的比率,并在rect()内生成y值。最后,rgb()函数计算一个颜色,为透明度添加一个alpha参数。

enter image description here