如何 left-align 在 gganimate 动画中绘制标签?

How can I left-align plot labels in a gganimate animation?

我想将绘图标签(标题、副标题)对齐到图像的左侧,而不是绘图区域的左侧,以获得 gganimate 动画。

这可以通过转换为 gtable 然后修改布局来使用静态图表。动画需要一种不同的方法,因为 gganimate objects 无法转换为 gtable。

此代码使用默认标题和副标题对齐方式创建静态图:

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

情节如下:

我希望标题和副标题对齐到图像的左侧,而不是绘图区域的左侧。这对于静态图来说很简单,如下:

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

这会将标题和副标题对齐到图片的左侧,看起来像这样:

在 gganimate 图表上尝试 left-align 标签时出现问题。

已转换为gtable的ggplot2图表(如上例中的gtable_plot)不能用于创建gganimate动画。一旦创建了动画 object,就无法将其转换为 gtable object。

例如,这会引发错误:

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


ggplotGrob(anim_plot)

这也不行:

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

因此,我需要一些其他方法来将标签对齐到图像的左侧,以便与 gganimate 一起使用。请注意,我不想使用 +theme(plot.title = element_text(hjust = -n)),因为 n 会因地块而异。

the dev version of ggplot2, thanks to Claus Wilke 现在可以做到这一点。 ggplot2 现在通过 theme() 的参数支持 left-alignment,而不必修改使用 ggplotGrob() 转换的绘图。这意味着您可以制作静态图,left-align 标题(和副标题 + 标题),然后使用 gganimate 对其进行动画处理。

参数是:theme(plot.title.position = "plot")