R:有两组的条形图,其中一组堆叠 [英] R: bar plot with two groups, of which one is stacked
问题描述
在R中创建条形图时遇到一个小问题.有3个变量:
I've encountered a small problem when creating a bar plot in R. There are 3 variables:
a <- c(3,3,2,1,0)
b <- c(3,2,2,2,2)
c <- 0:4
条形图应按'a'和'c'分组,并且'b'应堆叠在'a'的顶部.单独进行分组和堆叠很简单:
The bar plot should be grouped by 'a' and 'c', and 'b' should be stacked on top of 'a'. Doing the grouping and stacking seperately is straightforward:
barplot(rbind(a,c), beside=TRUE)
barplot(rbind(a,b), beside=FALSE)
如何在一张图表中同时完成两项操作?
How can you do both at once in one graph?
推荐答案
执行此操作需要考虑barplot
如何绘制堆积的条形.基本上,您需要在适当的地方为它提供一些值为0的数据.使用您的数据:
Doing this requires thinking about how barplot
draws stacked bars. Basically, you need to feed it some data with 0 values in appropriate places. With your data:
mydat <- cbind(rbind(a,b,0),rbind(0,0,c))[,c(1,6,2,7,3,8,4,9,5,10)]
barplot(mydat,space=c(.75,.25))
要了解引擎盖下发生了什么,请查看mydat
:
To see what's going on under the hood, take a look at mydat
:
> mydat
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
a 3 0 3 0 2 0 1 0 0 0
b 3 0 2 0 2 0 2 0 2 0
0 0 0 1 0 2 0 3 0 4
在这里,您正在用三个值(a
的值,b
的值,c
的值)绘制每个条形图. mydat
矩阵的每一列都是一个条形图,对其进行了排序,以使ab条形图适当地散布在c条形图上.您可能想要在间距和颜色上玩转.
Here, you're plotting each bar with three values (the value of a
, the value of b
, the value of c
). Each column of the mydat
matrix is a bar, sorted so that the ab bars are appropriately interspersed with the c bars. You may want to play around with spacing and color.
在R-help 时间 没有 解决方案,因此希望对您有所帮助.
Apparently versions of this have been discussed on R-help various times without great solutions, so hopefully this is helpful.
这篇关于R:有两组的条形图,其中一组堆叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!