Good morning SO community, I have the following snippet of code:
library( animation )
library( dplyr )
library( gganimate )
library( ggplot2 )
someData = data.frame( years = seq( -5000, 1000, by = 100 ) ) %>%
mutate( values = sample( 1:20, length( years ), replace = TRUE ),
label = ifelse( years < 0, paste0( abs( years ), ' B.C.E.' ), years ) )
chart = ggplot( someData ) +
geom_line( aes( x = years, y = values, frame = years, cumulative = TRUE ) ) +
ggtitle( 'Year: ' )
gganimate( chart, interval = .2 )
This way, the years appear in the title of the plot (numerically ordered).
Is there a way to put the label
values - in the same order they appear in the data frame - instead?
My first try was to use frame = label
in the aesthetics of geom_line
but the labels appeared in alphabetical order. So, I tried to change the levels order through:
someData$label = factor( someData$label, levels = someData$label, order = TRUE )
but this gave me the following error:
Error in frame_vec == f : comparison of these types is not implemented
In addition: Warning message:
In FUN(X[[i]], ...) :
Incompatible methods ("Ops.ordered", "Ops.factor") for "=="
Any help would be much appreciated, thanks.
There is actually a pending pull request concerning this functionality, but it hasn't been merged into the original repo yet. In the meantime, you could install the modified package using devtools::install_github("nteetor/gganimate")
, and then you can do:
gg_animate(chart, title_frame = ~ with(someData, label[years == .]))