6

I want to create an animated barplot with the gganimate package. At the top of each bar, I want to put the value of the bar rounded to zero digits.

Consider the following example:

# Example data
df <- data.frame(ordering = c(rep(1:3, 2), 3:1, rep(1:3, 2)),
                 year = factor(sort(rep(2001:2005, 3))),
                 value = round(runif(15, 0, 100)),
                 group = rep(letters[1:3], 5))

# Create animated ggplot
ggp <- ggplot(df, aes(x = ordering, y = value)) +
  geom_bar(stat = "identity", aes(fill = group)) +
  transition_states(year, transition_length = 2, state_length = 0) +
  geom_text(y = df$value, label = as.integer(round(df$value)))
ggp

enter image description here

Unfortunately, I did not manage to round the values properly. Is there a way to round values during transition?

Joachim Schork
  • 2,025
  • 3
  • 25
  • 48
  • `round(runif(15, 0, 100),0)`? **Not sure** – NelsonGon Feb 10 '19 at 13:15
  • @NelsonGon Unfortunately, that does not work. – Joachim Schork Feb 10 '19 at 13:17
  • 1
    https://stackoverflow.com/questions/53055118/gganimate-geom-text-with-numeric-values-animates-at-decimal-numbers-instead-of I don't think there is some option to do that at the moment, but there is a "manual" solution on this question you could easily adapt. – VFreguglia Feb 10 '19 at 13:19
  • @Freguglia Thank you for your response! The problem with the manual solution provided in the other thread is that the duration of the horizontal transition of the bars would be shortened. In the suggested thread there is no horizontal transition and therefore the solution works for the barchart of the other thread, but not for mine. Do you know a way how I could retain the horizontal transition duration? – Joachim Schork Feb 11 '19 at 09:38
  • 1
    open issue https://github.com/thomasp85/gganimate/issues/204 – qwr Apr 08 '20 at 01:07

1 Answers1

5

Since df$value is already rounded to zero decimals via round() you can use as.character() when setting your labels.

> df$value
[1] 29 81 92 50 43 73 40 41 69 15 11 66  4 69 78
> as.character(df$value)
[1] "29" "81" "92" "50" "43" "73" "40" "41" "69" "15" "11" "66" "4"  "69" "78"

Result:

ggp <- ggplot(df, aes(x = ordering, y = value)) +
  geom_bar(stat = "identity", aes(fill = group)) +
  transition_states(year, transition_length = 2, state_length = 0) +
  geom_text(label = as.character(df$value))

enter image description here

Mike N.
  • 1,662
  • 1
  • 13
  • 19
  • 1
    Thank you for your answer! The problem with your solution is that the values are not reflecting the movement in between, but only the fixed points that are defined in the input data. Do you know a way how the values could reflect the transition movement? – Joachim Schork Feb 11 '19 at 09:41