-1

To draw X-axis labels for barplots in R, I use text() like this:

text(mean(bp), par("usr")[3] - 0.05*yDiff, xpd=NA, labels=journey, cex=0.9, font=2)

To draw a legend, I use something like this:

legend("bottom", legend=abbrevLabels, fill=c(colors), xpd=NA, horiz=TRUE, bty="n", 
   cex=1.0, inset=c(0, -0.3), xjust=0, adj=0.035, 
   text.width=rep(meanLabelLen/7.5, length(legendLabels)))

Both vertical offsets here -- the 0.05*yDiff and the insert offset of -0.3 for the legend -- are in Y-axis space. For various reasons, that's a problem for me. Instead, I prefer offsets in units of pixels. That is, what I really want to say is: "render labels 10 pixels below the bottom of the graph".

How can this be done?

jay.sf
  • 60,139
  • 8
  • 53
  • 110
Kode Charlie
  • 1,297
  • 16
  • 32
  • You should really make this [reproducible](https://stackoverflow.com/help/mcve) so we understand what you want. – jay.sf Mar 24 '19 at 06:01
  • Unfortunately I can't. Graph contents are proprietary. – Kode Charlie Mar 24 '19 at 22:58
  • Sure you can, in that case please consider [**How to make a great reproducible example**](https://stackoverflow.com/a/5963610/6574038). Show some effort! :) – jay.sf Mar 25 '19 at 05:58

1 Answers1

0

For constant vertical offset of horizontal, X-axis labels situated underneath bar plots (at the bottom of a larger grid of such plots), it turns out that using title with the line attribute has consistent behavior / placement independent of device size. Here is what I now do:

title(xlab=journey, line=0, cex=0.8, font.lab=2, xpd=NA)

where line is integral and 0 is nearest the plot, and a higher integer is further away (in the negative Y direction).

For the legend, I could not come up with a constant vertical offset that behaved independently of either grid dimensions or device size. Several points here:

  • yjust parameter to legend did not work at all. I looked online for examples, but no matter what value I used, yjust was a no-go.
  • y parameter does work, but regrettably, not in conjunction with a descriptive attribute for x; that is, if x is set to bottom, you cannot concurrently set y. I found this behavior disconcerting, as I would generally expect these coordinates to be independent of each other.

To work around these limitations, here is what I did:

yInset <- 0.4 * (1.075 - par("fin")[2] / dev.size("in")[2])
legend(x='bottom', yjust=-0.75, inset=c(0, -yInset), legend=abbrevLabels, fill=c(colors), xpd=NA, horiz=TRUE, bty="n", cex=1.0, adj=0.035, text.width=rep(meanLabelLen/7.5, length(legendLabels)))

This logic effectively sets up a sliding Y-offset in proportion to grid dimensions and device size. The empirically determined scaling / offset factors of 1.075 and 0.4 are truly gross, but for now suffice.

It would help in the future if some of the limitations for legend cited above are resolved (or possibly better explained in the case that I misunderstood the docs).

Kode Charlie
  • 1,297
  • 16
  • 32