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?

0

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This is great - but is surprisingly hard to use to get the labels in just the right position.
@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.
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

2 Comments

I'm so sorry - I think I meant I need the labels should be horizontally aligned, as in @Hack-R's answer
@JoshuaRosenberg No problem - I've learnt something new, so that's still worthwhile!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.