Home > Back-end >  How to animate a point moving from left to middle and from middle to right of the plot?
How to animate a point moving from left to middle and from middle to right of the plot?

Time:08-30

I have 2 dataframes that I want to use for animation:

first = dplyr::tibble(name = "first",
                        name_anim = paste0("hi", 1:100),
                        label = "hi",
                        x = seq(0, 0.25, length.out = 100),
                        y = 0.5)

second = dplyr::tibble(name = "second",
                        name_anim = paste0("bye", 1:100),
                        label =  "bye",
                        x = seq(first$x[100], first$x[100]   0.25, length.out = 100),
                        y = 0.5)

I want my animation to show "hi" from left to middle, and from the middle I want the point "hi" to become "bye".

What I have tried so far:

library(ggplot2)

g = ggplot(data = rbind(first, second), aes(x, y))  
        geom_point(size = 15, alpha = 0.3, aes(col = name))  
        geom_text(aes(label = label))  
        guides(color = "none")

g   gganimate::transition_states(name_anim)

which gives the following animation:

enter image description here

There are 2 problems I want to solve:

  1. The animation should start from left to middle, and then middle to right. Currently, it starts from middle to right, and then left to middle.

  2. The moving point "jumps" back from time to time. (Why?) I want to fix this.

CodePudding user response:

The problem is that the transition states are ordered according to name_anim, but these have a lexicographic ordering that doesn't match the row ordering ("bye1" starts before "hi1" because it comes first alphabetically). If you want smooth row-wise transitions, you can use something like transition_time after inserting a simple 1:200 sequence column.

ggplot(data = within(rbind(first, second), name_anim <- 1:200), aes(x, y))  
  geom_point(size = 15, alpha = 0.3, aes(col = name))  
  geom_text(aes(label = label))  
  guides(color = "none")   
  gganimate::transition_time(name_anim/50)

enter image description here

  • Related