For scatter plot:
library(car)
library(rgl)
dat <- iris
KM <- kmeans(dat[, 1:4], centers = 3)
scatter3d(
x = dat$Sepal.Length,
y = dat$Sepal.Width,
z = dat$Petal.Length,
bg.col = c("white"),
ellipsoid.alpha = 0.2,
xlab = "Sepal.Length",
ylab = "Sepal.Width",
zlab = "Petal.Length",
surface.col = colorRampPalette(c("blue", "yellow", "red"))(length(levels(factor(KM$cluster)))),
groups = factor(KM$cluster),
grid = FALSE,
surface = FALSE,
ellipsoid = TRUE
)
aspect3d(1,1,1)
movie3d(
spin3d(axis = c(0, 1, 0)),
duration = 25,
convert = FALSE,
fps = 7,
movie = "Iris_Cluster",
dir = getwd()
)
To save the output into a file, ImageMagick needs to be installed first.
'rgl' package looks for convert.exe file in ImageMagick, so ensure to click the option to install legacy utilities when installing ImageMagick. (Note: the later updates to the packages might have fixed this issue, but older version of Windows could present issues along this line).
Note2: If you are on 32bit Windows, install 32bit ImageMagick.
movie3d(
spin3d(axis = c(0, 1, 0)),
duration = 25,
convert = TRUE,
fps = 7,
movie = "Iris_Cluster",
dir = getwd()
)
For bar/column chart:
library(lattice)
library(latticeExtra)
library(animation)
Dat <- aggregate(Sepal.Length~Species+Petal.Length, iris, mean)
RotPlot<-function(A){
for(i in A){
print(
cloud(Sepal.Length ~ Species + Petal.Length, Dat, panel.3d.cloud = panel.3dbars,
screen = list(z = i, x = -60),
col.facet=colorRampPalette(c("dodgerblue", "salmon"))(nrow(Dat)),
xbase = 0.4, ybase = 0.4, scales = list(arrows = FALSE, col = 1),
col = "white", par.settings = list(axis.line = list(col = "transparent"))
)
)
}
}
ROT<-seq(0,360,by=10)
saveGIF(RotPlot(ROT), interval = 0.5, movie.name = "Iris.gif",
ani.height = 640, ani.width = 640)