0

I want to align Plots with titles with grid.arrange so that the y-Axis of the two plots matches. If one of the plots has a Title that contains a character with a decender (g,j,y,...) and the other doesn't the plots are misaligned.

Is there an option to fix the size of the element e.g. in element_text in the theme to line heights including decenders?

An alternative would be to modify the grid-grobs directly with ggplotGrob but this seems overly complicated.

require(ggplot2)
require(gridExtra)

test <- data.frame(x=1:3, y=1:3)

plot1 <- ggplot(test, aes(x=x, y=y)) +
  geom_point() +
  ggtitle("asdf")

plot2 <- ggplot(test, aes(x=x, y=y)) +
  geom_point() +
  ggtitle("asdfg")

grid.arrange(plot1, plot1, nrow=1)
grid.arrange(plot1, plot2, nrow=1)

Notice the slight difference in the alignment of the top border of the plotting area in the second plot. In the first one both are aligned perfectly.

snaut
  • 2,261
  • 18
  • 37
  • have you seen this [post](https://stackoverflow.com/questions/25061822/ggplot-geom-text-font-size-control/25062509)? If yes and no resolution, then how is your question different from it. Please explain. – mnm Mar 30 '18 at 11:10
  • I did not know this post, but still it's no resolution to my problem. The text elements that differ in height are both defined in the theme, not in the theme and a text element as in this post. Also I don't want to scale the font, but want the grob to have constant height independent of the characters appearing in the title. – snaut Mar 30 '18 at 11:17

1 Answers1

0

This hack solves the Problem, but I think it only works for one line titles.

Set the lineheight to 0 and add an empty line to every title:

require(ggplot2)
require(gridExtra)

test <- data.frame(x=1:3, y=1:3)

plot1 <- ggplot(test, aes(x=x, y=y)) +
  geom_point() +
  theme(
    plot.title = element_text(lineheight = 0),
  ) +
  ggtitle("asdf\n")

plot2 <- ggplot(test, aes(x=x, y=y)) +
  geom_point() +
  theme(
    plot.title = element_text(lineheight = 0)
  ) +
  ggtitle("asdfg\n")

grid.arrange(plot1, plot1, nrow=1)
grid.arrange(plot1, plot2, nrow=1)
snaut
  • 2,261
  • 18
  • 37