3
votes

I was asked this question on Twitter and thought it might be good to have it here.

When making labeled, side-by-side plots with plot_grid(), things work as expected for single-letter labels:

library(cowplot)

p1 <- ggplot(iris, aes(x = Sepal.Length, fill = Species)) + 
  geom_density(alpha = 0.7) +
  ggtitle("") + theme_minimal()

p2 <- ggplot(iris, aes(x = Sepal.Length, fill = Species)) + 
  geom_density(alpha = 0.7) +
  ggtitle("") +
  scale_fill_grey() + theme_minimal()

plot_grid(p1, p2, labels = c("A", "B"))

enter image description here

However, if we're using longer strings as labels, the labels move to the right, and they move the more the longer the strings are:

plot_grid(p1, p2, labels = c("Density plot in color", "In gray"))

enter image description here

How can this be fixed?

Disclaimer: I'm the author of the package. Posting this here with answer in the hope it will be useful.

1

1 Answers

5
votes

The default settings for the parameters hjust and label_x in plot_grid() are optimized for single-letter labels, and they don't work for longer labels. Overriding the settings fixes the problem:

plot_grid(p1, p2, labels = c("Density plot in color", "In gray"),
          hjust = 0, label_x = 0.01)

enter image description here

In particular, the default hjust setting is hjust = -0.5. This moves the label to the right by an amount equivalent to half its width. This makes sense for single letter labels, because then we can have the letters appear half a letter width away from the left border by setting label_x = 0, and this will work irrespective of label font size or any other plot features the user may have chosen.

However, moving a label by half its width doesn't make any sense at all for longer labels, and in particular labels of differing lengths.