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
Unfortunately, I did not manage to round the values properly. Is there a way to round values during transition?
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With