首页 > 解决方案 > 使用 gganimate 为 geom_bar 设置动画的问题

问题描述

我遇到了 gganimate 的问题,我需要一些帮助。

我试图显示一个条形图,然后在几年内对其进行动画处理,但我没有输出,也没有显示错误。有错误还是我错过了什么?

我正在使用有关欧盟工作事故的数据。我的 R 版本是:3.6.1 (2019-07-05)

希望下面的代码演示了这个问题

library(eurostat)
library(rvest)
library(tidyverse)
library(plotly)
library(gganimate)

# get Eurostat data: accidents at work
d_list <- get_eurostat('hsw_ph3_02')

## cast the list into an R data frame
df <- as.data.frame(d_list)

# get data 
data_UE27_time <- subset(df, df$wrkenv == "TOTAL" & df$geo =="EU27" & 
                             df$severity =="FAT" & df$sex == "M" & df$age == "TOTAL" &
                             df$unit == "NR" & df$nace_r2 != "TOTAL" & df$nace_r2 != "A_C-N", 
                         select=c(nace_r2,values,time))

#animated bar plot
gp <- ggplot(data = data_UE27_time, aes(x = nace_r2, y = values))+
  geom_bar(stat="identity") +
   transition_time(time) +
  labs(title = "Year: {frame_time}")

标签: rggplot2plotlyr-plotlygganimate

解决方案


library(dplyr)
library(magick)
library(png)
library(gganimate)

gp <- data_UE27_time %>% 
        as_tibble() %>% 
        ggplot(aes(x = nace_r2, y = values, group = time)) +
          geom_bar(stat="identity") +
          transition_time(time) +
          labs(title = "Year: {frame_time}")

animate(gp, nframes = 10)

reprex 包(v0.3.0)于 2019 年 12 月 2 日创建


推荐阅读