Open richarddmorey opened 1 month ago
The first issue appears to be caused by the call to ggplot
's compute_geom_1
function at https://github.com/thomasp85/gganimate/blob/b46d1ff9bfee89c33ca8d6c4fd3fa1074c649027/R/plot-build.R#L76
The data is in the correct order prior to this, but after this call, the rows in each frame are sorted in the opposite order to what the should be. In this case, since the movement in the x direction is negative, the rows should be sorted in descending order. However, this function sorts them in ascending order so the order of the points is wrong in each frame.
The only workarounds that I see is to make as many frames as there are rows in the data (obviously with thousands of rows this would be prohibitive) or to detect the order before calling the function, then fix it after calling. However, I don't know enough about the internal workings of gganimate
or ggplot2
to do this without possibly breaking something else!
Edited to add:
To confirm this is the case, I did the following:
debug(gganimate:::ggplot_build.gganim)
data <- lapply(data,
function(el){
el[order(el$x, decreasing = TRUE),]
})
This results in the following correct plot:
If you're reading this and facing a similar issue to mine, the code below (or something like it) demonstrates a temporary work-around with version 1.0.9 and 1.0.9.9000 (line numbers in the trace
call might have to be changed if that function changes in a subsequent version):
Basically, it inserts code into the gganimate
method that builds the animation that sorts the x aesthetic in descending order, so that the plot renders correctly. This is super hacky and I would not expect it to work generally (so YMMV).
# Define code to be inserted
e <- quote(data <- lapply(data, function(el){
if(is.null(el$x)) # Assuming x is the aesthetic that needs sorted
return(el)
el[order(el$x, decreasing = TRUE),] # Sort the aesthetic correctly
})
)
# Insert the code
trace(gganimate:::ggplot_build.gganim, e, at = 31, print = FALSE)
## RENDER THE ANIMATION HERE
# ...
##
# Revert to the gganimate's version of the function
untrace(gganimate:::ggplot_build.gganim)
Thanks to G. Grothendieck on Stack Overflow for suggesting trace
: https://stackoverflow.com/a/79057552/1129889
When running the following code, I should get a smooth line starting from
x=.5
tracing tox=0
, monotonically increasing.The plain
ggplot
shows this clearly:However, the end of the resulting animation appears to be broken:
This may be related to https://github.com/thomasp85/gganimate/issues/486. However, I did try version 1.0.7 and the dev version (1.0.9.9) and they all seemed to show the issue, so I'm not sure.
Edited to remove second apparently unrelated issue