我想将绘图标签(标题,副标题)对齐到我的图像的左侧,而不是绘图区域的左侧,以生成动画。
对于静态图表,可以通过转换为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")
这是情节的样子:
我希望标题和副标题对齐到图像的左侧,而不是绘图区域的左侧。对于静态图,这很简单,如下所示:
gtable_plot <- ggplotGrob(static_plot)
gtable_plot$layout$l[gtable_plot$layout$name %in% c("title", "subtitle")] <- 1
这会将标题和副标题对齐到图像的左侧,如下所示:
当试图在对齐图表上使标签左对齐时出现问题。
已转换为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
会因地块的不同而有所不同。
答案 0 :(得分:0)
Insert ASCII or Unicode Latin-based symbols and characters现在可以实现。 ggplot2现在支持通过HKCU\Control Panel\Input Method
的参数进行左对齐,而不必修改使用theme()
转换的图。这意味着您可以制作静态图,将标题(和字幕+标题)左对齐,然后使用gganimate对其进行动画处理。
参数为:ggplotGrob()