1

I am trying to add additional x-axis labels to a ggplot2 plot with discrete axis labels. I have tried a few approaches (including some that use grid, i.e. here), but have settled on using the add_sub() function from the cowplot package. However, it does not seem straightforward to add more than one addition label, as subsequent labels add below the plot already-modified with one additional label, whereas it should be vertically aligned with it). Here is an example, where "My Label" is in the correct position, but "My Second Label" is not. I've tried manually adjusting the vertical / y-axis position of the second label, but the same problem emerges with subsequent labels (in fact in a more tricky form, as the same adjustment that worked for the second label does not work in any straightforward way for the third). Here is an example:

library(ggplot2)
library(cowplot)
#> 
#> Attaching package: 'cowplot'
#> The following object is masked from 'package:ggplot2':
#> 
#>     ggsave

p <- ggplot(diamonds, aes(x = carat, y = price, color = cut)) +
    geom_point()

p1 <- add_sub(p, label = "My Label", x = .125)
p2 <- add_sub(p1, label = "My Second Label", x = .275)

ggdraw(p2)

How can I add additional x-axis labels to a ggplot2 plot (with discrete axis labels) using the add_sub() function from cowplot?

Joshua Rosenberg
  • 4,014
  • 9
  • 34
  • 73

2 Answers2

1

You get this result because add_sub is taking the input plot and writing below it, thus everytime you add another add_sub you'll be 1 level lower.

This is what I'd do to work around it:

p <- ggplot(diamonds, aes(x = carat, y = price, color = cut)) +
  geom_point()

p1 <- add_sub(p, label = c("My Label   My Second Label"))

ggdraw(p1)

enter image description here

and of course you can add more spaces between or make other tweaks as needed.

Hack-R
  • 22,422
  • 14
  • 75
  • 131
  • This is great - but is surprisingly hard to use to get the labels in just the right position. – Joshua Rosenberg Oct 03 '17 at 19:48
  • @JoshuaRosenberg If you want to give me an example I will help. Don't forget you can set `x` in addition to using spaces, use justification, etc. – Hack-R Oct 03 '17 at 20:34
1

You need to add hjust=0 to left-justify the labels...

p <- ggplot(diamonds, aes(x = carat, y = price, color = cut)) +
  geom_point() 

p1 <- add_sub(p, label = "My Label", x = .125, hjust=0)
p2 <- add_sub(p1, label = "My Second Label", x = .125, hjust=0)

ggdraw(p2)

enter image description here

Andrew Gustar
  • 17,295
  • 1
  • 22
  • 32