I am trying to add an animated scatter plot over a contour plot. However, the contour plot at the first frame just disappears after I hit Play. Is there a way to keep it during the whole animation? Below is the code.

I found this post dealing with the same issue and they had a solution, but it is in Python. I don’t know how to replicate the solution in R.

Thank you.

```
my.f <- function(x,y){
-sqrt((x-1)^2 + y^2)
}
f <- '-sqrt((x-1)^2 + y^2)'
iter <- data.frame(x=NA,y=NA,z=NA)
iter[1,c('x','y')] <- c(-2,2)
iter[1,]$z <- my.f(x=iter[1,1],y=iter[1,2])
change <- 1
i <- 1
while((abs(change) > .01) & (i < 50)){
der <- gradient(f = f,
var = c(x=iter[i,1],y=iter[i,2]))
i <- i + 1
iter[i,1:2] <- iter[i-1,1:2] + 0.1*der
iter[i,]$z <- my.f(x=iter[i,1],y=iter[i,2])
change <- iter[i,]$z - iter[i-1,]$z
cat('Iteration :', i, 'Value :', round(iter[i,]$z,4),'\n')
}
iter
iter$it <- 1:nrow(iter)
grid <- expand.grid(x=seq(-5,5,.1),y=seq(-5,5,.1))
grid$z <- -((grid[,1] - 1)^2 + grid[,2]^2)^.5
plot_ly(grid,
x = ~x,
y = ~y,
z = ~z,
type = 'contour',
colors = 'YlGnBu',
showscale=FALSE,
reversescale =T) %>%
add_trace(x = iter$x,
y = iter$y,
frame = iter$it,
type = 'scatter',
mode = 'markers',
marker = list(color = 'black',size=5),
showlegend=FALSE)
```