【发布时间】: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_time 或transition_states 与shadow_mark 一起使用,我将无法绘制线,而如果我使用transition_reveal 来获取线,过去几年的条形图正在消失。
我需要让条形图和线形图都通过years,同时保留过去的值。
【问题讨论】: