This post shows how to build a 3d scatterplot with R and the rgl package. It provides the reproducible code and makes it easy to apply it to your own dataset.
Building a 3d scatterplot requires a dataset
with 3 numeric variables, each being used on an axis. Here, the
famous iris dataset is used.
The rgl package comes with the
plot3d() function that is pretty close from the base R
plot() function. Instead of providing just an
x and a y argument, you also have to
provide the z coordinate.
Note that the output is interactive by default. If you have X11 or a
similar tool installed, you should be able to rotate the chart for a
better user experience. A few command line are also provided in case
you want to export the chart at .html,
.png or .Rmd format.
# library
library(rgl)
# This is to output a rgl plot in a rmarkdown document.
# setupKnitr()
# Data: the iris data is provided by R
data <- iris
# Add a new column with color
mycolors <- c('royalblue1', 'darkcyan', 'oldlace')
data$color <- mycolors[ as.numeric(data$Species) ]
# Plot
plot3d(
x=data$`Sepal.Length`, y=data$`Sepal.Width`, z=data$`Petal.Length`,
col = data$color,
type = 's',
radius = .1,
xlab="Sepal Length", ylab="Sepal Width", zlab="Petal Length")
# To display in an R Markdown document:
# rglwidget()
# To save to a file:
htmlwidgets::saveWidget(rglwidget(width = 520, height = 520),
file = "HtmlWidget/3dscatter.html",
libdir = "libs",
selfcontained = FALSE
)
👋 After crafting hundreds of R charts over 12 years, I've distilled my top 10 tips and tricks. Receive them via email! One insight per day for the next 10 days! 🔥