Longer plot labels move to the right when arranging plots with plot_grid from cowplot

淺唱寂寞╮ 提交于 2020-01-06 06:18:09

问题


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"))

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"))

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:


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)

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.



来源:https://stackoverflow.com/questions/47724511/longer-plot-labels-move-to-the-right-when-arranging-plots-with-plot-grid-from-co

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!