I am working on a study comparing differential evolution and particle swarm optimization performance, and I need to be able to add population points onto a 3D plot. I have reviewed Adding points to 3d plot in r, but that solution does not seem to work in my case, and I cannot figure out why. I am taking the well-known G2 function and using persp3D() as follows:
G2 <- function(x) {
if (x[1] >= 0 & x[1] <= 10 & x[2] >= 0 & x[2] <= 10 &
x[1] * x[2] >= 0.75 & x[1] + x[2] <= 15) {
s <- cos(x[1]) ^ 4 + cos(x[2]) ^ 4
p <- 2 * cos(x[1]) ^ 2 * cos(x[2]) ^ 2
r <- sqrt(x[1] ^ 2 + 2 * x[2] ^ 2)
f <- -abs((s - p) / r)
} else {
f <- 0
}
return(f)
}
x = y = seq(0, 10, .1)
data = data.frame(matrix(nrow = length(x), ncol = length(y)))
names(data) = y
rownames(data) = x
#Fill in data.frame with G2 values
for (i in 1:length(x)) {
for (j in 1:length(y)) {
z = G2(c(x[i], y[j]))
data[i,j] = z
}
}
zlim = -range(data)
z = as.matrix(data)
par(mfrow = c(1, 1))
windows()
library(plot3D)
persp3D(z = -z, xlab = "x1", bty = "bl2",
ylab = "x2", zlab = "G2", clab = "depth of G2",
expand = 0.5, d = 2, phi = 20, theta = 30, resfac = 2,
image = TRUE,
contour = list(col = "grey", side = c("zmin", "z")),
zlim = zlim, colkey = list(side = 1, length = 0.5))
All of this works well, and I get the plot I am looking for. However, when I try to add points, as suggested in the solution referenced above, my 3D plot is regenerated as a plot of just the one red point:
points3D(1, 1, G2(c(1,1)), col = "red", size = 30)
How do I simply add this point to the existing persp3D() plot? Also, can I control where the point is added (meaning to the contour plot or on the 3D image? My intention is to add populations as the algorithms evolve, and create GIFs for easy visualization, but I do not want to get off point, so I am simplifying by just trying to add this one point to the plot. Thank you for any help!