1

I am plotting bar plots and box plots using boxplot and barplot in R, and space is tight. I every bar / box to be labelled visibly, but R automatically hides labels that it reckons will make the display too cramped.

axis() has the parameter gap.axis. Is there an equivalent for boxplot and barplot?

Plotting barplot(..., axes = FALSE); axis(1, gap.axis = 0) doesn't work because the position of the x axis doesn't correspond to the position of bars.

Reproducible example:

boxplot(matrix(1:100, 10, 10), cex.axis = 2)
barplot(setNames(1:10, 1:10), cex.names = 2)
Martin Smith
  • 3,687
  • 1
  • 24
  • 51
  • Do we want to show every x and y axis tick labels? in your example 1,2,3,..10? Maybe see this post https://stackoverflow.com/q/8688854/680068 – zx8754 May 18 '21 at 09:39
  • That's right. The example you linked is great for `plot()`, but doesn't help for `barplot()` or `boxplot()`. – Martin Smith May 18 '21 at 09:57
  • 1
    Another related post: https://stackoverflow.com/q/9981929/680068 – zx8754 May 18 '21 at 10:12

1 Answers1

0

In R 4.1.0, barplot() passes gap.axis is passed with the ... to axis(), producing the required effect. To suppress the warnings resulting from gap.axis also being passed to other plotting functions (reported as a bug), use:

suppressWarnings(barplot(setNames(1:10, 1:10),
                         cex.names = 2, gap.axis = -10))

[Edited:] As of R4.1.0-patched80484, gap.axis is natively supported by boxplot(), thanks to Martin Maechler.

As a workaround in older versions of R, use:

dat <- matrix(1:100, 10, 10)
boxplot(dat, axes = FALSE)
axis(1, seq_len(ncol(dat)), colnames(dat),
     cex.axis = 2, gap.axis = -10)
Martin Smith
  • 3,687
  • 1
  • 24
  • 51