3
votes

I want to align my plot labels (title, subtitle) to the left of my image, not the left of the plotting area, for a gganimate animation.

This is possible with static charts by converting to a gtable and then modifying the layout. A different approach is needed for animations, as gganimate objects cannot be converted to gtable.

This code creates a static plot with default title and subtitle alignment:

library(tidyverse)
library(gganimate)

static_plot <- iris %>%
  ggplot(aes(x = Sepal.Length, y = Sepal.Width,
             color = Species)) +
  geom_point() +
  labs(title = "I want this aligned with the left edge of the chart",
       subtitle = "Not the left edge of the plotting area",
       caption = "Because it looks better")

Here's what the plot looks like:

static plot with default label alignment

I would like the title and subtitle to be aligned to the left of the image, not the left of the plotting area. This is straightforward for static plots, as follows:

gtable_plot <- ggplotGrob(static_plot)
gtable_plot$layout$l[gtable_plot$layout$name %in% c("title", "subtitle")] <- 1

This aligns the title and subtitle to the left of the image, and looks like this:

static plot with desired label alignment

The problem comes when trying to left-align labels on a gganimate chart.

A ggplot2 chart that has been converted to a gtable (like gtable_plot in the example above) cannot be used to create a gganimate animation. Once an animation object has been created, it cannot be converted to a gtable object.

For example, this throws an error:

anim_plot <- static_plot +
  transition_states(Species,
                    transition_length = 2,
                    state_length = 1)


ggplotGrob(anim_plot)

This also does not work:

gtable_plot +
  transition_states(Species,
                    transition_length = 2,
                    state_length = 1)

I therefore need some other way of aligning labels to the left of the image that will work with gganimate. Please note that I do not want to use +theme(plot.title = element_text(hjust = -n)), as n will vary for different plots.

1

1 Answers

0
votes

This is now possible with the dev version of ggplot2, thanks to Claus Wilke. ggplot2 now supports left-alignment through an argument to theme(), rather than having to modify a plot that has been converted using ggplotGrob(). This means you can make a static plot, left-align the title (and subtitle + caption) and then animate that using gganimate.

The argument is: theme(plot.title.position = "plot")