按年份创建具有多列的数据集的动画图表

Create animated chart of a dataset with multiples columns by year

数据集是

year ID top_1 top_2 top_3
1952 25 7012 6647 6419
1953 28 8850 7165 6470
1954 31 8188 7678 7246
1955 34 8586 8485 7525
1956 37 8850 8516 8163
1957 40 7525 6501 NA
1958 43 8188 6165 NA
1959 46 6707 6187 5630

我想要这样的东西

我不确定要在 aes() 参数中放入什么

p <- ggplot( data = x , aes(year, y = ??  ) +
  geom_bar( stat = "identity" ) +
  transition_states(year) +
  labs(title = "abc") +
  coord_cartesian(ylim = c(5500 , 9000)) +
  xlab("") +
  ylab("hgt")
animate(p, nframes = 450, fps=16)

首先,您需要使用 melt 重塑数据。之后,您可以设置 transition_states 以显示不同年份的条形图。要在标题中显示年份,您可以使用 {next_state}。您可以使用以下代码:

library(tidyverse)
library(gganimate)
library(reshape)

df_melted <- melt(df, id = c("ID", "year"))

p <- df_melted %>%
  ggplot(aes(x = variable, y = value, fill = variable)) +
  geom_bar(stat = "identity" ) +
  transition_states(
    year,
    transition_length = 2,
    state_length = 1
  ) +
  ease_aes('sine-in-out') +
  labs(title = "Heighest 3 peaks in Year: {next_state}") +
  xlab("") +
  ylab("hgt")
p  

输出: