0

Here is shown how to label histogram bars with data values or percents using labels = TRUE. Is it also possible to rotate those labels? My goal is to rotate them to 90 degrees because now the labels over bars overrides each other and it is unreadable.

PS: please note that my goal is not to rotate y-axis labels as it is shown e.g. here

Community
  • 1
  • 1
Wakan Tanka
  • 7,542
  • 16
  • 69
  • 122
  • 1
    @jeremycg this is not a duplicate of mentioned question. This question ask how to rotate labels for each bar. Linked question asks how to rotate y-axis labels. – Wakan Tanka Nov 21 '15 at 23:11
  • My guess is that you'll need to plot the text labels yourself (using `text(..., srt=90)`). It may help to know that `hist(...)` provides output that tells you the `mids` for each bar. – r2evans Nov 21 '15 at 23:14

1 Answers1

3

Using mtcars, here's one brute-force solution (though it isn't very brutish):

h <- hist(mtcars$mpg)
maxh <- max(h$counts)
strh <- strheight('W')
strw <- strwidth(max(h$counts))
hist(mtcars$mpg, ylim=c(0, maxh + strh + strw))
text(h$mids, strh + h$counts, labels=h$counts, adj=c(0, 0.5), srt=90)

The srt=90 is the key here, rotating 90 degrees counter-clockwise (anti-clockwise?).

maxh, strh, and strw are used (1) to determine how much to extend the y-axis so that the text is not clipped to the visible figure, and (2) to provide a small pad between the bar and the start of the rotated text. (The first reason could be mitigated by xpd=TRUE instead, but it might impinge on the main title, and will be a factor if you set the top margin to 0.)

enter image description here

Note: if using density instead of frequency, you should use h$density instead of h$counts.

Edit: changed adj, I always forget the x/y axes on it stay relative to the text regardless of rotation.

Edit #2: changing the first call to hist so the string height/width are calculate-able. Unfortunately, plotting twice is required in order to know the actual height/width.

r2evans
  • 141,215
  • 6
  • 77
  • 149
  • Thank you for your answer, but when I run your code I get: `> strh <- strheight('W') Error in strheight("W") : plot.new has not been called yet` – Wakan Tanka Nov 22 '15 at 00:31
  • Note that if you are confident enough about the size of the labels, you can forego the first call to `hist` and use another mechanism. This double-plot is to get relatively accurate measures of string sizes on the plot window. – r2evans Nov 22 '15 at 00:42