Scatterplot3d: 3D graphics - R software and data visualization - Easy Guides - Wiki (2024)

  • Install and load scaterplot3d
  • Prepare the data
  • The function scatterplot3d()
  • Basic 3D scatter plots
  • Change the main title and axis labels
  • Change the shape and the color of points
  • Change point shapes by groups
  • Change point colors by groups
  • Change the global appearance of the graph
    • Remove the box around the plot
    • Add grids on scatterplot3d
  • Add bars
  • Modification of scatterplot3d output
    • Add legends
      • Specify the legend position using xyz.convert()
      • Specify the legend position using keywords
      • Customize the legend position
    • Add point labels
    • Add regression plane and supplementary points
  • Infos

There are many packages in R (RGL, car, lattice, scatterplot3d, …) for creating 3D graphics.

This tutorial describes how to generate a scatter pot in the 3D space using R software and the package scatterplot3d.

scaterplot3d is very simple to use and it can be easily extended by adding supplementary points or regression planes into an already generated graphic.

It can be easily installed, as it requires only an installed version of R.

Scatterplot3d: 3D graphics - R software and data visualization - Easy Guides - Wiki (1)

install.packages("scatterplot3d") # Installlibrary("scatterplot3d") # load

The iris data set will be used:

data(iris)head(iris)
 Sepal.Length Sepal.Width Petal.Length Petal.Width Species1 5.1 3.5 1.4 0.2 setosa2 4.9 3.0 1.4 0.2 setosa3 4.7 3.2 1.3 0.2 setosa4 4.6 3.1 1.5 0.2 setosa5 5.0 3.6 1.4 0.2 setosa6 5.4 3.9 1.7 0.4 setosa

iris data set gives the measurements of the variables sepal length and width, petal length and width, respectively, for 50 flowers from each of 3 species of iris. The species are Iris setosa, versicolor, and virginica.

A simplified format is:

scatterplot3d(x, y=NULL, z=NULL)

x, y, z are the coordinates of points to be plotted. The arguments y and z can be optional depending on the structure of x.

In what cases, y and z are optional variables?

  • Case 1 : x is a formula of type zvar ~ xvar + yvar. xvar, yvar and zvar are used as x, y and z variables
  • Case 2 : x is a matrix containing at least 3 columns corresponding to x, y and z variables, respectively
# Basic 3d graphicsscatterplot3d(iris[,1:3])

Scatterplot3d: 3D graphics - R software and data visualization - Easy Guides - Wiki (2)

# Change the angle of point viewscatterplot3d(iris[,1:3], angle = 55)

Scatterplot3d: 3D graphics - R software and data visualization - Easy Guides - Wiki (3)

scatterplot3d(iris[,1:3], main="3D Scatter Plot", xlab = "Sepal Length (cm)", ylab = "Sepal Width (cm)", zlab = "Petal Length (cm)")

Scatterplot3d: 3D graphics - R software and data visualization - Easy Guides - Wiki (4)

shapes = c(16, 17, 18) shapes <- shapes[as.numeric(iris$Species)]scatterplot3d(iris[,1:3], pch = shapes)

Scatterplot3d: 3D graphics - R software and data visualization - Easy Guides - Wiki (6)

Read more on the different point shapes available in R : Point shapes in R

colors <- c("#999999", "#E69F00", "#56B4E9")colors <- colors[as.numeric(iris$Species)]scatterplot3d(iris[,1:3], pch = 16, color=colors)

Scatterplot3d: 3D graphics - R software and data visualization - Easy Guides - Wiki (7)

Read more about colors in R: colors in R

The arguments below can be used:

  • grid: a logical value. If TRUE, a grid is drawn on the plot.
  • box: a logical value. If TRUE, a box is drawn around the plot

Remove the box around the plot

scatterplot3d(iris[,1:3], pch = 16, color = colors, grid=TRUE, box=FALSE)

Scatterplot3d: 3D graphics - R software and data visualization - Easy Guides - Wiki (8)

Note that, the argument grid = TRUE plots only the grid on the xy plane. In the next section, we’ll see how to add grids on the other facets of the 3D scatter plot.

Add grids on scatterplot3d

This section describes how to add xy-, xz- and yz- to scatterplot3d graphics.

We’ll use a custom function named addgrids3d(). The source code is available here : addgrids3d.r. The function is inspired from the discussion on this forum.

A simplified format of the function is:

addgrids3d(x, y=NULL, z=NULL, grid = TRUE, col.grid = "grey", lty.grid=par("lty"))

  • x, y, and z are numeric vectors specifying the x, y, z coordinates of points. x can be a matrix or a data frame containing 3 columns corresponding to the x, y and z coordinates. In this case the arguments y and z are optional
  • grid specifies the facet(s) of the plot on which grids should be drawn. Possible values are the combination of “xy”, “xz” or “yz”. Example: grid = c(“xy”, “yz”). The default value is TRUE to add grids only on xy facet.
  • col.grid, lty.grid: the color and the line type to be used for grids

Add grids on the different factes of scatterplot3d graphics:

# 1. Source the functionsource('http://www.sthda.com/sthda/RDoc/functions/addgrids3d.r')# 2. 3D scatter plotscatterplot3d(iris[, 1:3], pch = 16, grid=FALSE, box=FALSE)# 3. Add gridsaddgrids3d(iris[, 1:3], grid = c("xy", "xz", "yz"))

Scatterplot3d: 3D graphics - R software and data visualization - Easy Guides - Wiki (9)

The problem on the above plot is that the grids are drawn over the points.

The R code below, we’ll put the points in the foreground using the following steps:

  1. An empty scatterplot3 graphic is created and the result of scatterplot3d() is assigned to s3d
  2. The function addgrids3d() is used to add grids
  3. Finally, the function s3d$points3d is used to add points on the 3D scatter plot
# 1. Source the functionsource('~/hubiC/Documents/R/function/addgrids3d.r')# 2. Empty 3D scatter plot using pch=""s3d <- scatterplot3d(iris[, 1:3], pch = "", grid=FALSE, box=FALSE)# 3. Add gridsaddgrids3d(iris[, 1:3], grid = c("xy", "xz", "yz"))# 4. Add pointss3d$points3d(iris[, 1:3], pch = 16)

Scatterplot3d: 3D graphics - R software and data visualization - Easy Guides - Wiki (10)

The function points3d() is described in the next sections.

The argument type = “h” is used. This is useful to see very clearly the x-y location of points.

scatterplot3d(iris[,1:3], pch = 16, type="h", color=colors)

Scatterplot3d: 3D graphics - R software and data visualization - Easy Guides - Wiki (11)

scatterplot3d returns a list of function closures which can be used to add elements on a existing plot.

The returned functions are :

  • xyz.convert(): to convert 3D coordinates to the 2D parallel projection of the existing scatterplot3d. It can be used to add arbitrary elements, such as legend, into the plot.
  • points3d(): to add points or lines into the existing plot
  • plane3d(): to add a plane into the existing plot
  • box3d(): to add or refresh a box around the plot

Add legends

Specify the legend position using xyz.convert()

  1. The result of scatterplot3d() is assigned to s3d
  2. The function s3d$xyz.convert() is used to specify the coordinates for legends
  3. the function legend() is used to add legends to plots
s3d <- scatterplot3d(iris[,1:3], pch = 16, color=colors)legend(s3d$xyz.convert(7.5, 3, 4.5), legend = levels(iris$Species), col = c("#999999", "#E69F00", "#56B4E9"), pch = 16)

Scatterplot3d: 3D graphics - R software and data visualization - Easy Guides - Wiki (12)


It’s also possible to specify the position of legends using the following keywords: “bottomright”, “bottom”, “bottomleft”, “left”, “topleft”, “top”, “topright”, “right” and “center”.

Read more about legend in R: legend in R.

Specify the legend position using keywords

# "right" positions3d <- scatterplot3d(iris[,1:3], pch = 16, color=colors)legend("right", legend = levels(iris$Species), col = c("#999999", "#E69F00", "#56B4E9"), pch = 16)

Scatterplot3d: 3D graphics - R software and data visualization - Easy Guides - Wiki (13)

# Use the argument insets3d <- scatterplot3d(iris[,1:3], pch = 16, color=colors)legend("right", legend = levels(iris$Species), col = c("#999999", "#E69F00", "#56B4E9"), pch = 16, inset = 0.1)

Scatterplot3d: 3D graphics - R software and data visualization - Easy Guides - Wiki (14)

What means the argument inset in the R code above?

The argument inset is used to inset distance(s) from the margins as a fraction of the plot region when legend is positioned by keyword. ( see ?legend from R). You can play with inset argument using negative or positive values.

# "bottom" positions3d <- scatterplot3d(iris[,1:3], pch = 16, color=colors)legend("bottom", legend = levels(iris$Species), col = c("#999999", "#E69F00", "#56B4E9"), pch = 16)

Scatterplot3d: 3D graphics - R software and data visualization - Easy Guides - Wiki (15)

Using keywords to specify the legend position is very simple. However, sometimes, there is an overlap between some points and the legend box or between the axis and legend box.

Is there any solution to avoid this overlap?

Yes, there are several solutions using the combination of the following arguments for the function legend():

  • bty = “n” : to remove the box around the legend. In this case the background color of the legend becomes transparent and the overlapping points become visible.
  • bg = “transparent”: to change the background color of the legend box to transparent color (this is only possible when bty != “n”).
  • inset: to modify the distance(s) between plot margins and the legend box.
  • horiz: a logical value; if TRUE, set the legend horizontally rather than vertically
  • xpd: a logical value; if TRUE, it enables the legend items to be drawn outside the plot.

Customize the legend position

# Custom point shapess3d <- scatterplot3d(iris[,1:3], pch = shapes)legend("bottom", legend = levels(iris$Species), pch = c(16, 17, 18), inset = -0.25, xpd = TRUE, horiz = TRUE)

Scatterplot3d: 3D graphics - R software and data visualization - Easy Guides - Wiki (16)

# Custom colorss3d <- scatterplot3d(iris[,1:3], pch = 16, color=colors)legend("bottom", legend = levels(iris$Species), col = c("#999999", "#E69F00", "#56B4E9"), pch = 16, inset = -0.25, xpd = TRUE, horiz = TRUE)

Scatterplot3d: 3D graphics - R software and data visualization - Easy Guides - Wiki (17)

# Custom shapes/colorss3d <- scatterplot3d(iris[,1:3], pch = shapes, color=colors)legend("bottom", legend = levels(iris$Species), col = c("#999999", "#E69F00", "#56B4E9"), pch = c(16, 17, 18), inset = -0.25, xpd = TRUE, horiz = TRUE)

Scatterplot3d: 3D graphics - R software and data visualization - Easy Guides - Wiki (18)

In the R code above, you can play with the arguments inset, xpd and horiz to see the effects on the appearance of the legend box.

Add point labels

The function text() is used as follow:

scatterplot3d(iris[,1:3], pch = 16, color=colors)text(s3d$xyz.convert(iris[, 1:3]), labels = rownames(iris), cex= 0.7, col = "steelblue")

Scatterplot3d: 3D graphics - R software and data visualization - Easy Guides - Wiki (19)

Add regression plane and supplementary points

  1. The result of scatterplot3d() is assigned to s3d
  2. A linear model is calculated as follow : lm(zvar ~ xvar + yvar). Assumption : zvar depends on xvar and yvar
  3. The function s3d$plane3d() is used to add the regression plane
  4. Supplementary points are added using the function s3d$points3d()

The data sets trees will be used:

data(trees)head(trees)
 Girth Height Volume1 8.3 70 10.32 8.6 65 10.33 8.8 63 10.24 10.5 72 16.45 10.7 81 18.86 10.8 83 19.7

This data set provides measurements of the girth, height and volume for black cherry trees.

3D scatter plot with the regression plane:

# 3D scatter plots3d <- scatterplot3d(trees, type = "h", color = "blue", angle=55, pch = 16)# Add regression planemy.lm <- lm(trees$Volume ~ trees$Girth + trees$Height)s3d$plane3d(my.lm)# Add supplementary pointss3d$points3d(seq(10, 20, 2), seq(85, 60, -5), seq(60, 10, -10), col = "red", type = "h", pch = 8)

Scatterplot3d: 3D graphics - R software and data visualization - Easy Guides - Wiki (20)

This analysis has been performed using R software (ver. 3.1.2) and scatterplot3d (ver. 0.3-35)

Scatterplot3d: 3D graphics - R software and data visualization - Easy Guides - Wiki (2024)

FAQs

What is the function of scatter3D in R? ›

The scatter3D() function of the plot3D graphics library in R creates nice three dimensional scatter plots. boxes for 3 options bty = "g", "b2","bl" axes -----> Boolean value of TRUE draws the axes. label -----> A value of TRUE enables the label for axes.

How to make a 3D scatter plot in R? ›

You can also create an interactive 3D scatterplot using the plot3D(x , y , z) function in the rgl package. It creates a spinning 3D scatterplot that can be rotated with the mouse. The first three arguments are the x , y , and z numeric vectors representing points.

How to install scatterplot3d package in RStudio? ›

It can be easily installed, as it requires only an installed version of R.
  1. Install and load scaterplot3d. ...
  2. Prepare the data. ...
  3. The function scatterplot3d() ...
  4. Basic 3D scatter plots. ...
  5. Change the main title and axis labels. ...
  6. Change the shape and the color of points. ...
  7. Change point shapes by groups. ...
  8. Change point colors by groups.

When to use a 3D scatter plot? ›

3D scatter plots are used to plot data points on three axes in the attempt to show the relationship between three variables. Each row in the data table is represented by a marker whose position depends on its values in the columns set on the X, Y, and Z axes.

What is the size of scatter3d? ›

scatter3d(x,y,z) creates a scatter plot with markers at the locations specified by x , y , and z . The default type of the marker is a circle, the default color is "blue" and the default marker size is 36. This means the circle surrounding the marker has an area of 36 points squared.

What is scatter map 3D? ›

A type of scatter plot that shows the relationship between three variables. Plotly2_demo's interactive graph and data of "Helix Curve using 3D Scatter" is a scatter3d. The x-axis shows values from 0 to 0. The y-axis shows values from 0 to 0.

Which method is used to create a scatter plot in R? ›

A scatter plot can be created using the function plot(x, y). The function lm() will be used to fit linear models between y and x.

What is the function of a scatter plot? ›

Scatter plots' primary uses are to observe and show relationships between two numeric variables. The dots in a scatter plot not only report the values of individual data points, but also patterns when the data are taken as a whole. Identification of correlational relationships are common with scatter plots.

How to plot 3D surface in R? ›

Creating 3D Plots in R Programming – persp() Function. 3D plot in R Language is used to add title, change viewing direction, and add color and shade to the plot. The persp() function which is used to create 3D surfaces in perspective view. This function will draw perspective plots of a surface over the x–y plane.

How to install R packages on Windows? ›

Installing R on Windows OS
  1. Go to the CRAN website.
  2. Click on "Download R for Windows".
  3. Click on "install R for the first time" link to download the R executable (.exe) file.
  4. Run the R executable file to start installation, and allow the app to make changes to your device.
  5. Select the installation language.
Feb 7, 2022

How to install data packages in R? ›

In R, you can easily install and load additional packages provided by other users. or click Tools > Install packages. Write the package name in the dialog, then click install. Once you install the package, you need to load it so that it becomes available to use.

When to use 3D data visualization? ›

Generally, 2D visualizations are more effective for data that has one or two variables, such as bar charts, line charts, or scatter plots. 3D visualizations can be useful for data that has three or more variables, such as surface plots, volume plots, or network graphs.

When not to use a scatter graph? ›

Too little or too much: Try not to use a scatter plot when you either have very few data points, or a large number of data points.

What is the function of Knitr in R? ›

Description. This function takes an input file, extracts the R code in it according to a list of patterns, evaluates the code and writes the output in another file. It can also tangle R source code from the input document ( purl() is a wrapper to knit(..., tangle = TRUE) ). The knitr.

What is the function GPAR in R? ›

Description. gpar() should be used to create a set of graphical parameter settings. It returns an object of class "gpar" . This is basically a list of name-value pairs.

What is the function of Webshot in R? ›

Webshot makes it easy to take screenshots of web pages from R. It can also: Run Shiny applications locally and take screenshots of the application. Render R Markdown documents and take screenshots of the document.

What is the function Mean_sd in R? ›

mean_sd returns a vector with two values (mean and standard deviation) of x . mean_pm_sd returns a vector with 3 values: mean - 1 sd, mean, mean + 1 sd.

References

Top Articles
Pressure mounts on Secret Service; agency had denied requests for extra Trump security
Altius Dispensary Promo Code
Cranes For Sale in United States| IronPlanet
Pnct Terminal Camera
Voorraad - Foodtrailers
Black Gelato Strain Allbud
Geometry Escape Challenge A Answer Key
Anki Fsrs
Sitcoms Online Message Board
Missing 2023 Showtimes Near Landmark Cinemas Peoria
Sport Clip Hours
Jack Daniels Pop Tarts
Lenscrafters Huebner Oaks
Chile Crunch Original
24 Hour Walmart Detroit Mi
Cvb Location Code Lookup
Dr Manish Patel Mooresville Nc
Letter F Logos - 178+ Best Letter F Logo Ideas. Free Letter F Logo Maker. | 99designs
Commodore Beach Club Live Cam
Dumb Money, la recensione: Paul Dano e quel film biografico sul caso GameStop
Troy Bilt Mower Carburetor Diagram
How do I get into solitude sewers Restoring Order? - Gamers Wiki
List of all the Castle's Secret Stars - Super Mario 64 Guide - IGN
Edicts Of The Prime Designate
Cta Bus Tracker 77
Palm Springs Ca Craigslist
Gopher Hockey Forum
Breckie Hill Mega Link
Today Was A Good Day With Lyrics
Morse Road Bmv Hours
Village
Slim Thug’s Wealth and Wellness: A Journey Beyond Music
Dark Entreaty Ffxiv
Sams Gas Price Sanford Fl
Cosas Aesthetic Para Decorar Tu Cuarto Para Imprimir
Kqelwaob
Progressbook Newark
Stouffville Tribune (Stouffville, ON), March 27, 1947, p. 1
Donald Trump Assassination Gold Coin JD Vance USA Flag President FIGHT CIA FBI • $11.73
Capital Hall 6 Base Layout
Strange World Showtimes Near Atlas Cinemas Great Lakes Stadium 16
Black Adam Showtimes Near Amc Deptford 8
Craiglist Hollywood
Umiami Sorority Rankings
Sand Castle Parents Guide
Courses In Touch
Eat Like A King Who's On A Budget Copypasta
Aznchikz
The 13 best home gym equipment and machines of 2023
Lux Funeral New Braunfels
Costco Gas Price Fort Lauderdale
Thrift Stores In Burlingame Ca
Latest Posts
Article information

Author: Clemencia Bogisich Ret

Last Updated:

Views: 5999

Rating: 5 / 5 (60 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Clemencia Bogisich Ret

Birthday: 2001-07-17

Address: Suite 794 53887 Geri Spring, West Cristentown, KY 54855

Phone: +5934435460663

Job: Central Hospitality Director

Hobby: Yoga, Electronics, Rafting, Lockpicking, Inline skating, Puzzles, scrapbook

Introduction: My name is Clemencia Bogisich Ret, I am a super, outstanding, graceful, friendly, vast, comfortable, agreeable person who loves writing and wants to share my knowledge and understanding with you.