Search code examples
rggplot2textgganimate

Why are colours appearing in the labels of my gganimate sketch?


I have a gganimate sketch in R and I would like to have the percentages of my bar chart appear as labels.

But for some bizarre reason, I am getting seemingly random colours in place of the labels that I'm requesting.

screen grab of animated gif

If I run the ggplot part without animating then it's a mess (as it should be), but it's obvious that the percentages are appearing correctly.

enter image description here

Any ideas? The colour codes don't correspond to the colours of the bars which I have chosen separately. The codes displayed also cycle through about half a dozen different codes, at a rate different to the frame rate that I selected. And while the bars are the same height (they grow until they reach the chosen height displayed in the animation) then they display the same code until they stop and it gets frozen.

Code snippet:

df_new <- data.frame(index, rate, year, colour)
df_new$rate_label <- ifelse(round(df_new$rate, 1) %% 1 == 0, 
                            paste0(round(df_new$rate, 1), ".0%"), paste0(round(df_new$rate, 1), "%"))

p <- ggplot(df_new, aes(x = year, y = rate, fill = year)) +
  geom_bar(stat = "identity", position = "dodge") + 
  scale_fill_manual(values = colour) + 
  #geom_text(aes(y = rate, label = paste0(rate, "%")), vjust = -0.7) + 
  geom_shadowtext(aes(y = rate, label = rate_label),
                  bg.colour='white',
                  colour = 'black',
                  size = 9,
                  fontface = "bold",
                  vjust = -0.7,
                  alpha = 1
  ) +
  coord_cartesian(clip = 'off') +
  ggtitle("% population belonging to 'No religion', England and Wales census") +
  theme_minimal() + 
  xlab("") + ylab("") +
  theme(legend.position = "none") + 
  theme(plot.title = element_text(size = 18, face = "bold")) +
  theme(axis.text = element_text(size = 14)) +
  scale_y_continuous(limits = c(0, 45), breaks = 10*(0:4))
p

p <- p + transition_reveal(index) + view_follow(fixed_y = T)

animate(p, renderer = gifski_renderer(), nframes = 300, fps = frame_rate, height = 500, width = 800,
        end_pause = 0)

anim_save("atheism.gif")

Solution

  • So it was answered here although I don't know why the fix works.

    For some reason, labels need to go into gganimate as factors

    as.factor()
    

    I just had to add the line:

    df_new$rate_label <- as.factor(df_new$rate_label)
    

    and it works fine.

    screengrab from animation