【问题标题】:Animated graph using gganimate使用 gganimate 的动画图
【发布时间】:2019-06-10 11:10:16
【问题描述】:

我有一个示例数据,我想使用显示随时间变化的动画图表来绘制。

#here's the data
df <- structure(list(`Year` = c(2012, 2012, 2012, 2013, 2013, 2013, 2014, 2014, 2014), 
                 `continent` = c("Africa", "Asia", "Europe", "Africa", "Asia", "Europe", "Africa", "Asia", "Europe"),
                 `Cash` = c(400000, 410000, 200000, 300000, 500000, 250000, 400000, 600000, 500000)),
            row.names = c(NA, -9L), class = c("tbl_df", "tbl", "data.frame"))



#here's my attempt at plotting it
ggplot(df, aes(Year, Cash, group = continent)) +
  geom_line(aes(colour = continent)) +
  geom_segment(aes(xend = 2012, yend = Cash), linetype = 2, colour = 'grey')+
  geom_point(size = 2, colour = "white") + 
  geom_text(aes(x = 2012.1, label = continent), hjust = 0)+
  transition_reveal(continent, Year) + 
  coord_cartesian(clip = 'off') + 
  theme(plot.margin = margin(5.5, 40, 5.5, 5.5), legend.position = "none")
#I am getting the error below
Error in ggproto(NULL, TransitionReveal, params = list(along_quo = along_quo,  : 
  object 'Year' not found

#when I remove continent from transition_reveal, i get a plot but it doesn't look nice at all.
#I would like to plot something similar to the picture below

【问题讨论】:

    标签: r


    【解决方案1】:

    使用transition_reveal(Year) +; ggplot(aes()) 调用中的 group 术语负责将系列分开。

    library(gganimate)
    a <- ggplot(df, aes(Year, Cash, group = continent)) +
      geom_line(aes(colour = continent)) +
      # Edit - I found the dashed lines distracting when they moved with 
      #   the points, because they were drawn from x = the active Year back
      #   to xend = 2012, making a kind of moire pattern.
      # geom_segment(aes(xend = 2012, yend = Cash), linetype = 2, colour = 'gray40')+
      # Direction of segment reversed below, less distracting
      geom_segment(aes(x = 2012, xend = Year, yend = Cash), linetype = 2, colour = 'gray50')+
      geom_point(size = 2, colour = "white") + 
      geom_text(aes(x = 2012.1, label = continent), hjust = 0, vjust = -0.4) +
      scale_y_continuous(labels = scales::comma) +
      scale_x_continuous(breaks = 2012:2014, minor_breaks = NULL, labels = scales::comma_format(big.mark = "")) +
      transition_reveal(Year) + 
      coord_cartesian(clip = 'off') + 
      theme(plot.margin = margin(5.5, 40, 5.5, 5.5), legend.position = "none")
    
    animate(a, fps = 30, duration = 10, width = 500, height = 250)
    

    【讨论】:

    • 非常感谢乔恩。最后一件事,我正在尝试更改主题,我尝试了 theme_economist() 和 theme_wsj() 但它告诉我“它找不到函数“theme_economist()””。你能帮忙吗?
    • 你先加载library(ggthemes)了吗?
    猜你喜欢
    • 2021-02-22
    • 1970-01-01
    • 1970-01-01
    • 2019-03-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-13
    • 2020-07-23
    • 1970-01-01
    相关资源
    最近更新 更多