Joshua Rosenberg
Joshua Rosenberg

Reputation: 4226

Add additional x-axis labels to a ggplot2 plot (with discrete axis labels) using cowplot

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?

Upvotes: 1

Views: 1164

Answers (2)

Andrew Gustar
Andrew Gustar

Reputation: 18425

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

Upvotes: 1

Hack-R
Hack-R

Reputation: 23214

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.

Upvotes: 1

Related Questions