I have some data in which multiple y coordinate values for a single x coordinate value. It is similar to the one included in this question. It also has a state
variable which has to be used for the transition_state()
function in gganimate
.
library(data.table)
df <- data.table(
x = seq(11),
type1 = c(2, 3, 2.5, 3, 2, 2, 3, 2.5, 3.5, 3, 2),
type2 = c(NA, 3, 3.5, 3, NA, NA, 3, 3.5, 4, 3, NA)
)
m.df <- melt.data.table(df, "x", variable.name = "grp")
m.df[x %in% seq(5), "state" := 1][x %in% seq(6, 11), "state" := 2]
m.df
#> x grp value state
#> 1: 1 type1 2.0 1
#> 2: 2 type1 3.0 1
#> 3: 3 type1 2.5 1
#> 4: 4 type1 3.0 1
#> 5: 5 type1 2.0 1
#> 6: 6 type1 2.0 2
#> 7: 7 type1 3.0 2
#> 8: 8 type1 2.5 2
#> 9: 9 type1 3.5 2
#> 10: 10 type1 3.0 2
#> 11: 11 type1 2.0 2
#> 12: 1 type2 NA 1
#> 13: 2 type2 3.0 1
#> 14: 3 type2 3.5 1
#> 15: 4 type2 3.0 1
#> 16: 5 type2 NA 1
#> 17: 6 type2 NA 2
#> 18: 7 type2 3.0 2
#> 19: 8 type2 3.5 2
#> 20: 9 type2 4.0 2
#> 21: 10 type2 3.0 2
#> 22: 11 type2 NA 2
#> x grp value state
The data is plotted using gganimate as shown below.
library(ggplot2)
ggplot(m.df, aes(x, value, group = grp, color = grp)) +
geom_line(na.rm = T) +
geom_point(na.rm = T) +
theme_bw()
The plot can be found HERE
I want to use the gganimate transition_state()
function using the state column in the data as shown below, but shows an error.
library(gganimate)
ggplot(m.df, aes(x, value, group = grp, color = grp)) +
geom_line(na.rm = T) +
geom_point(na.rm = T) +
transition_states(state)
#> Error in rep(seq_len(nrow(polygon)), splits + 1): invalid 'times' argument
What am I doing wrong here?
Thank you in advance
One option to make your code work is to group by both grp
and state
using e.g. interaction
. Otherwise gganimate
fails to split your data by state
as both states are present in each group. Additionally, you have to put the group
aes after the color
aes. Otherwise you run in to the same issue:
library(ggplot2)
library(gganimate)
ggplot(m.df, aes(x, value, color = grp, group = interaction(grp, state))) +
geom_line(na.rm = T) +
geom_point(na.rm = T) +
transition_states(state)