【问题标题】:Add gradients and hand-drawn effects to gganimate plot为 gganimate 绘图添加渐变和手绘效果
【发布时间】:2025-12-26 06:05:17
【问题描述】:

我有兴趣将gganimate 与渐变以及手绘和绘画类型的填充效果一起使用(请参阅此处的粗略、绘画和渐变:https://semiotic.nteract.io/guides/sketchy-painty-patterns)。这可能吗?我发现ggrough (https://xvrdm.github.io/ggrough/) 能够将ggplot2 对象转换为具有这些效果。但是,是否可以使用ggrough 或其他一些东西与gganimate 结合使用?

还有其他方法可以做到这一点,即使在基础ggplot2 中(即不使用gganimate?)请注意,我担心这两个问题的答案是否定的,尤其是渐变填充(请参阅@hadley Hadley Wickhams 的回答这个问题:How to add texture to fill colors in ggplot2)。

或者还有其他解决方案仍然使用ggplot2,但不使用gganimate?我想如果可以在基础ggplot2 中制作许多单独的文件并将它们拼接在一起以制作.gif。虽然理论上我可以使用ggrough 的输出来做到这一点。

【问题讨论】:

  • 这可能是一种 rube goldberg 解决方案,但我不知道如何优雅地做到这一点。您可以获取您的数据,使用tweenr 跨帧进行插值,然后编写一个函数来渲染每个帧并使用以下内容保存输出:*.com/questions/56817353/… 然后您可以使用gifski 将帧组合成一个 gif。
  • 有趣!感谢您的建议并让我知道tweenr。我认为这可行。
  • 如果你愿意迁移到 python-plotnine (ggplot clone) 有动画支持 (plotnine.readthedocs.io/en/stable/generated/…) 和自定义主题支持,可能会绕过 ggplot 的一些限制.我能找到的最接近的预制是 xkcd-plotnine.readthedocs.io/en/stable/_modules/plotnine/themes/…(像漫画一样的摆动线条等)。您应该能够将 matplotlib 中的任何参数添加到 plotnine。
  • 感谢您对 python - plotnine 的提醒!

标签: r ggplot2 textures gradient gganimate


【解决方案1】:

另一个选择可能是使用xkcd 库来获得波浪线。它不会做波浪形的填充,但它是一个开始,并且处于正确的美学邻域。我无法使用gganimate 开箱即用,但可以使用tweenr 准备您的数据(gganimate 依赖的同一包)并将其输入gganimate::transition_manual 以获得良好的效果:

方法如下。鉴于这些虚假数据:

library(tidyverse); library(gganimate)
df <- tibble(Group = rep(1:3, times = 3),
             value = c(1:6, 3:1),
             period = rep(1:3, each = 3))

我们可以使用geom_rectgganimate::transition_states 制作动画。 geom_col 在这里会更容易,但我想稍后显示与xkcd::xkcdrect 的相似性。

ggplot() +
  geom_rect(data = df,
           aes(xmin = Group - 0.4, xmax = Group + 0.4,
               ymin = 0, ymax = value), 
           fill = "gray80") +
  transition_states(period)

当我放入 xkcd::xkcdrect 等效项时出现错误:

# Doesn't work
ggplot() +
  xkcd::xkcdrect(aes(xmin = Group - 0.4, xmax = Group + 0.4,
                     ymin = 0, ymax = value), fill = "gray80",
                 df) +
  transition_states(period)

if (nrow(from) == 0 && nrow(to) == 0) { 中的错误:缺失值 其中需要 TRUE/FALSE 另外:警告消息:1:在 rep("raw", length = nrow(from)) : 'length.out' 使用的第一个元素 论点 2:在 rep("raw", length = nrow(to)) 中:使用的第一个元素 'length.out' 参数 3:在 rep(NA_integer_, length = nrow(to)) 中:
'length.out' 参数使用的第一个元素

但是我们可以通过手动准备补间数据来到达同一个地方,然后将其输入transition_manual

df_tween <- tweenr::tween_states(
  list(df[1:3,],
       df[4:6,],
       df[7:9,],
       df[1:3,]), 3, 1, 'cubic-in-out', 100)


  ggplot() +
  xkcd::xkcdrect(aes(xmin = Group - 0.4, xmax = Group + 0.4,
                     ymin = 0, ymax = value), fill = "gray80",
                 df_tween) +
  transition_manual(.frame)

【讨论】: