12

I'm trying to add some text to the right hand side of a horizontal barplot at the same heights as each bar, however, both text() and axis() don't seem to plot this at the heights corresponding to each bar.

Here's a similar barplot

x <- runif(10, 0,1)
y <- matrix(c(x, 1-x), nrow=2, ncol=10, byrow=TRUE)
barplot(y, horiz=TRUE, beside=FALSE, names.arg=seq(1,10,1), las=1, xlim=c(0, 1.2))

Neither of these two options align properly, how does the scaling work here?

axis(4, at=seq(1,10,1), labels=seq(1,10,1))
text(1.1, seq(1,10,1), labels=seq(1, 10, 1))
CCID
  • 1,368
  • 5
  • 19
  • 35

1 Answers1

17

By chacking the documentation of barplot, you can see that it has an invisible return value: the midpoints of the bars. You can use those to add additional information to the plot.

x <- runif(10, 0,1) 
y <- matrix(c(x, 1-x), nrow=2, ncol=10, byrow=TRUE) 
bp <- barplot(y, horiz=TRUE, beside=FALSE, names.arg=seq(1,10,1), las=1, 
              xlim=c(0, 1.2)) 
text(x, bp, signif(x,2), pos=4)
bp
Aniko
  • 18,516
  • 4
  • 48
  • 45
  • THanks, that's great. Value A numeric vector (or matrix, when beside = TRUE), say mp, giving the coordinates of all the bar midpoints drawn, useful for adding to the graph. – CCID Nov 18 '10 at 17:07
  • I copied the text from the barplot help file – CCID Nov 18 '10 at 17:07
  • 1
    Why was my picture from yesterday removed? Useing a graphic would help to understand. – buhtz Aug 24 '16 at 07:00