0
votes

I have two 3x2 Matrices A, and B :

A:

          n2  n3
Part1     1   5
Part2     2   6
Part3     3   7

B:

          n2  n3   
Part1     5   1 
Part2     6   2   
Part3     7   3  

and I want to create stacked bar based on the columns n2, n3 for A, and B and then group the stacked bar, such that n2 for A, and B are grouped together side-by-side and same for n3. This is what I have tried:

  d1 <- read.csv("A.csv", header=T, dec=".",sep = " ")
  d1 <- subset(d1, select = c(n2, n3))

  d2 <- read.csv("B.csv", header=T, dec=".",sep = " ")
  d2 <- subset(d2, select = c(n2, n3))

  d <- cbind(d1[,1],d2[,1],d1[,2],d2[,2])

  barplot(t(d), beside=T, ,col=c("lawngreen","firebrick","deepskyblue"),
          space=c(0,0,0.2,0))

and it produces: enter image description here

Which bars are grouped, but there is no stacking, and colors are mis-used as well. And when I change the barplot to the following, it produces the below plot:

   barplot(t(d), col=c("lawngreen","firebrick","deepskyblue"), 
           space=c(0,0,0.2,0))

enter image description here

In which bars are wrongly stacked, and wrongly grouped. I appreciate it if you help me to resolve this as I am new to R :/

1

1 Answers

1
votes

barplot() groups the bars using the columns of your input matrix. Using this as the data:

> (d <- matrix((1:7)[-4],ncol=2)[,c(1,2,2,1)])
     [,1] [,2] [,3] [,4]
[1,]    1    5    5    1
[2,]    2    6    6    2
[3,]    3    7    7    3

You can just take off the transpose from your previous code:

barplot(d, col=c("lawngreen","firebrick","deepskyblue"), space=c(0,0,0.2,0))

stacked bar plot