Based on this SO question I am trying to create an animated bar plot, but the bar label tween values are showing hexadecimal values:
library(ggplot2)
library(dplyr)
library(gganimate)
set.seed(123)
df <- data.frame(
period = rep(1:3, each = 5),
x = rep(LETTERS[1:5], 3),
p = rbeta(15, 3, 2)
)
data <- df %>%
group_by(period) %>%
mutate(rank = min_rank(-p)) %>%
ungroup()
ggplot(data, aes(x = rank)) +
geom_tile(aes(y = p / 2,
height = p,
width = 0.75)) +
geom_text(aes(y = p,
label = scales::percent(p, 1)),
hjust = 0,
nudge_y = 0.005) +
coord_flip(clip = "off", expand = F) +
scale_x_reverse() +
labs(title = 'Period {closest_state}',
x = "",
y = "") +
theme(axis.text = element_blank(),
axis.ticks = element_blank(),
plot.margin = margin(r = 5, unit = "cm")) +
transition_states(period) +
ease_aes('linear')
Things I have tried
- As this other SO question suggests I have tried
label = round(p * 100)
. - I have tried to create character labels in
df
:df$labs <- paste0(round(df$p * 100), "%")
and then using them in thegeom_text
label instead ofp
.
Questions
I have two questions:
- How do I correct these tween values so they properly display as rounded percentages?
- Is there a way to hide tween values and only show the true values once a transition state is reached (e.g., at Period 1, Period 2, and Period 3 only)?