2

首先,我为一个非常简单的时间序列线图创建了一个动画图……一些示例数据:

library(dplyr)
library(gganimate)
library(tweenr)

data <- tribble(
  ~year, ~num,
  1950, 56,
  1951, 59,
  1952, 64,
  1953, 67,
  1954, 69,
  1955, 74,
  1956, 78,
  1957, 83
)

dat_ani <- data %>% 
  ggplot(aes(x = year, y = num, frame = year, cumulative = TRUE)) +
  geom_path() +
  geom_point()

gganimate(dat_ani)

所以,只使用 gganimate 就可以了,但我想更进一步,使用 tweenr 来实现更平滑的过渡。

知道 tweenr 如何使用插值,我想要一个类似于上面的数据帧,但看起来更接近这个(只看 1950 年到 1951 年之间):

data2 <- tribble(
  ~year, ~num,
  1950.0, 56.0,
  1950.1, 56.3,
  1950.2, 56.6,
  1950.3, 56.9,
  1950.4, 57.2,
  1950.5, 57.5,
  1950.6, 57.8,
  1950.7, 58.1,
  1950.8, 58.4,
  1950.9, 58.7,
  1951.0, 59.0,
)

但与所有其他插值年份和数据点。我用 tween_elements() 函数尝试了另一种方法,但没有奏效(我认为因为 x、time 和 id 都是同一个变量……)。

我不知道如何创建这些数据帧的列表以用作 tween_states() 函数的输入。我试过了:

df_fun <- function(i) {
  dat <- data %>% subset(data$year[i])
  return(dat)
}

df_list <- purrr::map(seq(1950, 1957, by = 0.2), df_fun)

tween_data <- tween_states(df_list, tweenlength = 2, statelength = 3, 
                                             ease = "linear", nframes = 200)

在其他尝试中,但这当然行不通,因为原始数据框中没有年份 == 1950.2、1950.4 等……</p>

任何帮助,将不胜感激!

4

1 回答 1

3

如果其他人有兴趣,我在 RStudio 社区发帖并能够在那里找到答案:

https://community.rstudio.com/t/tweenr-gganimate-with-line-plot/4027/5?u=r-by-ryo

library(tidyverse)

data <- tribble(
  ~year, ~num,
  1950, 56,
  1951, 59,
  1952, 64,
  1953, 67,
  1954, 69,
  1955, 74,
  1956, 78,
  1957, 83
)

dat_ani <- map(seq(nrow(data)), ~data[c(seq(.x), rep(.x, nrow(data) - .x)), ]) %>% 
    tweenr::tween_states(5, 2, 'cubic-in-out', 100) %>% 
    ggplot(aes(year, num, frame = .frame)) + 
    geom_path() + 
    geom_point()

animation::ani.options(interval = 0.05)    # speed it up
gganimate::gganimate(dat_ani, title_frame = FALSE)

map 调用为每行创建一个包含与数据相同数量的观测值的数据框的列表,但将尚未显示的行替换为最后显示的行。现在 tweenr::tween_states 可以跟踪每个点应该移动的位置,这让它可以平滑地插值。

归功于RStudio 社区论坛上的alistaire !

于 2018-01-09T17:35:01.150 回答