Creating three-dimensional scatter plots

In this recipe, we will learn how to create three-dimensional scatter plots that can be very useful when we want to explore the relationships between more than two variables at a time.

Getting ready

We need to install and load the scatterplot3d package in order to run this recipe:

install.packages("scatterplot3d")
library(scatterplot3d)

How to do it...

Let's create the simplest default three-dimensional-scatter plot with our mtcars dataset:

scatterplot3d(x=mtcars$wt,
              y=mtcars$disp,
              z=mtcars$mpg)
How to do it...

How it works...

That was easy! The scatterplot3d() functions much like the basic plot() function. In the preceding example, all we had to provide was wt, disp, and mpg from the mtcars dataset as the x, y, and z arguments, respectively.

There's more...

Just like plot() and other graph functions, scatterplot3d() accepts a number of additional arguments using which we can configure the graph in many ways. Let's try some of these additional settings.

Let's add a title to the graph, change the plotting symbol and the angle of viewing, add highlighting, and add vertical drop lines to the x-y plane:

scatterplot3d(mtcars$wt,mtcars$disp,mtcars$mpg, 
pch=16, highlight.3d=TRUE, angle=20,
xlab="Weight",ylab="Displacement",zlab="Fuel Economy (mpg)",
type="h", 
main="Relationships between car specifications")
There's more...

As you can see, we changed some of the graph settings using arguments we used in the plot() function previously. These include the axis titles, graph title, and symbol type. In addition, we added some color highlighting by setting the highlight.3d argument to TRUE, which draws the points in different colors related to the y coordinates (disp). The angle argument is used to set the angle between the x and y axes, which controls the point from which we view the data. Finally, setting type to h adds the vertical lines to the x-y plane, which makes reading the graph easier.

For more advanced three-dimensional data visualization in R, please have a look at the rggobi package, which allows interactive analysis with 3D plots. The package can be installed like any other R package:

install.packages("rggobi")

Please refer to the package's website for more details: http://www.ggobi.org/rggobi/.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.107.147