Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot 3D scatter diagram using ggplot?

I tried to use the plotly package, but it is not working in my case at all. The ggplot package is working for 2D plots but it is giving an error when adding one more axis. How to solve this issue?

ggplot(data,aes(x=D1,y=D2,z=D3,color=Sample)) +   geom_point() 

How to add one more axis and get the 3D plot in this?

like image 259
MrYelameli Avatar asked Jul 12 '17 08:07

MrYelameli


People also ask

Can Ggplot plot 3D?

Unfortunately, at the time of writing (April 2021), ggplot2 does not natively support 3d plots.

How do you make a 3D scatter plot?

After adding data, go to the 'Traces' section under the 'Structure' menu on the left-hand side. Choose the 'Type' of trace, then choose '3D Scatter' under '3D' chart type. Next, select 'X', 'Y' and 'Z' values from the dropdown menus. This will create a 3D scatter trace, as seen below.

Can you make 3D graphs in R?

R allows to build three dimensional charts, mainly thanks to the rgl package. Even if 3D is often a bad practice, it can be useful in specific situation.


2 Answers

Since you tagged your question with plotly and said that you've tried to use it with plotly, I think it would be helpful to give you a working code solution in plotly:

Creating some data to plot with:

set.seed(417) library(plotly) temp <- rnorm(100, mean=30, sd=5) pressure <- rnorm(100) dtime <- 1:100 

Graphing your 3d scatterplot using plotly's scatter3d type:

plot_ly(x=temp, y=pressure, z=dtime, type="scatter3d", mode="markers", color=temp) 

Renders the following: enter image description here

ggplot as others have note, by itself does not support 3d graphics rendering.

like image 174
onlyphantom Avatar answered Sep 24 '22 03:09

onlyphantom


A possible solutions is gg3D.

gg3D is a package created to extend ggplot2 to produce 3D plots. It does exactly what you are asking for: it adds a third axis to a ggplot. I find it quite good and easy to use and that is what I use for my limited needs.

An example taken from the vignette to produce a basic plot

devtools::install_github("AckerDWM/gg3D")  library("gg3D")  ## An empty plot with 3 axes qplot(x=0, y=0, z=0, geom="blank") +    theme_void() +   axes_3D() 

Empty 3D axes

## Axes can be populated with points using the function stat_3D.  data(iris) ggplot(iris, aes(x=Petal.Width, y=Sepal.Width, z=Petal.Length, color=Species)) +    theme_void() +   axes_3D() +   stat_3D() 

iris data

There are other options not involving ggplot. For example the excellent plot3D package with its extension plot3Drgl to plot in openGL.

like image 32
Marco Stamazza Avatar answered Sep 24 '22 03:09

Marco Stamazza