使用 R 制作包含条形图和线图的动画图
Animate plot containing both bar and line plots using R
我有这种格式的数据:
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
对任何一个图进行动画处理,使得过去的 values/bars 在通过 year
变量的过程中显示在图中。
如果我使用 transition_time
或 transition_states
以及 shadow_mark
,我无法绘制线,而如果我使用 transition_reveal
来获取线,则过去几年的酒吧正在消失。
我需要在保留过去的值的同时让条形图和线条都经过 years
。
我想你要找的是 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)
我有这种格式的数据:
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
对任何一个图进行动画处理,使得过去的 values/bars 在通过 year
变量的过程中显示在图中。
如果我使用 transition_time
或 transition_states
以及 shadow_mark
,我无法绘制线,而如果我使用 transition_reveal
来获取线,则过去几年的酒吧正在消失。
我需要在保留过去的值的同时让条形图和线条都经过 years
。
我想你要找的是 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)