r - 如何在 gganimate 动画中左对齐绘图标签?

标签 r ggplot2 gganimate

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

这可以通过转换为 gtable 然后修改布局来使用静态图表。动画需要一种不同的方法,因为 gganimate 对象无法转换为 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")

剧情是这样的:

static plot with default label alignment

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

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

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

static plot with desired label alignment

尝试在 gganimate 图表上左对齐标签时出现问题。

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

例如,这会引发错误:

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() 的参数支持左对齐,而不必修改已使用 ggplotGrob() 转换的绘图。这意味着您可以制作静态图,将标题(和副标题 + 说明)左对齐,然后使用 gganimate 对其进行动画处理。

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

关于r - 如何在 gganimate 动画中左对齐绘图标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57370339/

相关文章:

r - 根据 r 中的年龄确定出生日期

重置 ggplot 分面每列中的颜色

r - 如何在另一个包中使用 ggplot_add

r - 在 gganimate 中使用 transition_reveal 来累积绘制线条

r - 如何更快地渲染 ggplot2+gganimate+ggflags

r - 编写读取示例文件的 R 包小插图?

r - 显示每个方面而不是整体的摘要行

r - 如何在多面条形图中添加百分比值(qplot/ggplot/R)

r - gganimate 在 windows 10 中呈现像素化

r - 采样对数正态分布到精确均值和sd