我正在使用如何在
gganimate
制作gif,我想通过将ggplot
对象转换为gtable
来进行一些细微的图形格式调整。例如,我想改变图形标题的位置,使其始终出现在图形的左上角。
下面是一个图形调整的示例:
library(ggplot2)
library(gganimate)
library(dplyr)
# Helper function to position plot title all the way to left of plot
align_titles_left <- function(p, newpage = TRUE) {
p_built <- invisible(ggplot2::ggplot_build(p))
gt <- invisible(ggplot2::ggplot_gtable(p_built))
gt$layout[which(gt$layout$name == "title"), c("l", "r")] <- c(2, max(gt$layout$r))
gt$layout[which(gt$layout$name == "subtitle"), c("l", "r")] <- c(2, max(gt$layout$r))
# Prints the plot to the current graphical device
# and invisibly return the object
gridExtra::grid.arrange(gt, newpage = newpage)
invisible(gt)
}
# Create an example plot
static_plot <- iris %>%
ggplot(aes(x = Sepal.Length, y = Sepal.Width,
color = Species)) +
geom_point() +
labs(title = "This title should appear in the far left.")
# Print the static plot using the adjustment function
align_titles_left(static_plot)
如何在gganimate
中使用此函数?
下面是一些示例gganimate
代码,可以将此示例中的图形转换为动画。
# Produce the animated plot
static_plot +
transition_states(Species,
transition_length = 3,
state_length = 1)