简体   繁体   中英

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 , ie 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 ?

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)

在此处输入图片说明

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

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)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM