【问题标题】:Animate plot containing both bar and line plots using R使用 R 动画包含条形图和折线图
【发布时间】:2020-03-08 21:05:44
【问题描述】:

我有这种格式的数据:

head(data)
year    price   profit
2018    3185.96   9
2017    3249.69   10
2016    3005.24   6
2015    3739.79   17
2014    2238.22   15

我想将价格变量作为条形,将利润作为 x 轴的年份,并使用 gganimate 为绘图设置动画。我可以通过这种方式使用 2 y 轴绘制两个变量的静态图:

p1 <- ggplot(data) + geom_bar(aes(year, price, fill = year), stat = 'identity') +
  geom_line(aes(year, profit*100)) +
  scale_y_continuous(name = 'Price',sec.axis = sec_axis(~./100, 'Profit%')) 

或以这种方式使用构面网格:

long <- pivot_longer(data, -year, names_to = 'Category', values_to = 'Value')

p2 <- ggplot(long, aes(year, Value)) + facet_grid(Category~., scales = 'free') +
  geom_bar(data = long[long$Category == 'price', ], stat = 'identity') +
  geom_line(data = long[long$Category == 'profit', ])

问题是我无法使用gganimate 为任何一个绘图设置动画,以便在绘图通过year 变量时显示过去的值/条形图。

如果我将transition_timetransition_statesshadow_mark 一起使用,我将无法绘制线,而如果我使用transition_reveal 来获取线,过去几年的条形图正在消失。

我需要让条形图和线形图都通过years,同时保留过去的值。

【问题讨论】:

    标签: r ggplot2 gganimate


    【解决方案1】:

    我想你要找的是transition_manual():

    library(tidyverse)
    library(gganimate)
    
    data %>%
      ggplot(aes(year, price, fill = year)) + 
      geom_bar(stat = 'identity') +
      geom_line(aes(year, profit*100)) +
      scale_y_continuous(name = 'Price',
                         sec.axis = sec_axis(~./100, 'Profit%')) + 
      transition_manual(year, cumulative = TRUE)
    

    【讨论】:

      猜你喜欢
      • 2019-10-16
      • 2021-01-06
      • 2012-10-16
      • 2013-06-29
      • 1970-01-01
      • 2019-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多