I have a dataframe
df
:
df = data.frame(name = "bird",
value = seq(0, 1, length.out = 100),
step = 1:100)
I want to animate this data by showing the variable value
increasing. In the animation, I want to show the current step
and value
for that step.
This is what I have done so far:
library(ggplot2)
gg = ggplot(df, aes(name, value))
geom_bar(stat = "identity", fill = "darkgreen")
coord_cartesian(ylim = c(0, 1))
gg gganimate::transition_states(step)
ggtitle("Step: {closest_state}",
subtitle = "Value: {frame}")
step
is shown correctly, but clearly value
is not.
CodePudding user response:
In a similar vein, but without much piping and less computation (simple base R subsetting)
library(gganimate)
#> Loading required package: ggplot2
df <- data.frame(
name = "bird",
value = seq(0, 1, length.out = 100),
step = 1:100
)
anim <- ggplot(df, aes(name, value))
geom_col(fill = "darkgreen")
coord_cartesian(ylim = 0:1)
transition_manual(frames = step)
ggtitle("Step: {current_frame}",
subtitle = "Value: {round(df$value[as.integer(current_frame)], 2)}"
)
animate(anim, duration = 4)
Created on 2022-06-29 by the reprex package (v2.0.1)
PS I am using transition_manual
with current_frame
because gganimate did not show all frames. Another option would be to use set details = fps in animate
CodePudding user response:
You can filter your data by pull
ing the value for every step like this:
df = data.frame(name = "bird",
value = seq(0, 1, length.out = 100),
step = 1:100)
library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.1.2
library(gganimate)
library(dplyr)
#> Warning: package 'dplyr' was built under R version 4.1.2
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
gg = ggplot(df, aes(name, value))
geom_bar(stat = "identity", fill = "darkgreen")
coord_cartesian(ylim = c(0, 1))
gg transition_states(step)
ggtitle("Step: {closest_state}",
subtitle = "Value: {filter(df, step == closest_state) %>% pull(value) %>% .[[1]] %>% round(., 2)}")
Created on 2022-06-29 by the reprex package (v2.0.1)