Skip to content
Prev 86917 / 398513 Next

rotated labels in barplot with beside=T and multiple groups

On Tue, 2006-02-21 at 14:07 +0100, Karin Lagesen wrote:
It appears to be a matrix, comprised of the results of using cut() along
with perhaps tapply() or similar on one or more continuous variables
using a grouping variable. See ?cut and ?tapply.
First, your code above has some errors.

The use of "col=colors[1:length(lsu[,1])]" does not work. It can either
be:

  col=colors()[1:length(lsu[,1])]

or easier to read:

  colors()[1:nrow(lsu)]


Second, the offset (-1.5) you have in the call to text():

  par("usr")[3] - 1.5

puts the text labels well below the bottom of the plot, which is why
they are not seen.  You need to change it to:

  par("usr")[3] - .05

or a similarly reduced offset figure.

Thus, you can now use:

  par(mar = c(6, 4, 4, 2) + 0.1)

  bplot <- barplot(lsu, beside = TRUE, 
                   col = colors()[1:nrow(lsu)], 
                   ylim = c(0, 1.0), xaxt = "n", xlab = "")

  axis(side = 1, at = bplot, labels = FALSE, tick = TRUE)

  nam <- rep("a", 10)

  text(bplot, par("usr")[3] - .05, srt = 45, adj = 1, 
       labels = nam, xpd = TRUE)


In order to get group labels for each of the three bars, you need to pay
attention to the "Value" section of ?barplot, which says:

     If 'beside' is true, use 'colMeans(mp)' for the midpoints of each
     _group_ of bars, see example.
  
Thus, if you want to place group labels on the plot use:

par(mar = c(6, 4, 4, 2) + 0.1)

bplot <- barplot(lsu, beside = TRUE, 
                 col = colors()[1:nrow(lsu)], 
                 ylim = c(0, 1.0), xaxt = "n", xlab = "")

nam <- rep("a", 10)

# Here is the change. Use colMeans(bplot)
text(colMeans(bplot), par("usr")[3] - .05, srt = 45, adj = 1, 
     labels = nam, xpd = TRUE)


Do not use the call to axis() if you don't want the tick marks, since
there is no other need for that function here.

If you do want to put tick marks at the midpoint of each group, you
could use:

  axis(1, at = colMeans(bplot), labels = FALSE)

HTH,

Marc Schwartz