r - Ggplot - plot a dataframe with multiple points in 1 row in order to animate it with gganimate -
i have dataframe each row contains information coordinates of 8 points @ point in time:
time x1 y1 x2 y2 x3 y3 … x8 y8
a row may example:
mydata <- data.frame(time=0.1,x1=-7.79,y1=7.32,x2=-3.86,y2=-1.62,x3=-1.35,y3=-4.61,x4=-6.24,y4=-9.89,x5=-6.40,y5=2.00,x6=4.02,y6=4.77,x7=-1.42,y7=9.89,x8=6.59,y8=-8.02)
the problem have ggplot accepts 1 column name each axis. moreover, animate movements of points using gganimate, that's why want use ggplot. how can this?
i managed animate data drawing plot using standard r plot() method each point in time , redrawing it, doesn't allow me save animation or work further.
this builds on answer pavodive , adds how animation part done.
i define larger data set such there animate:
set.seed(1544) mydata <- data.frame(seq(0, 1, = 0.1), matrix(runif(11*8*2, -10, 10), nrow = 11)) names(mydata) <- c("time", paste0(c("x", "y"), rep(1:8, each = 2)))
and use pavodive's code convert long format:
library(tidyr) library(magrittr) long_data <- gather(mydata, "coord", "value", -time) %>% separate(coord, sep = 1, = c("axis", "val2")) %>% spread(key = axis, value = value)
using gg_animate()
luckily rather simple. have add frame aesthetic:
p <- ggplot(long_data, aes(x = x, y = y, frame = time)) + geom_point() gg_animate(p, "animation.gif")
if using rstudio, can omit file name in gg_animate()
show plot in rstudio's plot pane.
Comments
Post a Comment