2
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, which I do via:

  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(d, col=c("lawngreen","firebrick","deepskyblue"),
          space=c(0,0,0.2,0), xaxt = "n", yaxt="n",ylim = c(0, 25))

  x_axis_range <- c(2,3)
  x_axis_labels <- c("2", "3")
  axis(1,at = x_axis_range, labels = x_axis_range)

  y_axis_range <- c(0,2,4,6,25) 
  y_axis_labels <- c("0","2","4","6","25") 
  axis(2,at = y_axis_range, labels = y_axis_labels, las=2)

and it produces: enter image description here

However, I want 2 and 3 to appear centered under each grouped bars. How can I do it?

1

1 Answers

2
votes

Change the code that produces the x-axis to

x_axis_range <- c(1, 3.2)
x_axis_labels <- c("2", "3")
axis(1,at = x_axis_range, labels = x_axis_labels)

enter image description here

The bars are created with a width of one. In addition, you require to be the space between the second and third bar to be 0.2. Thus, the left borders of the bars are placed at 0, 1, 2.2, 3.2. If you want the labels to be placed at the centre of each group, you need therefore to put them at 1 and 3.2, which is what above definition of x_axis_range does.

I still left the labels to be 2 and 3, but of course you can change them to whatever you want.