Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gganimate round values during transition

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?

like image 969
Joachim Schork Avatar asked Feb 10 '19 13:02

Joachim Schork


1 Answers

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

like image 162
Mike N. Avatar answered Nov 07 '22 01:11

Mike N.