Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
528 views
in Technique[技术] by (71.8m points)

grouping - R: bar plot with two groups, of which one is stacked

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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))

barplot

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

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.

Apparently versions of this have been discussed on R-help various times without great solutions, so hopefully this is helpful.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...