具有gganimate的动态轴标签

时间:2019-07-03 14:05:18

标签: r ggplot2 gganimate

请查看文章末尾的代码。我正在制作动画,其中一些条形图会随时间交换位置,以便始终从最大到最小排名。 缺少的内容(它必须是单线的,但我不能正确地做到这一点)是在y轴上添加一些标签(“汽车品牌”),这些标签也跟随其运动中的条形图。 这在加尼玛尼中可行吗? 谢谢!

rm(list=ls())


library(ggplot2)
library(gganimate)
library(viridis)
library(scales)

df <- structure(list(year = c(2009L, 2009L, 2009L, 2009L, 2009L, 
2009L, 
2009L, 2009L, 2010L, 2010L, 2010L, 2010L, 2010L, 2010L, 2010L, 
2010L, 2011L, 2011L, 2011L, 2011L, 2011L, 2011L, 2011L, 2011L, 
2012L, 2012L, 2012L, 2012L, 2012L, 2012L, 2012L, 2012L, 2013L, 
2013L, 2013L, 2013L, 2013L, 2013L, 2013L, 2013L, 2014L, 2014L, 
2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2015L, 2015L, 2015L, 
2015L, 2015L, 2015L, 2015L, 2015L, 2016L, 2016L, 2016L, 2016L, 
2016L, 2016L, 2016L, 2016L), brand = structure(c(1L, 2L, 3L, 
4L, 5L, 6L, 7L, 8L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 1L, 2L, 3L, 
4L, 5L, 6L, 7L, 8L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 1L, 2L, 3L, 
4L, 5L, 6L, 7L, 8L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 1L, 2L, 3L, 
4L, 5L, 6L, 7L, 8L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L), .Label =   
 c("Citroen", 
"Fiat", "Ford", "Opel", "Peugeot", "Renault", "Volkswagen", "Other"
)   , class = "factor"), value = c(924111, 1021942, 1239489, 938400, 
960536, 1188702, 1510253, 5529845, 959405, 940856, 1179685, 1039742, 
1043974, 1243694, 1611953, 6276478, 928320, 855064, 1128147, 
1035073, 993881, 1179988, 1768384, 6453032, 770751, 711860, 1004351, 
813578, 850368, 936676, 1656771, 6197882, 725815, 721701, 1010450, 
837515, 798557, 948212, 1651806, 6237630, 754466, 734565, 1143046, 
912828, 888482, 1057786, 1742056, 6739541, 782841, 835529, 1324603, 
997695, 980186, 1246559, 1787549, 7506155, 795025, 943298, 1272251, 
1046056, 1011515, 1429635, 1765735, 8097817), ordering = c(1L, 
4L, 6L, 2L, 3L, 5L, 7L, 8L, 2L, 1L, 5L, 3L, 4L, 6L, 7L, 8L, 2L, 
1L, 5L, 4L, 3L, 6L, 7L, 8L, 2L, 1L, 6L, 3L, 4L, 5L, 7L, 8L, 2L, 
1L, 6L, 4L, 3L, 5L, 7L, 8L, 2L, 1L, 6L, 4L, 3L, 5L, 7L, 8L, 1L, 
2L, 6L, 4L, 3L, 5L, 7L, 8L, 1L, 2L, 5L, 4L, 3L, 6L, 7L, 8L)), 
class =    c("tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -64L))


gpl <- ggplot(data = df, aes(x  = ordering, y=value/1e6,
                         group= brand  ,
                          fill=brand
                         )) +
geom_bar(position=position_dodge2(reverse=T), stat="identity", alpha=1)+



## scale_x_continuous(
##     breaks = df$ordering,
##     labels = df$brand,
##     expand = c(0,0)
##   ) +


coord_flip()+
theme(axis.text.x = element_text(size=15,angle=0, colour="black",  
vjust=0.5), axis.text.y = element_text(angle=0) )+

scale_fill_viridis(discrete=T)+



scale_y_continuous(breaks=pretty_breaks(n=5))+

xlab("Brand")+
ylab("Million of Vehicles")+


labs(title = 'Vehicles Sold  in Year: {frame_time}') +
transition_time(year) +
ease_aes('linear')


anim <- animate(gpl, width=1200, height=600)



anim_save("myanimation.gif", anim)

0 个答案:

没有答案