2

How can I use cowplot to add labels to plots in multiplot panels, where the labels have superscripts?

I can use superscripts on the axis titles with substitute, bquote or expression, like this:

library(ggplot2)
library(cowplot)

p1 <- ggplot(mtcars, aes(disp, mpg)) +
  geom_point()
p2 <- ggplot(mtcars, aes(disp, hp)) +
  geom_point() +
  # this will create a nice superscript
  xlab(bquote(A^x))

p2

enter image description here

But I don't know how to give a set of those labels to cowplot to label multiple plots:


# create a vector of labels for the grid of plots
labels_with_superscript <- 
  c(bquote(A^x), 
    bquote(B^x))

# create the grid of plots? 
plot_grid(p1, p2, 
          ncol = 1, 
          align = "v",
          labels =  labels_with_superscript
)

Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE, : object 'A' not found

What's the secret to getting that to work so I can get something like Ax and Bx as the plot labels instead of A and B in the plot below?

plot_grid(p1, p2, 
          ncol = 1, 
          align = "v",
          labels =  "AUTO"
)

enter image description here

Ben
  • 41,615
  • 18
  • 132
  • 227
  • 1
    I cant get it to work but I think you need to pass `parse = TRUE` to the `plot_grid` function so that it can work with `geom_text`, something similar to [this](https://stackoverflow.com/questions/59129952/using-ggplot-geom-text-when-combining-superscript-and-variable-label-that-contai). If you look at the underlying code, its using `geom_text`, i.e. run `draw_plot_label` and `draw_text` in console...not sure thats of any help – user63230 Dec 01 '20 at 10:06

1 Answers1

4

You can do this using a plotmath expression. @user63230 has the right idea in the comments, however, you can't pass the parse argument to the plot_grid() function but you can use draw_plot_label() afterwards although you also need to specify the label positions:

library(ggplot2)
library(cowplot)

labels_with_superscript <-  c("A^x", "B^x")

plot_grid(p1, p2, 
          ncol = 1, 
          align = "v") +
  draw_plot_label(labels_with_superscript, x = c(0, 0), y = c(1, .5), parse = TRUE)

enter image description here

Ritchie Sacramento
  • 29,890
  • 4
  • 48
  • 56
  • Is there a method available where the placement of the labels is automatic, like the standard plot_grid labelling? I have a panel of nine plots, and setting individual plot locations by coordinates is going to take a great deal of trial and error to find the right locations. Thank you – Ben Dec 01 '20 at 22:15
  • Probably the easiest thing to do is just to edit the `parse` argument into the `draw_plot_label()` call within the `plot_grid()` function as that already calculates label coordinates taking into account the layout and relative sizes of the plots, e.g. `new_plot_grid <- edit(plot_grid)` - the function begins on line 70. – Ritchie Sacramento Dec 01 '20 at 23:06