How to Plot 3D Scatter Diagram Using ggplot in R
Last Updated :
30 Aug, 2024
The ggplot2
package in R is one of the most popular tools for creating complex and aesthetically pleasing plots. However, ggplot2
is primarily designed for 2D plotting, which presents a challenge when it comes to creating 3D scatter plots. While ggplot2
does not natively support 3D plotting, it can be combined with other packages like plotly
or rgl
to create interactive 3D scatter plots.
This article will guide you through the process of creating a 3D scatter plot using ggplot2
and plotly
in R, along with theoretical concepts and practical examples.
Understanding 3D Scatter Plots
A 3D scatter plot displays points in a three-dimensional space, allowing you to visualize the relationship between three continuous variables. Each axis (x, y, z) represents one variable, and the points in the plot represent the observations.
Now we will discuss step-by-step implementation of How to Plot 3D Scatter Diagram Using ggplot using R Programming Language.
Step 1: Install and Load the Required Libraries
First, you need to install and load the ggplot2
and plotly
libraries:
R
# Install the required packages if not already installed
install.packages("ggplot2")
install.packages("plotly")
# Load the libraries
library(ggplot2)
library(plotly)
Step 2: Create a Sample Dataset
To demonstrate how to create a 3D scatter plot, let’s start by creating a sample dataset with three variables:
R
# Create a sample dataset
set.seed(123) # For reproducibility
data <- data.frame(
x = rnorm(100),
y = rnorm(100),
z = rnorm(100)
)
# Preview the dataset
head(data)
Output:
x y z
1 -0.56047565 -0.71040656 2.1988103
2 -0.23017749 0.25688371 1.3124130
3 1.55870831 -0.24669188 -0.2651451
4 0.07050839 -0.34754260 0.5431941
5 0.12928774 -0.95161857 -0.4143399
6 1.71506499 -0.04502772 -0.4762469
This dataset consists of 100 observations of three normally distributed variables: x
, y
, and z
.
Step 3: Create a Basic ggplot2
Scatter Plot
Start by creating a basic 2D scatter plot using ggplot2
:
R
# Create a basic 2D scatter plot with ggplot2
gg <- ggplot(data, aes(x = x, y = y, color = z)) +
geom_point(size = 3) +
labs(title = "2D Scatter Plot", x = "X Axis", y = "Y Axis", color = "Z Axis") +
theme_minimal()
# Display the plot
print(gg)
Output:
Plot 3D Scatter Diagram Using ggplotThis code creates a 2D scatter plot with x
and y
on the axes and z
represented by the color of the points. However, to visualize the third dimension effectively, we need to create a 3D plot.
Step 4: Convert to a 3D Scatter Plot with plotly
To create a 3D scatter plot, we can use the plotly
package, which allows interactive plotting and works well with ggplot2
:
R
# Convert the ggplot object to a plotly object for 3D plotting
p <- plot_ly(data, x = ~x, y = ~y, z = ~z, type = "scatter3d", mode = "markers",
marker = list(size = 3)) %>%
layout(title = "3D Scatter Plot",
scene = list(xaxis = list(title = "X Axis"),
yaxis = list(title = "Y Axis"),
zaxis = list(title = "Z Axis")))
# Display the 3D scatter plot
p
Output:
Plot 3D Scatter Diagram Using ggplotplot_ly
: This function from the plotly
package is used to create interactive plots. It takes data and maps the variables x
, y
, and z
to the axes of the 3D plot.type = "scatter3d"
: Specifies that the plot should be a 3D scatter plot.mode = "markers"
: Indicates that points (markers) should be used to represent the data.marker = list(size = 3)
: Sets the size of the markers.
Step 5: Customizing the 3D Plot
You can further customize the 3D scatter plot by adjusting the color, size, and shape of the points, as well as the appearance of the axes:
R
# Customizing the 3D scatter plot
p <- plot_ly(data, x = ~x, y = ~y, z = ~z, type = "scatter3d", mode = "markers",
marker = list(size = 5, color = ~z, colorscale = "Viridis", symbol = "circle")) %>%
layout(title = "Customized 3D Scatter Plot",
scene = list(xaxis = list(title = "X Axis"),
yaxis = list(title = "Y Axis"),
zaxis = list(title = "Z Axis",
backgroundcolor = "rgb(230, 230,230)",
gridcolor = "rgb(255, 255, 255)",
showbackground = TRUE)))
# Display the customized 3D scatter plot
p
Output:
Plot 3D Scatter Diagram Using ggplotcolorscale = "Viridis"
: Sets a color gradient for the z
variable, providing a visually appealing color scheme.symbol = "circle"
: Specifies the shape of the markers.backgroundcolor
and gridcolor
: Customize the appearance of the plot background and gridlines.
Conclusion
Although ggplot2
does not natively support 3D plots, combining it with plotly
allows you to create interactive and customizable 3D scatter plots in R. This guide provided a step-by-step approach to creating a 3D scatter plot, from setting up the environment to customizing the plot's appearance. With these tools, you can effectively visualize relationships between three continuous variables, enhancing your data analysis capabilities.
Similar Reads
How to save a plot using ggplot2 in R?
In this article, we are going to see how to save GGPlot in R Programming language. ggplot2 is a plotting package in R that is used to create complex plots from data specified in a data frame. It provides a more programmatic interface for specifying which variables to plot on to the graphical device,
3 min read
How to plot a subset of a dataframe using ggplot2 in R ?
In this article, we will discuss plotting a subset of a data frame using ggplot2 in the R programming language. Dataframe in use: AgeScoreEnrollNo117700521880103177915419752051885256199630717903581971409188345 To get a complete picture, let us first draw a complete data frame. Example: C/C++ Code #
8 min read
Comprehensive Guide to Scatter Plot using ggplot2 in R
In this article, we are going to see how to use scatter plots using ggplot2 in the R Programming Language. ggplot2 package is a free, open-source, and easy-to-use visualization package widely used in R. It is the most powerful visualization package written by Hadley Wickham. This package can be inst
7 min read
How to change the legend shape using ggplot2 in R?
In this article, we will discuss how to change only legend shape using ggplot2 in R programming language. Here ScatterPlot is used the same can be applied to any other plot. Syntax : sample(x, size, replace = TRUE) Parameters : x : either a vector of one or more values from which we want to choose t
3 min read
How to create a scatter plot using lattice package in R?
In this article, we will discuss how to create the scatter plots using lattice package in R programming language. In R programming, the Lattice package is a data visualization library that consists of various functions to plot different kinds of plots. Using the lattice library we can able to plot v
2 min read
How to plot a graph in R using CSV file ?
To plot a graph in R using a CSV file, we need a CSV file with two-column, the values in the first column will be considered as the points at the x-axis and the values in the second column will be considered as the points at the y-axis. In this article, we will be looking at the way to plot a graph
2 min read
How to change plot area margins using ggplot2 in R?
In the R programming language, ggplot2 is a popular library for creating data visualizations. One of the key benefits of using ggplot2 is the ability to customize the appearance of plots in a variety of ways. In this article, we will explore some of the ways you can customize the appearance of your
3 min read
Create a Scatter Plot with Multiple Groups using ggplot2 in R
In this article, we will discuss how to create a scatter plot with multiple groups in R Programming Language. Geoms can be added to the plot to compute various graphical representations of the data in the plot (points, lines, bars). The geom_point() method is used to create scatter plots in R. The g
2 min read
How To Make Scree Plot in R with ggplot2
In this article, we are going to see how can we plot a Scree plot in R Programming Language with ggplot2. Loading dataset: Here we will load the dataset, (Remember to drop the non-numerical column). Since the iris flower dataset contains a species column that is of character type so we need to drop
2 min read
How to Create a Scatter Plot In Excel?
A scatter plot in Excel is a powerful visualization tool for identifying trends, relationships, and patterns between two variables. By plotting data points on an Excel XY scatter plot, you can gain insights into correlations and outliers, making it an essential tool for data analysis. Whether youâre
7 min read