<?xml version="1.0" encoding="UTF-8" ?>
<!-- RSS generated by PHPBoost on Sat, 09 May 2026 09:46:18 +0200 -->

<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
	<channel>
		<title><![CDATA[Easy Guides]]></title>
		<atom:link href="https://www.sthda.com/english/syndication/rss/wiki/33" rel="self" type="application/rss+xml"/>
		<link>https://www.sthda.com</link>
		<description><![CDATA[Last articles of the category: 3D graphics]]></description>
		<copyright>(C) 2005-2026 PHPBoost</copyright>
		<language>en</language>
		<generator>PHPBoost</generator>
		
		
		<item>
			<title><![CDATA[3D graphics]]></title>
			<link>https://www.sthda.com/english/wiki/3d-graphics</link>
			<guid>https://www.sthda.com/english/wiki/3d-graphics</guid>
			<description><![CDATA[<!-- START HTML -->

            
  <!--====================== start from here when you copy to sthda================-->  
  <div id="rdoc">


<p><br/></p>
<p>Previously, we described the <a href="https://www.sthda.com/english/english/wiki/r-basics-quick-and-easy">essentials of R programming</a> and provided quick start guides for <a href="https://www.sthda.com/english/english/wiki/importing-data-into-r">importing data</a> into <strong>R</strong> as well as visualizing data using <a href="https://www.sthda.com/english/english/wiki/r-base-graphs">R base graphs</a>.</p>
<br/>
<div class="block">
This chapter describes how to create static and interactive three-dimension (<strong>3D</strong>) <strong>graphs</strong>. We provide also an R package named graph3d to easily build and customize, step by step, 3D graphs in R software.
</div>
<p><br/></p>
<div id="how-this-chapter-is-organized" class="section level1">
<h1>How this chapter is organized?</h1>
<br/>
<div class="block">
<ul>
<li>Static 3D Scatter Plots
<ul>
<li><a href="https://www.sthda.com/english/english/wiki/scatterplot3d-3d-graphics-r-software-and-data-visualization">Simple 3D Scatter Plots: scatterplot3d Package</a></li>
<li><a href="https://www.sthda.com/english/english/wiki/impressive-package-for-3d-and-4d-graph-r-software-and-data-visualization">Advanced 3D Graphs: plot3D Package</a></li>
</ul></li>
<li>Interactive 3D Graphs
<ul>
<li><a href="https://www.sthda.com/english/english/wiki/amazing-interactive-3d-scatter-plots-r-software-and-data-visualization">Interactive 3D Scatter Plots</a></li>
<li><a href="https://www.sthda.com/english/english/wiki/a-complete-guide-to-3d-visualization-device-system-in-r-r-software-and-data-visualization">Guide to RGL 3D Visualization System</a></li>
</ul></li>
</ul>
</div>
<p><br/></p>
<hr/>
</div>
<div id="simple-3d-scatter-plots-scatterplot3d-package" class="section level1">
<h1>Simple 3D Scatter Plots: scatterplot3d Package</h1>
<ul>
<li>Install and load scaterplot3d</li>
<li>Prepare the data</li>
<li>The function scatterplot3d()</li>
<li>Basic 3D scatter plots</li>
<li>Change the main title and axis labels</li>
<li>Change the shape and the color of points</li>
<li>Change point shapes by groups</li>
<li>Change point colors by groups</li>
<li>Change the global appearance of the graph
<ul>
<li>Remove the box around the plot</li>
<li>Add grids on scatterplot3d</li>
</ul></li>
<li>Add bars</li>
<li>Modification of scatterplot3d output
<ul>
<li>Add legends</li>
<li>Add point labels</li>
<li>Add regression plane and supplementary points</li>
</ul></li>
</ul>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/3d-graphics-scatterplot3d-1.png" width="480" style="margin-bottom:10px;" /></p>
<p><span class="success">Read more: —> <a href="https://www.sthda.com/english/english/wiki/scatterplot3d-3d-graphics-r-software-and-data-visualization">Simple 3D Scatter Plots: scatterplot3d Package</a>.</span></p>
</div>
<div id="advanced-3d-graphs-plot3d-package" class="section level1">
<h1>Advanced 3D Graphs: plot3D Package</h1>
<ul>
<li>Install and load plot3D package</li>
<li>Prepare the data</li>
<li>Scatter plots
<ul>
<li>Basic scatter plot</li>
<li>Change the type of the box around the plot</li>
<li>Change the color by groups</li>
<li>Change the position of the legend</li>
<li>3D viewing direction</li>
<li>Titles and axis labels</li>
<li>Tick marks and labels</li>
<li>Add points and text to an existing plot</li>
</ul></li>
<li>Line plots
<ul>
<li>Add confidence interval</li>
<li>3D fancy Scatter plot with small dots on basal plane</li>
<li>Regression plane</li>
</ul></li>
<li>text3D: plot 3-dimensionnal texts</li>
<li>text3D and scatter3D</li>
<li>3D Histogram</li>
<li>scatter2D: 2D scatter plot</li>
<li>text2D</li>
<li>Interactive plot</li>
</ul>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/3d-graphics-scatter-plot-3d-text-r-data-visualization-1.png" width="480" style="margin-bottom:10px;" /></p>
<p><span class="success">Read more: —> <a href="https://www.sthda.com/english/english/wiki/impressive-package-for-3d-and-4d-graph-r-software-and-data-visualization">Advanced 3D Graphs: plot3D Package</a>.</span></p>
</div>
<div id="interactive-3d-scatter-plots" class="section level1">
<h1>Interactive 3D Scatter Plots</h1>
<ul>
<li>Install and load required packages</li>
<li>Prepare the data</li>
<li>The function scatter3d</li>
<li>Basic 3D scatter plots</li>
<li>Plot the points by groups
<ul>
<li>Default plot</li>
<li>Remove the surfaces</li>
<li>Add concentration ellipsoids</li>
<li>Change point colors by groups</li>
</ul></li>
<li>Axes
<ul>
<li>Change axis labels</li>
<li>Remove axis scales</li>
<li>Change axis colors</li>
</ul></li>
<li>Add text labels for the points</li>
<li>Export images</li>
</ul>
<div class="figure">
<img src="https://www.sthda.com/english/sthda/RDoc/images/rgl-scatter3d.gif" alt="3d scatter plot rgl" /><p class="caption">3d scatter plot rgl</p>
</div>
<p><span class="success">Read more: —> <a href="https://www.sthda.com/english/english/wiki/amazing-interactive-3d-scatter-plots-r-software-and-data-visualization">Interactive 3D Scatter Plots</a>.</span></p>
</div>
<div id="guide-to-rgl-3d-visualization-system" class="section level1">
<h1>Guide to RGL 3D Visualization System</h1>
<ul>
<li>Install the RGL package</li>
<li>Load the RGL package</li>
<li>Prepare the data</li>
<li>Start and close RGL device</li>
<li>3D scatter plot
<ul>
<li>Basic graph</li>
<li>Change the background and point colors</li>
<li>Change the shape of points</li>
</ul></li>
<li>rgl_init(): A custom function to initialize RGL device</li>
<li>Add a bounding box decoration</li>
<li>Add axis lines and labels</li>
<li>Set the aspect ratios of the x, y and z axes</li>
<li>Change the color of points by groups</li>
<li>Change the shape of points</li>
<li>Add an ellipse of concentration</li>
<li>Regression plane</li>
<li>Create a movie of RGL scene</li>
<li>Export images as png or pdf</li>
<li>Export the plot into an interactive HTML file</li>
<li>Select a rectangle in an RGL scene</li>
<li>Identify points in a plot</li>
<li>R3D Interface</li>
<li>RGL functions
<ul>
<li>Device management</li>
<li>Shape functions</li>
<li>Scene management</li>
<li>Setup the environment</li>
<li>Appearance setup</li>
<li>Export screenshot</li>
<li>Assign focus to an RGL window</li>
</ul></li>
</ul>
<div class="figure">
<img src="https://www.sthda.com/english/sthda/RDoc/images/rgl-movie3d.gif" alt="RGL movie 3d" /><p class="caption">RGL movie 3d</p>
</div>
<p><span class="success">Read more —> <a href="https://www.sthda.com/english/english/wiki/a-complete-guide-to-3d-visualization-device-system-in-r-r-software-and-data-visualization">Guide to RGL 3D Visualization System</a>.</span></p>
</div>
<div id="see-also" class="section level1">
<h1>See also</h1>
<ul>
<li><a href="https://www.sthda.com/english/english/wiki/r-base-graphs">R Base Graphs</a></li>
<li><a href="https://www.sthda.com/english/english/wiki/lattice-graphs">Lattice Graphs</a></li>
<li><a href="https://www.sthda.com/english/english/wiki/ggplot2-essentials">ggplot2 Graphs</a></li>
<li><a href="https://www.sthda.com/english/english/wiki/the-elements-of-choosing-colors-for-great-data-visualization-in-r">The Elements of Choosing Colors for Great Data Visualization in R</a></li>
</ul>
</div>
<div id="infos" class="section level1">
<h1>Infos</h1>
<p><span class="warning"> This analysis has been performed using <strong>R statistical software</strong> (ver. 3.2.4). </span></p>
</div>

<script>jQuery(document).ready(function () {
    jQuery('#rdoc h1').addClass('wiki_paragraph1');
    jQuery('#rdoc h2').addClass('wiki_paragraph2');
    jQuery('#rdoc h3').addClass('wiki_paragraph3');
    jQuery('#rdoc h4').addClass('wiki_paragraph4');
    });//add phpboost class to header</script>
<style>.content{padding:0px;}</style>
</div><!--end rdoc-->
<!--====================== stop here when you copy to sthda================-->


<!-- END HTML -->]]></description>
			<pubDate>Tue, 12 Jul 2016 07:26:04 +0200</pubDate>
			
		</item>
		
		<item>
			<title><![CDATA[Impressive package for 3D and 4D graph - R software and data visualization]]></title>
			<link>https://www.sthda.com/english/wiki/impressive-package-for-3d-and-4d-graph-r-software-and-data-visualization</link>
			<guid>https://www.sthda.com/english/wiki/impressive-package-for-3d-and-4d-graph-r-software-and-data-visualization</guid>
			<description><![CDATA[<!-- START HTML -->

  <!--====================== start from here when you copy to sthda================-->  
  <div id="rdoc">



<div id="TOC">
<ul>
<li><a href="#install-plot3d-package">Install plot3D package</a></li>
<li><a href="#load-plot3d-package">Load plot3D package</a></li>
<li><a href="#prepare-the-data">Prepare the data</a></li>
<li><a href="#scatter-plots">Scatter plots</a><ul>
<li><a href="#functions-for-scatter-plots-and-texts-in-2d-and-3d">Functions for scatter plots and texts in 2D and 3D</a></li>
<li><a href="#basic-scatter-plot">Basic scatter plot</a></li>
<li><a href="#change-the-type-of-the-box-around-the-plot">Change the type of the box around the plot</a></li>
<li><a href="#color-palettes">Color palettes</a></li>
<li><a href="#change-the-color-by-groups">Change the color by groups</a></li>
<li><a href="#change-the-position-of-the-legend">Change the position of the legend</a></li>
<li><a href="#d-viewing-direction">3D viewing direction</a></li>
<li><a href="#titles-and-axis-labels">Titles and axis labels</a></li>
<li><a href="#tick-marks-and-labels">Tick marks and labels</a></li>
<li><a href="#add-points-and-text-to-an-existing-plot">Add points and text to an existing plot</a></li>
</ul></li>
<li><a href="#line-plots">Line plots</a><ul>
<li><a href="#add-confidence-interval">Add confidence interval</a></li>
<li><a href="#d-fancy-scatter-plot-with-small-dots-on-basal-plane">3D fancy Scatter plot with small dots on basal plane</a></li>
<li><a href="#regression-plane">Regression plane</a></li>
</ul></li>
<li><a href="#text3d-plot-3-dimensionnal-texts">text3D: plot 3-dimensionnal texts</a></li>
<li><a href="#text3d-and-scatter3d">text3D and scatter3D</a></li>
<li><a href="#d-histogram">3D Histogram</a></li>
<li><a href="#scatter2d-2d-scatter-plot">scatter2D: 2D scatter plot</a></li>
<li><a href="#text2d">text2D</a></li>
<li><a href="#other-functions">Other functions</a></li>
<li><a href="#interactive-plot">Interactive plot</a></li>
<li><a href="#infos">Infos</a></li>
</ul>
</div>

<p><br/></p>
<p>In my previous articles, I already described how to make <strong>3D graphs</strong> in R using the package below:</p>
<ul>
<li><a href="https://www.sthda.com/english/english/wiki/scatterplot3d-3d-graphics-r-software-and-data-visualization">scatterplot3d</a>, non interactive</li>
<li><a href="https://www.sthda.com/english/english/wiki/amazing-interactive-3d-scatter-plots-r-software-and-data-visualization">scatter3d</a>, interactive</li>
<li><a href="https://www.sthda.com/english/english/wiki/a-complete-guide-to-3d-visualization-device-system-in-r-r-software-and-data-visualization">rgl</a>, interactive</li>
</ul>
<p>To close the discussion about 3D, in this tutorial I’ll describe the impressive <strong>plot3D</strong> package and its extension <strong>plot3Drgl</strong> package.</p>
<p><strong>plot3D</strong>, from Karline Soetaert, is an R package containing many functions for 2D and 3D plotting: <em>scatter3D</em>, <em>points3D</em>, <em>lines3D</em>,<em>text3D</em>, <em>ribbon3d</em>, <em>hist3D</em>, etc.</p>
<p>In addition to the x, y (and z) values, an <strong>additional data dimension</strong> can be represented by a color variable (argument <em>colvar</em>).</p>
<p>This <strong>“4D”</strong> plot (x, y, z, color) with a color legend is not (easily) possible using the packages mentioned above (scatterplot3d, scatter3d, rgl).</p>
<p>The package <strong>plot3Drgl</strong> allows to plot easily the graph generated with plot3D in openGL, as made available by package rgl. This is described at the end of the present article.</p>
<div id="install-plot3d-package" class="section level1">
<h1>Install plot3D package</h1>
<pre class="r"><code>install.packages("plot3D")</code></pre>
</div>
<div id="load-plot3d-package" class="section level1">
<h1>Load plot3D package</h1>
<pre class="r"><code>library("plot3D")</code></pre>
</div>
<div id="prepare-the-data" class="section level1">
<h1>Prepare the data</h1>
<p>We’ll use the <em>iris</em> data set in the following examples :</p>
<pre class="r"><code>data(iris)
head(iris)</code></pre>
<pre><code>  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa</code></pre>
<pre class="r"><code># x, y and z coordinates
x <- sep.l <- iris$Sepal.Length
y <- pet.l <- iris$Petal.Length
z <- sep.w <- iris$Sepal.Width</code></pre>
<p><span class="notice"><em>iris</em> data set gives the measurements of the variables sepal length and width and petal length and width, respectively, for 50 flowers from each of 3 species of iris. The species are Iris setosa, versicolor, and virginica.</span></p>
</div>
<div id="scatter-plots" class="section level1">
<h1>Scatter plots</h1>
<div id="functions-for-scatter-plots-and-texts-in-2d-and-3d" class="section level2">
<h2>Functions for scatter plots and texts in 2D and 3D</h2>
<p>The function below will be used:</p>
<pre class="r"><code>scatter3D(x, y, z, ..., colvar = z, col = NULL, add = FALSE)

text3D(x, y, z, labels, colvar = NULL, add = FALSE)

points3D(x, y, z, ...)

lines3D(x, y, z, ...)

scatter2D(x, y, colvar = NULL, col = NULL, add = FALSE)

text2D(x, y, labels, colvar = NULL, col = NULL, add = FALSE)</code></pre>
<br/>
<div class="block">
<ul>
<li><strong>x, y, z</strong>: vectors of point coordinates</li>
<li><strong>colvar</strong>: a variable used for coloring</li>
<li><strong>col</strong>: color palette used for coloring the colvar variable</li>
<li><strong>labels</strong>: the text to be written</li>
<li><strong>add</strong>: logical. If TRUE, then the points will be added to the current plot. If FALSE a new plot is started</li>
<li><strong>…</strong>: additional <em>persp</em> arguments including xlim, ylim, zlim, xlab, ylab, zlab, main, sub, r, d, scale, expand, box, axes, nticks, tictype.</li>
</ul>
</div>
<p><br/></p>
<br/>
<div class="warning">
<p>Note that:</p>
<ul>
<li><strong>points3D</strong> and <strong>lines3D</strong> are shorthand for scatter3D(…, type =“p”) and scatter3D(…, type = “l”), respectively.</li>
<li><strong>points2D</strong> and <strong>lines2D</strong> are shorthand for scatter2D(…, type = “p”) and scatter2D(…, type =“l”), respectively.</li>
</ul>
</div>
<p><br/></p>
</div>
<div id="basic-scatter-plot" class="section level2">
<h2>Basic scatter plot</h2>
<pre class="r"><code>scatter3D(x, y, z, clab = c("Sepal", "Width (cm)"))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-scatter-plot-3d-r-data-visualization-1.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="384" style="margin-bottom:10px;" /></p>
<p><span class="notice">The argument <em>clab</em> is used to change the title of the color legend.</span></p>
<p><span class="warning">By default, the points are colored automatically using the variable <em>Z</em></span></p>
<p>In the R code below:</p>
<ul>
<li><strong>colvar = NULL</strong>: avoids coloring by z variable</li>
<li><strong>col = “blue”</strong>: changes point colors to blue</li>
<li><strong>pch = 19</strong>: changes <a href="https://www.sthda.com/english/english/wiki/r-plot-pch-symbols-the-different-point-shapes-available-in-r">point shapes</a></li>
<li><strong>cex = 0.5</strong>: changes the size of points</li>
</ul>
<pre class="r"><code>scatter3D(x, y, z, colvar = NULL, col = "blue",
          pch = 19, cex = 0.5)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-scatter-plot-3d-r-data-visualization-2-1.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="384" style="margin-bottom:10px;" /></p>
</div>
<div id="change-the-type-of-the-box-around-the-plot" class="section level2">
<h2>Change the type of the box around the plot</h2>
<p>The argument <strong>bty</strong> is used. Allowed values are:</p>
<ul>
<li>“f”: full box</li>
<li>“b”: default value. Only the back panels are visible</li>
<li>“b2”: back panels and grid lines are visible</li>
<li>“g”: grey background with white grid lines</li>
<li>“bl”: black background</li>
<li>“bl2”: black background with grey lines</li>
<li>“u”: means that the user will specify the arguments col.axis, col.panel, lwd.panel, col.grid, lwd.grid manually</li>
<li>“n”: no box will be drawn. This is the same as setting box = FALSE</li>
</ul>
<pre class="r"><code># full box
scatter3D(x, y, z, bty = "f", colkey = FALSE, main ="bty= &amp;#39;f&amp;#39;")
# back panels and grid lines are visible
scatter3D(x, y, z, bty = "b2", colkey = FALSE, main ="bty= &amp;#39;b2&amp;#39;" )</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-scatter-plot-3d-box-type-r-data-visualization-1.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="259.2" style="margin-bottom:10px;" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-scatter-plot-3d-box-type-r-data-visualization-2.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="259.2" style="margin-bottom:10px;" /></p>
<pre class="r"><code># grey background with white grid lines
scatter3D(x, y, z, bty = "g", colkey = FALSE, main ="bty= &amp;#39;g&amp;#39;")
# User defined
scatter3D(x, y, z, pch = 18, bty = "u", colkey = FALSE, 
   main ="bty= &amp;#39;u&amp;#39;", col.panel ="steelblue", expand =0.4, 
   col.grid = "darkblue")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-scatter-plot-3d-box-type-r-data-visualization2-1.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="259.2" style="margin-bottom:10px;" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-scatter-plot-3d-box-type-r-data-visualization2-2.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="259.2" style="margin-bottom:10px;" /></p>
<p><span class="notice">The argument <strong>colkey = FALSE</strong> is used to remove the legend.</span></p>
</div>
<div id="color-palettes" class="section level2">
<h2>Color palettes</h2>
<p>Several color palettes are available in <strong>plot3D</strong> package:</p>
<ul>
<li><strong>jet.col(n, alpha)</strong>: generates the matlab-type colors. This is the default color palette used in plot3D</li>
<li><strong>jet2.col(n, alpha)</strong>: similar to <em>jet.col()</em> but lacks the deep blue colors</li>
<li><strong>gg.col(n, alpha)</strong> and <strong>gg2.col(n, alpha)</strong> generates gg-plot-like colors</li>
<li><strong>ramp.col(col = c(“grey”, “black”), n, alpha)</strong>: creates color schemes by interpolation</li>
<li><strong>alpha.col(col = “grey”, alpha)</strong>: creates transparent colors</li>
</ul>
<br/>
<div class="block">
<ul>
<li><strong>n</strong>: Number of colors to generate. Default value is 100</li>
<li><strong>alpha</strong>: color transparency. Value in the range <a href="https://www.sthda.com/english/wiki/0%20means%20transparent%20and%201%20means%20opaque">0, 1</a>. Default value is 1</li>
<li><strong>col</strong>: Colors to interpolate</li>
</ul>
</div>
<p><br/></p>
<pre class="r"><code># gg.col: ggplot2 like color
scatter3D(x, y, z, bty = "g", pch = 18, col = gg.col(100))
# ramp.col: custom palettes
scatter3D(x, y, z, bty = "g", pch = 18,
          col = ramp.col(c("blue", "yellow", "red")) )</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-scatter-plot-3d-color-palette-r-data-visualization-1.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="240" style="margin-bottom:10px;" /><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-scatter-plot-3d-color-palette-r-data-visualization-2.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="240" style="margin-bottom:10px;" /></p>
</div>
<div id="change-the-color-by-groups" class="section level2">
<h2>Change the color by groups</h2>
<p>The <strong>colkey</strong> is customized (see <strong>?colkey</strong> for more details):</p>
<pre class="r"><code>scatter3D(x, y, z, bty = "g", pch = 18, 
          col.var = as.integer(iris$Species), 
          col = c("#1B9E77", "#D95F02", "#7570B3"),
          pch = 18, ticktype = "detailed",
          colkey = list(at = c(2, 3, 4), side = 1, 
          addlines = TRUE, length = 0.5, width = 0.5,
          labels = c("setosa", "versicolor", "virginica")) )</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-color-groups-r-data-visualization-1.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="384" style="margin-bottom:10px;" /></p>
</div>
<div id="change-the-position-of-the-legend" class="section level2">
<h2>Change the position of the legend</h2>
<pre class="r"><code># Bottom colkey
scatter3D(x, y, z, bty = "g",
          colkey = list(side = 1, length = 0.5))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-scatter-plot-3d-box-type-r-data-visualization-2-1.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="384" style="margin-bottom:10px;" /></p>
<p><span class="notice">The argument <em>side</em> is used to specify the colkey position: 1: for bottom, 2: for left, 3: for top, 4: for right.</span></p>
</div>
<div id="d-viewing-direction" class="section level2">
<h2>3D viewing direction</h2>
<p>The arguments <em>theta</em> and <em>phi</em> can be used to define the angles for the viewing direction. <em>theta</em> is the azimuthal direction and <em>phi</em> the co-latitude.</p>
<pre class="r"><code>scatter3D(x, y, z, theta = 15, phi = 20)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-scatter-plot-3d-viewing-direction-r-data-visualization-1.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="384" style="margin-bottom:10px;" /></p>
<pre class="r"><code>scatter3D(x, y, z, phi = 0, bty ="g")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-scatter-plot-3d-viewing-direction-r-data-visualization-2.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="384" style="margin-bottom:10px;" /></p>
<p><span class="notice">The default values for theta and phi are 40.</span></p>
</div>
<div id="titles-and-axis-labels" class="section level2">
<h2>Titles and axis labels</h2>
<pre class="r"><code>scatter3D(x, y, z, pch = 18,  theta = 20, phi = 20,
          main = "Iris data", xlab = "Sepal.Length",
          ylab ="Petal.Length", zlab = "Sepal.Width")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-scatter-plot-3d-titles-r-data-visualization-1.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="384" style="margin-bottom:10px;" /></p>
</div>
<div id="tick-marks-and-labels" class="section level2">
<h2>Tick marks and labels</h2>
<p>The arguments below can be used:</p>
<ol style="list-style-type: decimal">
<li><strong>ticktype</strong>: Possible values are</li>
</ol>
<ul>
<li><em>“simple”</em> draws just an arrow parallel to the axis to indicate direction of increase</li>
<li><em>“detailed”</em> draws normal ticks and labels</li>
</ul>
<ol start="2" style="list-style-type: decimal">
<li><strong>nticks</strong>: the number of tick marks to draw on the axes. It has no effect if ticktype =“simple”.</li>
</ol>
<pre class="r"><code> scatter3D(x, y, z, phi = 0, bty = "g",
        pch = 20, cex = 2, ticktype = "detailed")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-scatter-plot-3d-tick-mark-r-data-visualization-1.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="384" style="margin-bottom:10px;" /></p>
</div>
<div id="add-points-and-text-to-an-existing-plot" class="section level2">
<h2>Add points and text to an existing plot</h2>
<p>The functions below can be used:</p>
<ul>
<li><strong>scatter3D(x, y, z,…, add = TRUE)</strong>: Adds points</li>
<li><strong>text3D(x, y, z, labels, …, add = TRUE)</strong>: Adds texts</li>
</ul>
<ol style="list-style-type: decimal">
<li><strong>Add points</strong> to an existing plot:</li>
</ol>
<pre class="r"><code># Create a scatter plot
 scatter3D(x, y, z, phi = 0, bty = "g",
        pch = 20, cex = 2, ticktype = "detailed")
# Add another point (black color)
scatter3D(x = 7, y = 3, z = 3.5, add = TRUE, colkey = FALSE, 
         pch = 18, cex = 3, col = "black")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-scatter-plot-3d-points-r-data-visualization-1.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="384" style="margin-bottom:10px;" /></p>
<ol start="2" style="list-style-type: decimal">
<li><strong>Add texts</strong> to an existing plot:</li>
</ol>
<pre class="r"><code># Create a scatter plot
 scatter3D(x, y, z, phi = 0, bty = "g", pch = 20, cex = 0.5)
# Add text
text3D(x, y, z,  labels = rownames(iris),
        add = TRUE, colkey = FALSE, cex = 0.5)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-scatter-plot-3d-texts-r-data-visualization-1.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="384" style="margin-bottom:10px;" /></p>
</div>
</div>
<div id="line-plots" class="section level1">
<h1>Line plots</h1>
<pre class="r"><code># type ="l" for lines only
 scatter3D(x, y, z, phi = 0, bty = "g", type = "l", 
           ticktype = "detailed", lwd = 4)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-scatter-plot-3d-line-r-data-visualization-1.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="384" style="margin-bottom:10px;" /></p>
<pre class="r"><code># type ="b" for both points and lines
 scatter3D(x, y, z, phi = 0, bty = "g", type = "b", 
           ticktype = "detailed", pch = 20, 
           cex = c(0.5, 1, 1.5))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-scatter-plot-3d-line-r-data-visualization-2.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="384" style="margin-bottom:10px;" /></p>
<pre class="r"><code># type ="h" for vertical lines
scatter3D(x, y, z, phi = 0, bty = "g",  type = "h", 
           ticktype = "detailed", pch = 19, cex = 0.5)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-scatter-plot-3d-line-r-data-visualization-3.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="384" style="margin-bottom:10px;" /></p>
<p><span class="notice">Vertical lines are useful to see clearly the x-y location of points.</span></p>
<div id="add-confidence-interval" class="section level2">
<h2>Add confidence interval</h2>
<p>The argument <strong>CI</strong> is used. It’s a list containing the parameters and values for the confidence intervals or NULL.</p>
<br/>
<div class="block">
<p>If <em>CI</em> is a list, it should contain at least the item x, y or z (latter for scatter3D).These should be 2-columned matrices, defining the left/right intervals.</p>
<p>Other parameters should be one of: alen = 0.01, lty = par(“lty”), lwd = par(“lwd”), col = NULL, to set the length of the arrow head, the line type and width, and the color.</p>
If <em>col</em> is <em>NULL</em>, then the colors as specified by <em>colvar</em> are used.
</div>
<p><br/></p>
<pre class="r"><code># Confidence interval
CI <- list(z = matrix(nrow = length(x),
                    data = rep(0.1, 2*length(x))))
head(CI$z)</code></pre>
<pre><code>     [,1] [,2]
[1,]  0.1  0.1
[2,]  0.1  0.1
[3,]  0.1  0.1
[4,]  0.1  0.1
[5,]  0.1  0.1
[6,]  0.1  0.1</code></pre>
<pre class="r"><code># 3D Scatter plot with CI
scatter3D(x, y, z, phi = 0, bty = "g", col = gg.col(100), 
          pch = 18, CI = CI)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-scatter-plot-3d-confidence-interval-r-data-visualization-1.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="384" style="margin-bottom:10px;" /></p>
</div>
<div id="d-fancy-scatter-plot-with-small-dots-on-basal-plane" class="section level2">
<h2>3D fancy Scatter plot with small dots on basal plane</h2>
<p>A helper function <strong>scatter3D_fancy()</strong> is used:</p>
<pre class="r"><code># Add small dots on basal plane and on the depth plane
scatter3D_fancy <- function(x, y, z,..., colvar = z)
  {
   panelfirst <- function(pmat) {
      XY <- trans3D(x, y, z = rep(min(z), length(z)), pmat = pmat)
      scatter2D(XY$x, XY$y, colvar = colvar, pch = ".", 
              cex = 2, add = TRUE, colkey = FALSE)
   
      XY <- trans3D(x = rep(min(x), length(x)), y, z, pmat = pmat)
      scatter2D(XY$x, XY$y, colvar = colvar, pch = ".", 
              cex = 2, add = TRUE, colkey = FALSE)
  }
  scatter3D(x, y, z, ..., colvar = colvar, panel.first=panelfirst,
    colkey = list(length = 0.5, width = 0.5, cex.clab = 0.75)) 
}</code></pre>
<p>Fancy scatter plot:</p>
<pre class="r"><code>scatter3D_fancy(x, y, z, pch = 16,
    ticktype = "detailed", theta = 15, d = 2,
    main = "Iris data",  clab = c("Petal", "Width (cm)") )</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-scatter-plot-3d-fancy-r-data-visualization-1.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="384" style="margin-bottom:10px;" /></p>
</div>
<div id="regression-plane" class="section level2">
<h2>Regression plane</h2>
<p>The mtcars data will be used:</p>
<pre class="r"><code>data(mtcars)
head(mtcars[, 1:6])</code></pre>
<pre><code>                   mpg cyl disp  hp drat    wt
Mazda RX4         21.0   6  160 110 3.90 2.620
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875
Datsun 710        22.8   4  108  93 3.85 2.320
Hornet 4 Drive    21.4   6  258 110 3.08 3.215
Hornet Sportabout 18.7   8  360 175 3.15 3.440
Valiant           18.1   6  225 105 2.76 3.460</code></pre>
<ol style="list-style-type: decimal">
<li>Use the function <em>lm()</em> to compute a linear regression model: <em>ax + by + cz + d = 0</em></li>
<li>Use the argument <em>surf</em> in <strong>scatter3D()</strong> function to add a regression surface.</li>
</ol>
<pre class="r"><code># x, y, z variables
x <- mtcars$wt
y <- mtcars$disp
z <- mtcars$mpg
# Compute the linear regression (z = ax + by + d)
fit <- lm(z ~ x + y)
# predict values on regular xy grid
grid.lines = 26
x.pred <- seq(min(x), max(x), length.out = grid.lines)
y.pred <- seq(min(y), max(y), length.out = grid.lines)
xy <- expand.grid( x = x.pred, y = y.pred)

z.pred <- matrix(predict(fit, newdata = xy), 
                 nrow = grid.lines, ncol = grid.lines)
# fitted points for droplines to surface
fitpoints <- predict(fit)

# scatter plot with regression plane
scatter3D(x, y, z, pch = 18, cex = 2, 
    theta = 20, phi = 20, ticktype = "detailed",
    xlab = "wt", ylab = "disp", zlab = "mpg",  
    surf = list(x = x.pred, y = y.pred, z = z.pred,  
    facets = NA, fit = fitpoints), main = "mtcars")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-regression-plane-1.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="384" style="margin-bottom:10px;" /></p>
<p><span class="success"><strong>surf</strong> is a list specifying a (fitted) surface to be added on the scatter plot. The list should include at least x, y, z, defining the surface.</span></p>
<p>Other optional parameters can be specified in the <em>surf</em> argument including: colvar, col, NAcol, border, facets, lwd, resfac, clim, ltheta, lphi, shade, lighting, fit. (<strong>see ?surf3D</strong> for more details on these parameters)</p>
<br/>
<div class ="warning">
<ul>
<li><p>Note that, by default <strong>colvar = z</strong>.</p></li>
<li>The argument <strong>fit</strong> should give the fitted <em>z-values</em>, in the same order as the z-values of the scatter points, for instance produced by <em>predict()</em>. When present, this will produce droplines from points to the fitted surface.
</div>

<p><br/></p></li>
</ul>
<p><span class="notice">Note that, the function <strong>expand.grid()</strong>, in the R code above, creates a data frame from all combinations of factors</span></p>
</div>
</div>
<div id="text3d-plot-3-dimensionnal-texts" class="section level1">
<h1>text3D: plot 3-dimensionnal texts</h1>
<p>The function <strong>text3D()</strong> is used as follow:</p>
<pre class="r"><code>text3D(x, y, z, labels, ...)</code></pre>
<p>The USArrests data sets will be used in the example below:</p>
<pre class="r"><code>data(USArrests)

with(USArrests, text3D(Murder, Assault, Rape, 
  labels = rownames(USArrests), colvar = UrbanPop, 
  col = gg.col(100), theta = 60, phi = 20,
  xlab = "Murder", ylab = "Assault", zlab = "Rape", 
  main = "USA arrests", cex = 0.6, 
  bty = "g", ticktype = "detailed", d = 2,
  clab = c("Urban","Pop"), adj = 0.5, font = 2))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-scatter-plot-3d-text-r-data-visualization-1.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="384" style="margin-bottom:10px;" /></p>
</div>
<div id="text3d-and-scatter3d" class="section level1">
<h1>text3D and scatter3D</h1>
<pre class="r"><code># Plot texts
with(USArrests, text3D(Murder, Assault, Rape, 
  labels = rownames(USArrests), colvar = UrbanPop, 
  col = gg.col(100), theta = 60, phi = 20,
  xlab = "Murder", ylab = "Assault", zlab = "Rape", 
  main = "USA arrests", cex = 0.6, 
  bty = "g", ticktype = "detailed", d = 2,
  clab = c("Urban","Pop"), adj = 0.5, font = 2))
# Add points
 with(USArrests, scatter3D(Murder, Assault, Rape - 1, 
    colvar = UrbanPop, col = gg.col(100), 
    type = "h", pch = ".", add = TRUE))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-scatter-plot-3d-text-2-r-data-visualization-1.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="384" style="margin-bottom:10px;" /></p>
<pre class="r"><code># Zoom near origin: choose suitable ranges
 plotdev(xlim = c(0, 10), ylim = c(40, 150), 
         zlim = c(7, 25))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-scatter-plot-3d-text-2-r-data-visualization-2.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="384" style="margin-bottom:10px;" /></p>
<br/>
<div class="warning">
<p>Note that, in order to choose suitable ranges for zooming, you can display axis ranges as follow:</p>
<pre class="r"><code># display axis ranges
 getplist()[c("xlim","ylim","zlim")] </code></pre>
<pre><code>$xlim
[1]  0.8 17.4

$ylim
[1]  45 337

$zlim
[1]  7.3 46.0</code></pre>
</div>
<p><br/></p>
</div>
<div id="d-histogram" class="section level1">
<h1>3D Histogram</h1>
<p>The function <strong>hist3D()</strong> is used:</p>
<pre class="r"><code>hist3D (x, y, z, ..., colvar = z, 
      col = NULL,  add = FALSE) </code></pre>
<br/>
<div class="block">
<ul>
<li><strong>z</strong>: Matrix containing the values to be plotted</li>
<li><strong>x, y</strong> vectors with x and y values. <em>x</em> should be of length equal to nrow(z) and y should be equal to ncol(z)</li>
<li><strong>colvar</strong>: the variable used for coloring. If present, it should have the same dimension as z.</li>
<li><strong>col</strong>: color palette to be used for the colvar variable. By default a <em>red-yellow-blue</em> color scheme (?jet.col) is used</li>
<li><strong>add</strong>: Logical. If TRUE, then the surfaces will be added to the current plot. If FALSE a new plot is started.</li>
</ul>
</div>
<p><br/></p>
<pre class="r"><code>data(VADeaths)
#  hist3D and ribbon3D with greyish background, rotated, rescaled,...
hist3D(z = VADeaths, scale = FALSE, expand = 0.01, bty = "g", phi = 20,
        col = "#0072B2", border = "black", shade = 0.2, ltheta = 90,
        space = 0.3, ticktype = "detailed", d = 2)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-histogram-3D-basic-r-data-visualization-1.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="384" style="margin-bottom:10px;" /></p>
<pre class="r"><code>hist3D (x = 1:5, y = 1:4, z = VADeaths,
        bty = "g", phi = 20,  theta = -60,
        xlab = "", ylab = "", zlab = "", main = "VADeaths",
        col = "#0072B2", border = "black", shade = 0.8,
        ticktype = "detailed", space = 0.15, d = 2, cex.axis = 1e-9)

# Use text3D to label x axis
 text3D(x = 1:5, y = rep(0.5, 5), z = rep(3, 5),
       labels = rownames(VADeaths),
       add = TRUE, adj = 0)

# Use text3D to label y axis
 text3D(x = rep(1, 4),   y = 1:4, z = rep(0, 4),
       labels  = colnames(VADeaths),
       add = TRUE, adj = 1)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-histogram-3D-r-data-visualization-1.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="384" style="margin-bottom:10px;" /></p>
<p><strong>fancy 3D</strong> histograms</p>
<pre class="r"><code>hist3D_fancy<- function(x, y, break.func = c("Sturges", "scott", "FD"), breaks = NULL,
                        colvar = NULL, col="white", clab=NULL, phi = 5, theta = 25, ...){
  
  # Compute the number of classes for a histogram
  break.func <- break.func [1]
  if(is.null(breaks)){
    x.breaks <- switch(break.func,
                       Sturges = nclass.Sturges(x),
                       scott = nclass.scott(x),
                       FD = nclass.FD(x))
    y.breaks <- switch(break.func,
                       Sturges = nclass.Sturges(y),
                       scott = nclass.scott(y),
                       FD = nclass.FD(y))
  } else x.breaks <- y.breaks <- breaks
  
  # Cut x and y variables in bins for counting
  x.bin <- seq(min(x), max(x), length.out = x.breaks)
  y.bin <- seq(min(y), max(y), length.out = y.breaks)
  xy <- table(cut(x, x.bin), cut(y, y.bin))
  z <- xy
  
  xmid <- 0.5*(x.bin[-1] + x.bin[-length(x.bin)])
  ymid <- 0.5*(y.bin[-1] + y.bin[-length(y.bin)])
  
  oldmar <- par("mar")
  par (mar = par("mar") + c(0, 0, 0, 2))
  hist3D(x = xmid, y = ymid, z = xy, ...,
    zlim = c(-max(z)/2, max(z)), zlab = "counts", bty= "g", 
    phi = phi, theta = theta,
    shade = 0.2, col = col, border = "black",
    d = 1, ticktype = "detailed")
   
  scatter3D(x, y,
    z = rep(-max(z)/2, length.out = length(x)),
    colvar = colvar, col = gg.col(100),
    add = TRUE, pch = 18, clab = clab,
    colkey = list(length = 0.5, width = 0.5,
       dist = 0.05, cex.axis = 0.8, cex.clab = 0.8)
       )
  par(mar = oldmar)

}</code></pre>
<pre class="r"><code>hist3D_fancy(quakes$long, quakes$lat, colvar=quakes$depth,
             breaks =30)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-histogramm-3D-fancy-1.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="384" style="margin-bottom:10px;" /></p>
<pre class="r"><code>hist3D_fancy(iris$Sepal.Length, iris$Petal.Width, 
             colvar=as.numeric(iris$Species))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-histogramm-3D-fancy-2.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="384" style="margin-bottom:10px;" /></p>
</div>
<div id="scatter2d-2d-scatter-plot" class="section level1">
<h1>scatter2D: 2D scatter plot</h1>
<p><strong>Create some data</strong>:</p>
<pre class="r"><code># x, y coordinates
set.seed(1234)
x  <- sort(rnorm(10)) 
y  <- runif(10)
# Variable for coloring points
col.v <- sqrt(x^2 + y^2) </code></pre>
<p><strong>Basic 2D scatter plot</strong>:</p>
<pre class="r"><code>scatter2D(x, y, colvar = col.v, pch = 16, bty ="n",
          type ="b")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-scatter-plot-2D-basic-r-data-visualization-1.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="384" style="margin-bottom:10px;" /></p>
<br/>

<div class="block">
<ol style="list-style-type: decimal">
<li><strong>type</strong>: plot types. Allowed values are:
</li>
</ol>
<ul>
<li><strong>“b”</strong> to draw both points and line</li>
<li><strong>“h”</strong> for vertical line</li>
<li><strong>“l”</strong> for line only</li>
<li><strong>“p”</strong> for points only</li>
</ul>
<ol style="list-style-type: decimal">
<li><strong>bty</strong>: box type</li>
</ol>
</div>
<p><br/></p>
<p><strong>2D scatter plot with confidence interval</strong>:</p>
<pre class="r"><code># Confidence interval for x variable only
CI <- list()
CI$x <- matrix(nrow = length(x), data = c(rep(0.25, 2*length(x))))

scatter2D(x, y, colvar = col.v, pch = 16, bty ="n", cex = 1.5, 
          CI = CI, type = "b")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-scatter-plot-2D-confidence-interval-r-data-visualization-1.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="384" style="margin-bottom:10px;" /></p>
<pre class="r"><code># Confidence interval for both x and y variables
CI$y <- matrix (nrow = length(y), data = c(rep(0.05, 2*length(y))))
CI$col <- "black"

scatter2D(x, y, colvar = col.v, pch = 16,  bty ="n", cex = 1.5,
          CI = CI, type ="b")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-scatter-plot-2D-confidence-interval-r-data-visualization-2.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="384" style="margin-bottom:10px;" /></p>
<pre class="r"><code>CI$y[c(2,4,8,10), ] <- NA  # Some points have no CI
CI$x[c(2,4,8,10), ] <- NA  # Some points have no CI
CI$alen <- 0.02            # increase arrow head
scatter2D(x, y, colvar = col.v, pch = 16,  bty ="n", cex = 1.5,
          CI = CI, type ="b")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-scatter-plot-2D-confidence-interval-r-data-visualization-3.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="384" style="margin-bottom:10px;" /></p>
</div>
<div id="text2d" class="section level1">
<h1>text2D</h1>
<pre class="r"><code># Only text
with(USArrests, text2D(x = Murder, y = Assault + 5, colvar = Rape, 
     xlab = "Murder", ylab = "Assault", clab = "Rape", 
     main = "USA arrests", labels = rownames(USArrests), cex = 0.6, 
     adj = 0.5, font = 2))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-text-2d-1.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="384" style="margin-bottom:10px;" /></p>
<pre class="r"><code># text with point
 with(USArrests, text2D(x = Murder, y = Assault + 5, colvar = Rape, 
     xlab = "Murder", ylab = "Assault", clab = "Rape", 
     main = "USA arrests", labels = rownames(USArrests), cex = 0.6, 
     adj = 0.5, font = 2))
 with(USArrests, scatter2D(x = Murder, y = Assault, colvar = Rape, 
     pch = 16, add = TRUE, colkey = FALSE))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-text-2D-r-data-visualization-1.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="384" style="margin-bottom:10px;" /></p>
</div>
<div id="other-functions" class="section level1">
<h1>Other functions</h1>
<p>It’s also possible to draw arrows, segments and rectangles in a 3D or 2D plot using the functions below:</p>
<pre class="r"><code>arrows3D(x0, y0, z0, x1, y1, z1, ..., colvar = NULL,
         col = NULL, type = "triangle", add = FALSE)

segments3D(x0, y0, z0, x1, y1, z1, ..., colvar = NULL,
           col = NULL, add = "FALSE")

rect3D(x0, y0, y0, x1, y1, z1, ..., colvar = NULL,
       col = NULL, add = FALSE)


arrows2D(x0, y0, z0, x1, y1, z1, ..., colvar = NULL,
         col = NULL, type = "triangle", add = FALSE)

segments2D(x0, y0, z0, x1, y1, z1, ..., colvar = NULL,
           col = NULL, add = "FALSE")

rect2D(x0, y0, y0, x1, y1, z1, ..., colvar = NULL,
       col = NULL, add = FALSE)</code></pre>
<br/>
<div class="block">
<ul>
<li><strong>x0, y0, z0</strong>: coordinates of points from which to draw</li>
<li><strong>x1</strong>, <strong>y1</strong>, <strong>z1</strong>: coordinates of points to which to draw. For arrows3D and segments3D, at least one must be supplied. For rect3D exactly one must be NULL.</li>
<li><strong>colvar</strong>: The variable used for coloring.</li>
<li><strong>col</strong>: color palette to be used for coloring. Default is <em>red-yellow-blue</em> color scheme.</li>
<li><strong>add</strong>: Logical. If TRUE, then the arrows, segments, … will be added to the current plot. If FALSE a new plot is started.</li>
</ul>
</div>
<p><br/></p>
<p>Prepare the data: we want to plot 4 arrows starting from the point of coordinates c(x0, y0, z0) and ending at c(x1, y1, z1)</p>
<pre class="r"><code>x0 <- c(0, 0, 0, 0)
y0 <- c(0, 0, 0, 0)
z0 <- c(0, 0, 0, 0)

x1 <- c(0.89, -0.46, 0.99, 0.96)
y1 <- c(0.36,  0.88, 0.02, 0.06)
z1 <- c(-0.28, 0.09, 0.05, 0.24)

cols <- c("#1B9E77", "#D95F02", "#7570B3", "#E7298A")</code></pre>
<p><strong>3D Arrows</strong>:</p>
<pre class="r"><code>arrows3D(x0, y0, z0, x1, y1, z1, colvar = x1^2, col = cols,
         lwd = 2, d = 3, clab = c("Quality", "score"), 
         main = "Arrows 3D", bty ="g", ticktype = "detailed")

# Add starting point of arrow
points3D(x0, y0, z0, add = TRUE, col="darkred", 
          colkey = FALSE, pch = 19, cex = 1)

# Add labels to the arrows
text3D(x1, y1, z1, c("Sepal.L", "Sepal.W", "Petal.L", "Petal.W"),
       colvar = x1^2, col = cols, add=TRUE, colkey = FALSE)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-arrow-3d-r-data-visualization-1.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="384" style="margin-bottom:10px;" /></p>
<p><strong>2D arrows:</strong></p>
<pre class="r"><code>arrows2D(x0, y0,  x1, y1,  colvar = x1^2, col = cols,
         lwd = 2, clab = c("Quality", "score"), 
          bty ="n", xlim = c(-1, 1), ylim = c(-1, 1))
# Add vertical and horizontal lines at c(0,0)
abline(h =0, v = 0, lty = 2)

# Add starting point of arrow
points2D(x0, y0, add = TRUE, col="darkred", 
          colkey = FALSE, pch = 19, cex = 1)

# Add labels to the arrows
text2D(x1, y1, c("Sepal.L", "Sepal.W", "Petal.L", "Petal.W"),
       colvar = x1^2, col = cols, add=TRUE, colkey = FALSE)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-arrow-2D-r-data-visualization-1.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="384" style="margin-bottom:10px;" /></p>
<p><span class="notice">Note that, <strong>segments3D()</strong> and <strong>segments2D()</strong> are very similar to <strong>arrows3D()</strong> and <strong>arrows2D()</strong> and you can play with them also.</span></p>
<p><strong>3D rectangle</strong>: the R code below creates a rectangle with a transparent fill color (alpha = 0.5)</p>
<pre class="r"><code>rect3D(x0 = 0, y0 = 0.5, z0 = 0, x1 = 1, z1 = 5, 
       ylim = c(0, 1), bty = "g", facets = TRUE, 
       border = "red", col ="#7570B3", alpha=0.5,
       lwd = 2, phi = 20)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-rectangle-3D-r-data-visualization-1.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="384" style="margin-bottom:10px;" /></p>
<p><span class="notice">In the R code above, <em>facets = FALSE</em>, will remove the rectangle fill color.</span></p>
<p><strong>2D rectangle</strong>:</p>
<pre class="r"><code>rect2D(x0 = runif(3), y0 = runif(3), 
       x1 = runif(3), y1 = runif(3), colvar = 1:3, 
       alpha = 0.4, lwd = 2, main = "rect2D")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/plot3d-rectangle-2D-r-data-visualization-1.png" title="plot3D - R software and data visualization" alt="plot3D - R software and data visualization" width="384" style="margin-bottom:10px;" /></p>
</div>
<div id="interactive-plot" class="section level1">
<h1>Interactive plot</h1>
<p>To draw an interactive <strong>3D plot</strong> the package <strong>plot3Drgl</strong> can be used.</p>
<p>The package <strong>plot3Drgl</strong> allows to plot the graph generated with <strong>plot3D</strong> in openGL, as made available by package rgl.</p>
<p>The simplest way is to do as follow:</p>
<ol style="list-style-type: decimal">
<li>Create base R-graphics using plot3D package</li>
<li>Then use the function plotrgl() to draw the same figure in rgl</li>
</ol>
<p><span class="success">The package <strong>rgl</strong> allows to interactively rotate, zoom the graphs. However it’s not yet possible to plot a colorkey</span></p>
<pre class="r"><code># Create his3D using plot3D
hist3D_fancy(iris$Sepal.Length, iris$Petal.Width, colvar=as.numeric(iris$Species))
# Make the rgl version
library("plot3Drgl")
plotrgl()</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/images/histogram-3d.gif" alt="RGL movie 3d" /></p>
<br/>
<div class="block">
<p>Note that, after creating the rgl plot you can use the functions below:</p>
<ul>
<li>croprgl(xlim, ylim, zlim, …) to modify the ranges</li>
<li>cutrgl(…) to zoom in on a selected region of the plot. The current plot will be overwritten</li>
<li><p>uncutrgl(…) and uncroprgl(…) restore the original plot.</p></li>
<li>…: any arguments for par3d, open3d or material3d in rgl package.</li>
</ul>
</div>
<p><br/></p>
</div>
<div id="infos" class="section level1">
<h1>Infos</h1>
<p><span class="warning"> This analysis has been performed using <strong>R software</strong> (ver. 3.1.2) and <strong>plot3D</strong> (ver. 1.0-2) </span></p>
<p><strong>References</strong>:</p>
<ul>
<li>Karline Soetaert. plot3D: Tools for plotting 3-D and 2-D data. <a href="http://cran.r-project.org/web/packages/plot3D/vignettes/plot3D.pdf">http://cran.r-project.org/web/packages/plot3D/vignettes/plot3D.pdf</a></li>
</ul>
</div>

<script>jQuery(document).ready(function () {
    jQuery('h1').addClass('wiki_paragraph1');
    jQuery('h2').addClass('wiki_paragraph2');
    jQuery('h3').addClass('wiki_paragraph3');
    jQuery('h4').addClass('wiki_paragraph4');
    });//add phpboost class to header</script>
<style>.content{padding:0px;}</style>
</div><!--end rdoc-->
<!--====================== stop here when you copy to sthda================-->


<!-- END HTML -->]]></description>
			<pubDate>Wed, 06 May 2015 22:59:35 +0200</pubDate>
			
		</item>
		
		<item>
			<title><![CDATA[A complete guide to 3D visualization device system in R - R software and data visualization]]></title>
			<link>https://www.sthda.com/english/wiki/a-complete-guide-to-3d-visualization-device-system-in-r-r-software-and-data-visualization</link>
			<guid>https://www.sthda.com/english/wiki/a-complete-guide-to-3d-visualization-device-system-in-r-r-software-and-data-visualization</guid>
			<description><![CDATA[<!-- START HTML -->

            
  <!--====================== start from here when you copy to sthda================-->  
  <div id="rdoc">


<div id="TOC">
<ul>
<li><a href="#install-the-rgl-package">Install the RGL package</a></li>
<li><a href="#load-the-rgl-package">Load the RGL package</a></li>
<li><a href="#prepare-the-data">Prepare the data</a></li>
<li><a href="#start-and-close-rgl-device">Start and close RGL device</a></li>
<li><a href="#d-scatter-plot">3D scatter plot</a><ul>
<li><a href="#basic-graph">Basic graph</a></li>
<li><a href="#change-the-background-and-point-colors">Change the background and point colors</a></li>
<li><a href="#change-the-shape-of-points">Change the shape of points</a></li>
</ul></li>
<li><a href="#rgl_init-a-custom-function-to-initialize-rgl-device">rgl_init(): A custom function to initialize RGL device</a></li>
<li><a href="#add-a-bounding-box-decoration">Add a bounding box decoration</a></li>
<li><a href="#add-axis-lines-and-labels">Add axis lines and labels</a><ul>
<li><a href="#scale-the-data">Scale the data</a></li>
<li><a href="#use-c-max-max">Use c(-max, max)</a></li>
<li><a href="#rgl_add_axes-a-custom-function-to-add-x-y-and-z-axes">rgl_add_axes(): A custom function to add x, y and z axes</a></li>
<li><a href="#show-scales-tick-marks">Show scales: tick marks</a></li>
</ul></li>
<li><a href="#set-the-aspect-ratios-of-the-x-y-and-z-axes">Set the aspect ratios of the x, y and z axes</a></li>
<li><a href="#change-the-color-of-points-by-groups">Change the color of points by groups</a></li>
<li><a href="#change-the-shape-of-points-1">Change the shape of points</a></li>
<li><a href="#add-an-ellipse-of-concentration">Add an ellipse of concentration</a></li>
<li><a href="#regression-plane">Regression plane</a></li>
<li><a href="#create-a-movie-of-rgl-scene">Create a movie of RGL scene</a></li>
<li><a href="#export-images-as-png-or-pdf">Export images as png or pdf</a></li>
<li><a href="#export-the-plot-into-an-interactive-html-file">Export the plot into an interactive HTML file</a></li>
<li><a href="#select-a-rectangle-in-an-rgl-scene">Select a rectangle in an RGL scene</a></li>
<li><a href="#identify-points-in-a-plot">Identify points in a plot</a></li>
<li><a href="#r3d-interface">R3D Interface</a><ul>
<li><a href="#d-scatter-plot-1">3D Scatter plot</a></li>
<li><a href="#some-important-functions">Some important functions</a></li>
</ul></li>
<li><a href="#rgl-functions">RGL functions</a><ul>
<li><a href="#device-management">Device management</a></li>
<li><a href="#shape-functions">Shape functions</a></li>
<li><a href="#scene-management">Scene management</a></li>
<li><a href="#setup-the-environment">Setup the environment</a></li>
<li><a href="#appearance-setup">Appearance setup</a></li>
<li><a href="#export-screenshot">Export screenshot</a></li>
<li><a href="#assign-focus-to-an-rgl-window">Assign focus to an RGL window</a></li>
</ul></li>
<li><a href="#infos">Infos</a></li>
</ul>
</div>

<p><br/></p>
<p>This <strong>R tutorial</strong> describes, step by step, how to build a <strong>3D graphic</strong> using <strong>R software</strong> and the <strong>rgl</strong> package. You’ll learn also how to create a <strong>movie</strong> of your <strong>3D scene</strong> in <strong>R</strong>.</p>
<p><strong>RGL</strong> is a <strong>3D graphics</strong> package that produces a real-time interactive <strong>3D plot</strong>. It allows to interactively rotate, zoom the graphics and select regions.</p>
<p>The <strong>rgl package</strong> includes also a <em>generic 3D interface</em> named <strong>R3D</strong>. <strong>R3D</strong> is a collection of generic 3D objects and functions which are described at the end of this article.</p>

<div id="install-the-rgl-package" class="section level1">
<h1>Install the RGL package</h1>
<pre class="r"><code>install.packages("rgl")</code></pre>
<br/>
<div class="warning">
<p>Note that, on Linux operating system, the <strong>rgl</strong> package can be installed as follow:</p>
<p><strong>sudo apt-get install r-cran-rgl</strong></p>
</div>
<p><br/></p>
</div>
<div id="load-the-rgl-package" class="section level1">
<h1>Load the RGL package</h1>
<pre class="r"><code>library("rgl")</code></pre>
</div>
<div id="prepare-the-data" class="section level1">
<h1>Prepare the data</h1>
<p>We’ll use the <em>iris</em> data set in the following examples:</p>
<pre class="r"><code>data(iris)
head(iris)</code></pre>
<pre><code>  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa</code></pre>
<pre class="r"><code>x <- sep.l <- iris$Sepal.Length
y <- pet.l <- iris$Petal.Length
z <- sep.w <- iris$Sepal.Width</code></pre>
<p><span class="notice"><em>iris</em> 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.</span></p>
</div>
<div id="start-and-close-rgl-device" class="section level1">
<h1>Start and close RGL device</h1>
<p><span class="warning">To make a 3D plot with RGL, you should first start the RGL device in R.</span></p>
<p>The functions below are used to manage the <strong>RGL</strong> device:</p>
<ul>
<li><strong>rgl.open()</strong>: Opens a new device</li>
<li><strong>rgl.close()</strong>: Closes the current device</li>
<li><strong>rgl.clear()</strong>: Clears the current device</li>
<li><strong>rgl.cur()</strong>: Returns the active device ID</li>
<li><strong>rgl.quit()</strong>: Shutdowns the RGL device system</li>
</ul>
<br/>
<div class="block">
<p>In the first sections of this tutorial, I’ll open a new RGL device for each plot.</p>
<p>Note that, you don’t need to do the same thing.</p>
You can just use the function <strong>rgl.open()</strong> the first time –> then make your first 3D plot –> then use <strong>rgl.clear()</strong> to clear the scene –> and make a new plot again.
</div>
<p><br/></p>
</div>
<div id="d-scatter-plot" class="section level1">
<h1>3D scatter plot</h1>
<div id="basic-graph" class="section level2">
<h2>Basic graph</h2>
<p>The function <strong>rgl.points()</strong> is used to draw a <strong>3D scatter plot</strong>:</p>
<pre class="r"><code>rgl.open() # Open a new RGL device
rgl.points(x, y, z, color ="lightgray") # Scatter plot</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/rgl-points-r-data-visualization-1.png" title="RGL - R software and data visualization" alt="RGL - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
<br/>
<div class="block">
<ul>
<li><strong>x, y, z</strong> : Numeric vector specifying the coordinates of points to be drawn. The arguments y and z are optional when:</li>
<li><em>x</em> is a matrix or a data frame containing at least 3 columns which will be used as the x, y and z coordinates. Ex: <em>rgl.points(iris)</em></li>
<li><em>x</em> is a formula of form zvar ~ xvar + yvar (see <strong>?xyz.coords</strong>). Ex: <em>rgl.points( z ~ x + y)</em>.</li>
<li><strong>…</strong>: Material properties. See <strong>?rgl.material</strong> for details.</li>
</ul>
</div>
<p><br/></p>
</div>
<div id="change-the-background-and-point-colors" class="section level2">
<h2>Change the background and point colors</h2>
<ul>
<li>The function <strong>rgl.bg(color)</strong> can be used to setup the background environment of the scene
</li>
<li>The argument <em>color</em> is used in the function <em>rgl.points()</em> to change point colors</li>
</ul>
<p><span class="notice">Note that, it’s also possible to change the <strong>size of points</strong> using the argument <strong>size</strong></span></p>
<pre class="r"><code>rgl.open()# Open a new RGL device
rgl.bg(color = "white") # Setup the background color
rgl.points(x, y, z, color = "blue", size = 5) # Scatter plot</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/rgl-background-point-colors-r-data-visualization-1.png" title="RGL - R software and data visualization" alt="RGL - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
<br/>
<div class="notice">
<p>Note that, the equivalent of the functions above for the <em>3d interface</em> is:</p>
<ul>
<li><strong>open3d()</strong>: Open a new 3D device</li>
<li><strong>bg3d(color)</strong>: Set up the background environment of the scene</li>
<li><strong>points3d(x, y, Z, …)</strong>: plot points of coordinates x, y, z</li>
</ul>
</div>
<p><br/></p>
</div>
<div id="change-the-shape-of-points" class="section level2">
<h2>Change the shape of points</h2>
<p>It’s possible to draw <strong>spheres</strong> using the functions <strong>rgl.spheres()</strong> or <strong>spheres3d()</strong>:</p>
<pre class="r"><code>spheres3d(x, y = NULL, z = NULL, radius = 1, ...)

rgl.spheres(x, y = NULL, z = NULL, r, ...)</code></pre>
<p><strong>rgl.spheres()</strong> draws spheres with center (x, y, z) and radius r.</p>
<br/>
<div class="block">
<ul>
<li><strong>x, y, z</strong> : Numeric vector specifying the coordinates for the center of each sphere. The arguments y and z are optional when:</li>
<li><em>x</em> is a matrix or a data frame containing at least 3 columns which will be used as the x, y and z coordinates. Ex: <em>rgl.spheres(iris, r = 0.2)</em></li>
<li><em>x</em> is a formula of form zvar ~ xvar + yvar (see <strong>?xyz.coords</strong>). Ex: <em>rgl.spheres( z ~ x + y, r = 0.2)</em>.</li>
<li><strong>radius</strong>: a vector or single value indicating the radius of spheres</li>
<li><strong>…</strong>: Material properties. See <strong>?rgl.material</strong> for details.</li>
</ul>
</div>
<p><br/></p>
<pre class="r"><code>rgl.open()# Open a new RGL device
rgl.bg(color = "white") # Setup the background color
rgl.spheres(x, y, z, r = 0.2, color = "grey") </code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/rgl-spheres-r-data-visualization-1.png" title="RGL - R software and data visualization" alt="RGL - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
<p><span class="warning">Note that, an <strong>rgl</strong> plot can be manually rotated by holding down on the mouse or touchpad. It can be also zoomed using the scroll wheel on a mouse or pressing ctrl + using the touchpad on a PC or two fingers (up or down) on a mac.</span></p>
</div>
</div>
<div id="rgl_init-a-custom-function-to-initialize-rgl-device" class="section level1">
<h1>rgl_init(): A custom function to initialize RGL device</h1>
<p>The function <strong>rgl_init()</strong> will create a new <strong>RGL</strong> device if requested or if there is no opened device:</p>
<pre class="r"><code>#&amp;#39; @param new.device a logical value. If TRUE, creates a new device
#&amp;#39; @param bg the background color of the device
#&amp;#39; @param width the width of the device
rgl_init <- function(new.device = FALSE, bg = "white", width = 640) { 
  if( new.device | rgl.cur() == 0 ) {
    rgl.open()
    par3d(windowRect = 50 + c( 0, 0, width, width ) )
    rgl.bg(color = bg )
  }
  rgl.clear(type = c("shapes", "bboxdeco"))
  rgl.viewpoint(theta = 15, phi = 20, zoom = 0.7)
}</code></pre>
<br/>
<div class="block">
<p><strong>Description of the used RGL functions</strong>:</p>
<ul>
<li><strong>rgl.open()</strong>: open a new device</li>
<li><strong>rgl.cur()</strong>: returns active device ID</li>
<li><strong>par3d(windowRect)</strong>: set the window size</li>
<li><strong>rgl.viewpoint(theta, phi, fov, zoom)</strong>: set up viewpoint. The arguments <em>theta</em> and <em>phi</em> are polar coordinates.</li>
<li><strong>theta</strong> and <strong>phi</strong> are the polar coordinates. Default values are 0 and 15, respectively</li>
<li><strong>fov</strong> is the field-of-view angle in degrees. Default value is 60</li>
<li><strong>zoom</strong> is the zoom factor. Default value is 1</li>
<li><strong>rgl.bg(color)</strong>: define the background color of the device</li>
<li><strong>rgl.clear(type)</strong>: Clears the scene from the specified stack (“shapes”, “lights”, “bboxdeco”, “background”)</li>
</ul>
</div>
<p><br/></p>
<p><span class="warning"> In the <strong>R code</strong> above, I used the function <strong>rgl.viewpoint()</strong> to set automatically the viewpoint orientation and the zoom. As you already know, the <strong>RGL</strong> device is interactive and you can adjust the viewpoint and zoom the plot using your mouse. </span></p>
</div>
<div id="add-a-bounding-box-decoration" class="section level1">
<h1>Add a bounding box decoration</h1>
<p>The function <strong>rgl.bbox()</strong> is used:</p>
<pre class="r"><code>rgl_init()
rgl.spheres(x, y, z, r = 0.2, color = "yellow")  # Scatter plot
rgl.bbox(color = "#333377") # Add bounding box decoration</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/rgl-rgl-bbox-bounding-box-r-data-visualization-1.png" title="RGL - R software and data visualization" alt="RGL - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
<p>A simplified format of the function <strong>rgl.bbox()</strong> is:</p>
<pre class="r"><code>rgl.bbox(xlen=5, ylen=5, zlen=5, marklen=15.9, ...)</code></pre>
<br/>
<div class="block">
<ul>
<li><strong>xlen</strong>, <strong>ylen</strong>, <strong>zlen</strong>: values specifying the number of tickmarks on x, y and Z axes, respectively</li>
<li><strong>marklen</strong>: value specifying the length of the tickmarks</li>
<li><strong>…</strong>: other rgl material properties (see <em>?rgl.material</em>) including:</li>
<li><strong>color</strong>: a vector of colors. The first color is used for the background color of the bounding box. The second color is used for the tick mark labels.</li>
<li><strong>emission</strong>, <strong>specular</strong>, <strong>shininess</strong>: properties for lighting calculation</li>
<li><strong>alpha</strong>: value specifying the color transparency. The value should be between 0.0 (fully transparent) and 1.0 (opaque)</li>
</ul>
</div>
<p><br/></p>
<pre class="r"><code>rgl_init()
rgl.spheres(x, y, z, r = 0.2, color = "yellow")  
# Add bounding box decoration
rgl.bbox(color=c("#333377","black"), emission="#333377",
         specular="#3333FF", shininess=5, alpha=0.8 ) </code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/rgl-rgl-bbox-bounding-box-2-r-data-visualization-1.png" title="RGL - R software and data visualization" alt="RGL - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
</div>
<div id="add-axis-lines-and-labels" class="section level1">
<h1>Add axis lines and labels</h1>
<ul>
<li>The function <strong>rgl.lines(x, y = NULL, z = NULL, …)</strong> can be used to add axis lines.</li>
<li>The function <strong>rgl.texts(x, y = NULL, z = NULL, text)</strong> is used to add axis labels</li>
</ul>
<br/>
<div class="block">
<p>For the function <strong>rgl.lines()</strong>, the arguments x, y, and z are numeric vectors of length 2 (i.e, : x = c(x1,x2), y = c(y1, y2), z = c(z1, z2) ).</p>
<ul>
<li>The values x1, y1 and y3 are the <strong>3D coordinates</strong> of the line starting point.</li>
<li>The values x2, y2 and y3 corresponds to the <strong>3D coordinates</strong> of the line ending point.</li>
</ul>
</div>
<p><br/></p>
<p><span class="warning">Note also that, the argument <em>x</em> can be a matrix or a data frame containing, at least, 3 columns corresponding to the x, y and z coordinates, respectively. In this case, the argument <em>y</em> and <em>z</em> can be omitted.</span></p>
<p>To draw an axis, you should specify the range (minimum and the maximum) of the axis to the function <strong>rgl.lines()</strong>:</p>
<pre class="r"><code># Make a scatter plot
rgl_init()
rgl.spheres(x, y, z, r = 0.2, color = "yellow") 
# Add x, y, and z Axes
rgl.lines(c(min(x), max(x)), c(0, 0), c(0, 0), color = "black")
rgl.lines(c(0, 0), c(min(y),max(y)), c(0, 0), color = "red")
rgl.lines(c(0, 0), c(0, 0), c(min(z),max(z)), color = "green")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/rgl-axis-lines-labels-r-data-visualization-1.png" title="RGL - R software and data visualization" alt="RGL - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
<p><span class="warning">As you can see, the axes are drawn but the problem is that they don’t cross at the point c(0, 0, 0)</span></p>
<p>There are two solutions to handle this situation:</p>
<ul>
<li><strong>Scale the data</strong> to make things easy. Transform the x, y and z variables so that their min = 0 and their max = 1</li>
<li><strong>Use c(-max, +max)</strong> as the ranges of the axes</li>
</ul>
<div id="scale-the-data" class="section level2">
<h2>Scale the data</h2>
<pre class="r"><code>x1 <- (x - min(x))/(max(x) - min(x))
y1 <- (y - min(y))/(max(y) - min(y))
z1 <- (z - min(z))/(max(z) - min(z))</code></pre>
<pre class="r"><code># Make a scatter plot
rgl_init()
rgl.spheres(x1, y1, z1, r = 0.02, color = "yellow") 
# Add x, y, and z Axes
rgl.lines(c(0, 1), c(0, 0), c(0, 0), color = "black")
rgl.lines(c(0, 0), c(0,1), c(0, 0), color = "red")
rgl.lines(c(0, 0), c(0, 0), c(0,1), color = "green")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/rgl-axis-lines-labels-1-r-data-visualization-1.png" title="RGL - R software and data visualization" alt="RGL - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
</div>
<div id="use-c-max-max" class="section level2">
<h2>Use c(-max, max)</h2>
<p>Let’s define a helper function to calculate the axis limits:</p>
<pre class="r"><code>lim <- function(x){c(-max(abs(x)), max(abs(x))) * 1.1}</code></pre>
<pre class="r"><code># Make a scatter plot
rgl_init()
rgl.spheres(x, y, z, r = 0.2, color = "yellow") 
# Add x, y, and z Axes
rgl.lines(lim(x), c(0, 0), c(0, 0), color = "black")
rgl.lines(c(0, 0), lim(y), c(0, 0), color = "red")
rgl.lines(c(0, 0), c(0, 0), lim(z), color = "green")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/rgl-axis-lines-2-r-data-visualization-1.png" title="RGL - R software and data visualization" alt="RGL - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
</div>
<div id="rgl_add_axes-a-custom-function-to-add-x-y-and-z-axes" class="section level2">
<h2>rgl_add_axes(): A custom function to add x, y and z axes</h2>
<pre class="r"><code># x, y, z : numeric vectors corresponding to
#  the coordinates of points
# axis.col : axis colors
# xlab, ylab, zlab: axis labels
# show.plane : add axis planes
# show.bbox : add the bounding box decoration
# bbox.col: the bounding box colors. The first color is the
# the background color; the second color is the color of tick marks
rgl_add_axes <- function(x, y, z, axis.col = "grey",
                xlab = "", ylab="", zlab="", show.plane = TRUE, 
                show.bbox = FALSE, bbox.col = c("#333377","black"))
  { 
  
  lim <- function(x){c(-max(abs(x)), max(abs(x))) * 1.1}
  # Add axes
  xlim <- lim(x); ylim <- lim(y); zlim <- lim(z)
  rgl.lines(xlim, c(0, 0), c(0, 0), color = axis.col)
  rgl.lines(c(0, 0), ylim, c(0, 0), color = axis.col)
  rgl.lines(c(0, 0), c(0, 0), zlim, color = axis.col)
  
   # Add a point at the end of each axes to specify the direction
   axes <- rbind(c(xlim[2], 0, 0), c(0, ylim[2], 0), 
                 c(0, 0, zlim[2]))
   rgl.points(axes, color = axis.col, size = 3)
  
  # Add axis labels
  rgl.texts(axes, text = c(xlab, ylab, zlab), color = axis.col,
             adj = c(0.5, -0.8), size = 2)
  
  # Add plane
  if(show.plane) 
    xlim <- xlim/1.1; zlim <- zlim /1.1
    rgl.quads( x = rep(xlim, each = 2), y = c(0, 0, 0, 0),
             z = c(zlim[1], zlim[2], zlim[2], zlim[1]))
  
  # Add bounding box decoration
  if(show.bbox){
    rgl.bbox(color=c(bbox.col[1],bbox.col[2]), alpha = 0.5, 
          emission=bbox.col[1], specular=bbox.col[1], shininess=5, 
          xlen = 3, ylen = 3, zlen = 3) 
  }
}</code></pre>
<br/>
<div class="block">
<ul>
<li>The function <strong>rgl.texts(x, y, z, text )</strong> is used to add texts to an <strong>RGL plot</strong>.</li>
<li><strong>rgl.quads(x, y, z)</strong> is used to add planes. x, y and z are numeric vectors of length four specifying the coordinates of the four nodes of the quad.</li>
</ul>
</div>
<p><br/></p>
<pre class="r"><code>rgl_init()
rgl.spheres(x, y, z, r = 0.2, color = "yellow") 
rgl_add_axes(x, y, z)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/rgl-add-axes-r-data-visualization-1.png" title="RGL - R software and data visualization" alt="RGL - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
</div>
<div id="show-scales-tick-marks" class="section level2">
<h2>Show scales: tick marks</h2>
<p>The function <strong>axis3d()</strong> can be used as follow:</p>
<pre class="r"><code>rgl_init()
rgl.spheres(x, y, z, r = 0.2, color = "yellow") 
rgl_add_axes(x, y, z)
# Show tick marks
axis3d(&amp;#39;x&amp;#39;, pos=c( NA, 0, 0 ), col = "darkgrey")
axis3d(&amp;#39;y&amp;#39;, pos=c( 0, NA, 0 ), col = "darkgrey")
axis3d(&amp;#39;z&amp;#39;, pos=c( 0, 0, NA ), col = "darkgrey")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/rgl-scales-r-data-visualization-1.png" title="RGL - R software and data visualization" alt="RGL - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
<p>It’s easier to just add a bounding box decoration:</p>
<pre class="r"><code>rgl_init()
rgl.spheres(x, y, z, r = 0.2, color = "yellow") 
rgl_add_axes(x, y, z, show.bbox = TRUE)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/rgl-scales-r-data-2-visualization-1.png" title="RGL - R software and data visualization" alt="RGL - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
</div>
</div>
<div id="set-the-aspect-ratios-of-the-x-y-and-z-axes" class="section level1">
<h1>Set the aspect ratios of the x, y and z axes</h1>
<p><span class="success">In the plot above, the bounding box is displayed as rectangle. All the coordinates are displayed at the same scale (<em>iso-metric</em>).</span></p>
<p>The function <strong>aspect3d(x, y = NULL, z = NULL)</strong> can be used to set the apparent ratios of the x, y and z axes for the current plot.</p>
<p>x, y and z are the ratio for x, y and z axes, respectively. x can be a vector of length 3, specifying the ratio for the 3 axes.</p>
<p><span class="success">If the ratios are (1, 1, 1), the bounding box will be displayed as a cube.</span></p>
<pre class="r"><code>rgl_init()
rgl.spheres(x, y, z, r = 0.2, color = "yellow") 
rgl_add_axes(x, y, z, show.bbox = TRUE)
aspect3d(1,1,1)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/rgl-aspect-ratio-data-visualization-1.png" title="RGL - R software and data visualization" alt="RGL - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
<p><span class="warning">Note that, the default display corresponds to the aspect “iso”: <em>aspect3d(“iso”).</em></span></p>
<p>The values of the ratios can be set larger or smaller to zoom on a given axis:</p>
<pre class="r"><code>rgl_init()
rgl.spheres(x, y, z, r = 0.2, color = "yellow") 
rgl_add_axes(x, y, z, show.bbox = TRUE)
aspect3d(2,1,1) # zoom on x axis</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/rgl-aspect-ratio-2-data-visualization-1.png" title="RGL - R software and data visualization" alt="RGL - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
</div>
<div id="change-the-color-of-points-by-groups" class="section level1">
<h1>Change the color of points by groups</h1>
<p>A helper function can be used to select automatically a color for each group:</p>
<pre class="r"><code>#&amp;#39; Get colors for the different levels of 
#&amp;#39; a factor variable
#&amp;#39; 
#&amp;#39; @param groups a factor variable containing the groups
#&amp;#39;  of observations
#&amp;#39; @param colors a vector containing the names of 
#   the default colors to be used
get_colors <- function(groups, group.col = palette()){
  groups <- as.factor(groups)
  ngrps <- length(levels(groups))
  if(ngrps > length(group.col)) 
    group.col <- rep(group.col, ngrps)
  color <- group.col[as.numeric(groups)]
  names(color) <- as.vector(groups)
  return(color)
}</code></pre>
<p>Change colors by groups :</p>
<pre class="r"><code>rgl_init()
rgl.spheres(x, y, z, r = 0.2, 
          color = get_colors(iris$Species)) 
rgl_add_axes(x, y, z, show.bbox = TRUE)
aspect3d(1,1,1)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/rgl-color-by-groups-r-data-visualization-1.png" title="RGL - R software and data visualization" alt="RGL - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
<p>Use custom colors:</p>
<pre class="r"><code>cols <- get_colors(iris$Species, c("#999999", "#E69F00", "#56B4E9"))
rgl_init()
rgl.spheres(x, y, z, r = 0.2, color = cols) 
rgl_add_axes(x, y, z, show.bbox = TRUE)
aspect3d(1,1,1)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/rgl-custom-color-by-groups-r-data-visualization-1.png" title="RGL - R software and data visualization" alt="RGL - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
<p>It’s also possible to use color palettes from the <strong>RColorBrewer</strong> package:</p>
<pre class="r"><code>library("RColorBrewer")
cols <- get_colors(iris$Species, brewer.pal(n=3, name="Dark2") )
rgl_init()
rgl.spheres(x, y, z, r = 0.2, color = cols) 
rgl_add_axes(x, y, z, show.bbox = TRUE)
aspect3d(1,1,1)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/rgl-rcolorbrewer-color-by-groups-r-data-visualization-1.png" title="RGL - R software and data visualization" alt="RGL - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
<p>Read more about colors in R: <a href="https://www.sthda.com/english/english/wiki/colors-in-r">colors in R</a></p>
</div>
<div id="change-the-shape-of-points-1" class="section level1">
<h1>Change the shape of points</h1>
<p>6 mesh objects are available in RGL package and can be used as point shapes:</p>
<ul>
<li><strong>cube3d()</strong></li>
<li><strong>tetrahedron3d()</strong></li>
<li><strong>octahedron3d()</strong></li>
<li><strong>icosahedron3d()</strong></li>
<li><strong>dodecahedron3d()</strong></li>
<li><strong>cuboctahedron3d()</strong></li>
</ul>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/rgl-rgl-mesh-objects-1.png" title="RGL - R software and data visualization" alt="RGL - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
<p>To make a plot using the objects above, the function <strong>shapelist3d()</strong> can be used as follow:</p>
<pre class="r"><code>shapelist3d(shapes, x, y, z)</code></pre>
<br/>
<div class="block">
<ul>
<li><strong>shapes</strong>: a single shape3d (ex: shapes = cube3d()) object or a list of them (ex: shapes = list(cube3d(), icosahedron3d()))</li>
<li><strong>x, y, z</strong>: the coordinates of the points to be plotted</li>
</ul>
</div>
<p><br/></p>
<pre class="r"><code>rgl_init()
shapelist3d(tetrahedron3d(), x, y, z, size =  0.15, 
            color = get_colors(iris$Species))
rgl_add_axes(x, y, z, show.bbox = TRUE)
aspect3d(1,1,1)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/rgl-shape-color-by-groups-r-data-visualization-1.png" title="RGL - R software and data visualization" alt="RGL - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
</div>
<div id="add-an-ellipse-of-concentration" class="section level1">
<h1>Add an ellipse of concentration</h1>
<p>The function <strong>ellipse3d()</strong> is used to estimate the ellipse of concentration. A simplified format is:</p>
<pre class="r"><code>ellipse3d(x, scale = c(1,1,1), centre = c(0,0,0), 
          level = 0.95, ...)</code></pre>
<br/>
<div class="block">
<ul>
<li><strong>x</strong>: the correlation or covariance matrix between x, y and z</li>
<li><strong>scale</strong>: If x is a correlation matrix, then the standard deviations of each parameter can be given in the scale parameter. This defaults to c(1, 1, 1), so no rescaling will be done.</li>
<li><strong>centre</strong>: The center of the ellipse will be at this position.</li>
<li><strong>level</strong>: The confidence level of a confidence region. This is used to control the size of the ellipsoid.</li>
</ul>
</div>
<p><br/></p>
<p><span class="warning">The function <strong>ellipse3d()</strong> returns an object of class <strong>mesh3d</strong> which can be drawn using the function <strong>shade3d()</strong> and/or <strong>wired3d()</strong></span></p>
<ol style="list-style-type: decimal">
<li>Draw the ellipse using the function <strong>shade3d()</strong>:</li>
</ol>
<pre class="r"><code>rgl_init()
rgl.spheres(x, y, z, r = 0.2, color = "#D95F02") 
rgl_add_axes(x, y, z, show.bbox = TRUE)
# Compute and draw the ellipse of concentration
ellips <- ellipse3d(cov(cbind(x,y,z)), 
            centre=c(mean(x), mean(y), mean(z)), level = 0.95)
shade3d(ellips, col = "#D95F02", alpha = 0.1, lit = FALSE)
aspect3d(1,1,1)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/rgl-ellipse-shade3d-r-data-visualization-1.png" title="RGL - R software and data visualization" alt="RGL - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
<ol start="2" style="list-style-type: decimal">
<li>Draw the ellipse using the function <strong>wired3d()</strong>:</li>
</ol>
<pre class="r"><code>rgl_init()
rgl.spheres(x, y, z, r = 0.2, color = "#D95F02") 
rgl_add_axes(x, y, z, show.bbox = TRUE)
# Compute and draw the ellipse of concentration
ellips <- ellipse3d(cov(cbind(x,y,z)), 
            centre=c(mean(x), mean(y), mean(z)), level = 0.95)
wire3d(ellips, col = "#D95F02",  lit = FALSE)
aspect3d(1,1,1)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/rgl-ellipse-wire3d-r-data-visualization-1.png" title="RGL - R software and data visualization" alt="RGL - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
<ol start="3" style="list-style-type: decimal">
<li>Combine <strong>shade3d()</strong> and <strong>wired3d()</strong>:</li>
</ol>
<pre class="r"><code>rgl_init()
rgl.spheres(x, y, z, r = 0.2, color = "#D95F02") 
rgl_add_axes(x, y, z, show.bbox = TRUE)
# Compute and draw the ellipse of concentration
ellips <- ellipse3d(cov(cbind(x,y,z)), 
            centre=c(mean(x), mean(y), mean(z)), level = 0.95)
shade3d(ellips, col = "#D95F02", alpha = 0.1, lit = FALSE)
wire3d(ellips, col = "#D95F02",  lit = FALSE)
aspect3d(1,1,1)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/rgl-ellipse-wire3d-shade3d-r-data-visualization-1.png" title="RGL - R software and data visualization" alt="RGL - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
<ol start="4" style="list-style-type: decimal">
<li><strong>Add ellipse for each group</strong>:</li>
</ol>
<pre class="r"><code># Groups
groups <- iris$Species
levs <- levels(groups)
group.col <- c("red", "green", "blue")
# Plot observations
rgl_init()
rgl.spheres(x, y, z, r = 0.2,
            color = group.col[as.numeric(groups)]) 
rgl_add_axes(x, y, z, show.bbox = FALSE)
# Compute ellipse for each group
for (i in 1:length(levs)) {
    group <- levs[i]
    selected <- groups == group
    xx <- x[selected]; yy <- y[selected]; zz <- z[selected]
    ellips <- ellipse3d(cov(cbind(xx,yy,zz)), 
              centre=c(mean(xx), mean(yy), mean(zz)), level = 0.95) 
    shade3d(ellips, col = group.col[i], alpha = 0.1, lit = FALSE) 
    # show group labels
    texts3d(mean(xx),mean(yy), mean(zz), text = group,
            col= group.col[i], cex = 2)
  }
aspect3d(1,1,1)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/rgl-ellipse-per-group-r-data-visualization-1.png" title="RGL - R software and data visualization" alt="RGL - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
</div>
<div id="regression-plane" class="section level1">
<h1>Regression plane</h1>
<p>The function <strong>planes3d()</strong> or <strong>rgl.planes()</strong> can be used to add regression plane into 3D rgl plot:</p>
<pre class="r"><code>rgl.planes(a, b = NULL, c = NULL, d = 0, ...)

planes3d(a, b = NULL, c = NULL, d = 0, ...)</code></pre>
<p><strong>planes3d()</strong> and <strong>rgl.planes()</strong> draw planes using the parameter <em>ax + by + cz + d = 0</em>.</p>
<ul>
<li><strong>a, b, c</strong>: coordinates of the normal to the plane</li>
<li><strong>d</strong>: coordinates of the offset</li>
</ul>
<p>Example of usage:</p>
<pre class="r"><code>rgl_init()
rgl.spheres(x, y, z, r = 0.2, color = "#D95F02") 
rgl_add_axes(x, y, z, show.bbox = FALSE)
aspect3d(1,1,1)
# Linear model
fit <- lm(z ~ x + y)
coefs <- coef(fit)
a <- coefs["x"]; b <- coefs["y"]; c <- -1
d <- coefs["(Intercept)"]
rgl.planes(a, b, c, d, alpha=0.2, color = "#D95F02")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/rgl-plane3d-r-data-visualization-1.png" title="RGL - R software and data visualization" alt="RGL - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
<p>The regression plane above is very ugly. Let’s try to do a custom one. The steps below are followed:</p>
<ol style="list-style-type: decimal">
<li>Use the function <em>lm()</em> to compute a linear regression model: <em>ax + by + cz + d = 0</em></li>
<li>Use the argument <strong>rgl.surface()</strong> to add a regression surface.</li>
</ol>
<pre class="r"><code>rgl_init()
rgl.spheres(x, y, z, r = 0.2, color = "#D95F02") 
rgl_add_axes(x, y, z, show.bbox = FALSE)
aspect3d(1,1,1)
# Compute the linear regression (y = ax + bz + d)
fit <- lm(y ~ x + z)
# predict values on regular xz grid
grid.lines = 26
x.pred <- seq(min(x), max(x), length.out = grid.lines)
z.pred <- seq(min(z), max(z), length.out = grid.lines)
xz <- expand.grid( x = x.pred, z = z.pred)
y.pred <- matrix(predict(fit, newdata = xz), 
                 nrow = grid.lines, ncol = grid.lines)
# Add regression surface
rgl.surface(x.pred, z.pred, y.pred, color = "steelblue", 
                alpha = 0.5, lit = FALSE)  
# Add grid lines
rgl.surface(x.pred, z.pred, y.pred, color = "black",
    alpha = 0.5, lit = FALSE, front = "lines", back = "lines")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/rgl-rgl-surface-r-data-visualization-1.png" title="RGL - R software and data visualization" alt="RGL - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
</div>
<div id="create-a-movie-of-rgl-scene" class="section level1">
<h1>Create a movie of RGL scene</h1>
<p>The function <strong>movie3d()</strong> can be used as follow:</p>
<pre class="r"><code>movie3d(f, duration, dir = tempdir(), convert = TRUE)</code></pre>
<ul>
<li><strong>f</strong> a function created using <strong>spin3d(axis)</strong></li>
<li><strong>axis</strong>: the desired axis of rotation. Default value is c(0, 0, 1).</li>
<li><strong>duration</strong> : the duration of the animation</li>
<li><strong>dir</strong>: A directory in which to create temporary files for each frame of the movie</li>
<li><strong>convert</strong>: If TRUE, tries to convert the frames to a single GIF movie. It uses <strong>ImageMagick</strong> for the image conversion.</li>
</ul>
<p><span class="warning">You should install <em>ImageMagick</em> (<a href="http://www.imagemagick.org/">http://www.imagemagick.org/</a>) to be able to create a movie from a list of png file.</span></p>
<pre class="r"><code>rgl_init()
rgl.spheres(x, y, z, r = 0.2, color = "#D95F02") 
rgl_add_axes(x, y, z, show.bbox = TRUE)
# Compute and draw the ellipse of concentration
ellips <- ellipse3d(cov(cbind(x,y,z)), 
            centre=c(mean(x), mean(y), mean(z)), level = 0.95)
wire3d(ellips, col = "#D95F02",  lit = FALSE)
aspect3d(1,1,1)
# Create a movie
movie3d(spin3d(axis = c(0, 0, 1)), duration = 3,
        dir = getwd())</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/images/rgl-movie3d.gif" alt="RGL movie 3d" /></p>
</div>
<div id="export-images-as-png-or-pdf" class="section level1">
<h1>Export images as png or pdf</h1>
<p>The plot can be saved as png or pdf.</p>
<ul>
<li>The function <strong>rgl.snapshot()</strong> is used to save the screenshot as png file:</li>
</ul>
<pre class="r"><code>rgl.snapshot(filename = "plot.png")</code></pre>
<ul>
<li>The function <strong>rgl.postscript()</strong> is used to save the screenshot to a file in <strong>ps, eps, tex, pdf, svg or pgf</strong> format:</li>
</ul>
<pre class="r"><code>rgl.postscript("plot.pdf",fmt="pdf")</code></pre>
<p>Example of usage:</p>
<pre class="r"><code>rgl_init()
rgl.spheres(x, y, z, r = 0.2, color = "#D95F02") 
rgl_add_axes(x, y, z, show.bbox = T)
aspect3d(1,1,1)
rg.snapshot("plot.png")</code></pre>
</div>
<div id="export-the-plot-into-an-interactive-html-file" class="section level1">
<h1>Export the plot into an interactive HTML file</h1>
<p>The function <strong>writeWebGL()</strong> is used to write the current scene to HTML:</p>
<pre class="r"><code>writeWebGL(dir = "webGL", filename = file.path(dir, "index.html"))</code></pre>
<ul>
<li><strong>dir</strong>: Where to write the files</li>
<li><strong>filename</strong>: The file name to use for the main file</li>
</ul>
<p>The R code below, writes a copy of the scene and then displays it in a browser:</p>
<pre class="r"><code>rgl_init()
rgl.spheres(x, y, z, r = 0.2, 
          color = get_colors(iris$Species)) 
rgl_add_axes(x, y, z, show.bbox = FALSE)
# This writes a copy into temporary directory &amp;#39;webGL&amp;#39;,
# and then displays it
browseURL(
  paste("file://", writeWebGL(dir=file.path(tempdir(), "webGL"), 
  width=500), sep="")
  )</code></pre>
</div>
<div id="select-a-rectangle-in-an-rgl-scene" class="section level1">
<h1>Select a rectangle in an RGL scene</h1>
<p>The functions <strong>rgl.select3d()</strong> or <strong>select3d()</strong> can be used to select <strong>3-dimensional</strong> regions.</p>
<p>They return a function f(x, y, z) which tests whether each of the points (x, y, z) is in the selected region.</p>
<p>The R code below, allows the user to select some points, and then redraw them in a different color:</p>
<pre class="r"><code>rgl_init()
rgl.spheres(x, y, z, r = 0.2, color = "#D95F02") 
rgl_add_axes(x, y, z, show.bbox = F)
aspect3d(1,1,1)
# Select a point
 f <- select3d()
 sel <- f(x,y,z) 
rgl.clear("shapes")
# Redraw the points
rgl.spheres(x[!sel],y[!sel], z[!sel], r = 0.2, color = "#D95F02")
rgl.spheres(x[sel],y[sel], z[sel], r = 0.2, color = "green")</code></pre>
</div>
<div id="identify-points-in-a-plot" class="section level1">
<h1>Identify points in a plot</h1>
<p>The function <strong>identify3d()</strong> is used:</p>
<pre class="r"><code>identify3d(x, y = NULL, z = NULL, labels, n)</code></pre>
<br/>
<div class="block">
<ul>
<li><strong>x, y, z</strong> : Numeric vector specifying the coordinates of points. The arguments y and z are optional when:</li>
<li><em>x</em> is a matrix or a data frame containing at least 3 columns which will be used as the x, y and z coordinates.</li>
<li><em>x</em> is a formula of form zvar ~ xvar + yvar (see <strong>?xyz.coords</strong>).</li>
<li><strong>labels</strong> an optional character vector giving labels for points</li>
<li><em>n</em> the maximum number of points to be identified</li>
</ul>
</div>
<p><br/></p>
<p><span class="notice">The function identify3d(), works similarly to the identify function in base graphics.</sapn></p>
<p>The R code below, allow the user to identify 5 points :</p>
<pre class="r"><code>rgl_init()
rgl.spheres(x, y, z, r = 0.2, color = "#D95F02") 
rgl_add_axes(x, y, z, show.bbox = F)
aspect3d(1,1,1)
rgl.material(color = "blue")
identify3d(x, y, z, labels = rownames(iris), n = 5)</code></pre>
<p><span class="warning">Use the right button to select, the middle button to quit.</span></p>
</div>
<div id="r3d-interface" class="section level1">
<h1>R3D Interface</h1>
<p>The <strong>rgl</strong> package also includes a higher level interface called <strong>r3d</strong>. This interface is designed to act more like classic 2D R graphics.</p>
<p><span class="success">The next sections describe how to make 3D graphics using the R3D interface.</span></p>
<div id="d-scatter-plot-1" class="section level2">
<h2>3D Scatter plot</h2>
<p>The function <strong>plot3d()</strong> is used:</p>
<pre class="r"><code>## Default method
plot3d(x, y, z, xlab, ylab, zlab, type = "p", col,  
        size, lwd, radius, add = FALSE, aspect = !add, ...)

## Method for class &amp;#39;mesh3d&amp;#39;
plot3d(x, xlab = "x", ylab = "y", zlab = "z",
       type = c("shade", "wire", "dots"), add = FALSE, ...) 

decorate3d(xlim, ylim, zlim, 
  xlab = "x", ylab = "y", zlab = "z", 
    box = TRUE, axes = TRUE, main = NULL, sub = NULL,
    top = TRUE, aspect = FALSE, expand = 1.03, ...)</code></pre>
<br/>
<div class="block">
<ul>
<li><strong>x, y, z</strong>: vectors of points to be drawn. Any reasonable way of defining the coordinates is acceptable. See the function <strong>xyz.coords</strong> for details</li>
<li><strong>xlab, yab, zlab</strong>: x, y and z axis labels</li>
<li><strong>type</strong>:</li>
<li><strong>For the default method</strong>: Allowed values are: ‘p’ for points, ‘s’ for spheres, ‘l’ for lines, ‘h’ for line segments from z = 0, and ‘n’ for nothing.</li>
<li><strong>For the mesh3d method</strong>, one of ‘shade’, ‘wire’, or ‘dots’</li>
<li><strong>col</strong>: the color to be used for plotted items</li>
<li><strong>size</strong>: size of points</li>
<li><strong>lwd</strong>: the line width for plotted item</li>
<li><strong>radius</strong>: the radius of sphere</li>
<li><strong>add</strong>: whether to add the points to an existing plot</li>
<li><strong>aspect</strong>: either a logical indicating whether to adjust the aspect ratio, or a new ratio</li>
<li><strong>…</strong>: additional parameters which will be passed to par3d, material3d or decorate3d</li>
<li><strong>box, axes</strong>: whether to draw a box and axes.</li>
<li><strong>main, sub</strong>: main title and subtitle</li>
<li><strong>top</strong>: whether to bring the window to the top when done</li>
</ul>
</div>
<p><br/></p>
<p><span class="warning">Note that, it’s recommended to use the function <strong>open3d()</strong> to initialize the *3d interface. However, in the following R code chunks, I’ll continue to use the custom function <strong>rgl_init()</strong>. </span></p>
<p><strong>Draw points</strong>:</p>
<pre class="r"><code>rgl_init()
plot3d(x, y, z, col="blue", type ="p")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/rgl-plot3d-r-data-visualization-1.png" title="RGL - R software and data visualization" alt="RGL - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
<p><strong>Remove the box and draw spheres</strong>:</p>
<pre class="r"><code>rgl_init()
plot3d(x, y, z, col="blue", box = FALSE,
       type ="s", radius = 0.15)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/rgl-spheres-r3d-r-data-visualization-1.png" title="RGL - R software and data visualization" alt="RGL - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
<p><span class="notice">To remove the axes, use the argument <strong>axes = FALSE</strong>.</span></p>
<p><strong>Axis labels</strong>:</p>
<pre class="r"><code>rgl_init()
plot3d(x, y, z, col="blue", box = FALSE,
       type ="s", radius = 0.15, xlab ="Sepal.Length", 
       ylab = "Petal.Length", zlab = "Sepal.Width")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/rgl-plot3d-axis-labels-r-data-visualization-1.png" title="RGL - R software and data visualization" alt="RGL - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
<p><strong>Add ellipse of concentration:</strong></p>
<pre class="r"><code>rgl_init()
plot3d(x, y, z, col="blue", box = FALSE,
       type ="s", radius = 0.15)
ellips <- ellipse3d(cov(cbind(x,y,z)), 
            centre=c(mean(x), mean(y), mean(z)), level = 0.95)
plot3d(ellips, col = "blue", alpha = 0.2, add = TRUE, box = FALSE)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/rgl-plot3d-ellipse-r-data-visualization-1.png" title="RGL - R software and data visualization" alt="RGL - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
<p><strong>Change the ellipse type</strong>: possible values for the argument <strong>type = c(“shade”, “wire”, “dots”)</strong></p>
<pre class="r"><code>rgl_init()
plot3d(x, y, z, col="blue", box = FALSE,
       type ="s", radius = 0.15)
ellips <- ellipse3d(cov(cbind(x,y,z)), 
            centre = c(mean(x), mean(y), mean(z)), level = 0.95)
plot3d(ellips, col = "blue", alpha = 0.5, add = TRUE, type = "wire")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/rgl-plot3d-r3d-ellipse-type-r-data-visualization-1.png" title="RGL - R software and data visualization" alt="RGL - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
<p><strong>bbox3d(): Add bounding box decoration</strong></p>
<pre class="r"><code>rgl_init()
plot3d(x, y, z, col="blue", box = FALSE,
       type ="s", radius = 0.15)
# Add bounding box decoration
rgl.bbox(color=c("#333377","black"), emission="#333377",
         specular="#3333FF", shininess=5, alpha=0.8, nticks = 3 ) 
# Change the axis aspect ratios
aspect3d(1,1,1)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/rgl-plot3d-ellipse-type-r-data-visualization-1.png" title="RGL - R software and data visualization" alt="RGL - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
</div>
<div id="some-important-functions" class="section level2">
<h2>Some important functions</h2>
<ul>
<li><strong>open3d()</strong>: Open a new device</li>
<li><strong>Add a shape to the current scene</strong>:</li>
<li>points3d(x, y, z, …)</li>
<li>lines3d(x, y, z, …)</li>
<li>segments3d(x, y, z, …)</li>
<li>quads3d(x, y, z, …)</li>
<li><strong>texts3d(x, y, z, text)</strong>: Adds text</li>
<li><strong>Draw boxes, axes and other text</strong>:</li>
<li><strong>axes3d()</strong>: Add standard axes</li>
<li><strong>title3d(main, sub, xlab, ylab, zlab)</strong>: Add titles</li>
<li><strong>box3d()</strong>: Draws a box around the plot</li>
<li><strong>mtext3d()</strong>: to put a text in the plot margin(s)</li>
</ul>
</div>
</div>
<div id="rgl-functions" class="section level1">
<h1>RGL functions</h1>
<p>Some important functions for managing RGL device are listed below:</p>
<div id="device-management" class="section level2">
<h2>Device management</h2>
<table>
<thead>
<tr class="header">
<th align="left">Functions</th>
<th align="left">Description</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left">rgl.open()</td>
<td align="left">Opens a new device</td>
</tr>
<tr class="even">
<td align="left">rgl.close()</td>
<td align="left">Closes the current device</td>
</tr>
<tr class="odd">
<td align="left">rgl.cur()</td>
<td align="left">Returns the ID of the active device</td>
</tr>
<tr class="even">
<td align="left">rgl.dev.list()</td>
<td align="left">Returns all device IDs</td>
</tr>
<tr class="odd">
<td align="left">rgl.set(which)</td>
<td align="left">Set a device as active</td>
</tr>
<tr class="even">
<td align="left">rgl.quit()</td>
<td align="left">Shutdown the RGL device system</td>
</tr>
</tbody>
</table>
<p>The equivalents in r3d interface:</p>
</div>
<div id="shape-functions" class="section level2">
<h2>Shape functions</h2>
<p>Adds a shape node to the current scene.</p>
<table>
<thead>
<tr class="header">
<th align="left">Functions</th>
<th align="left">Description</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left">rgl.points(x, y, z, …)</td>
<td align="left">Draws a point at x, y and z</td>
</tr>
<tr class="even">
<td align="left">rgl.lines(x, y, z, …)</td>
<td align="left">Draws line segments based on pairs of vertices (x = c(x1,x2), y = c(y1,y2), z = c(z1, z2))</td>
</tr>
<tr class="odd">
<td align="left">rgl.triangles(x, y, z, …)</td>
<td align="left">Draws triangles with nodes (xi, yi, zi), i = 1, 2, 3</td>
</tr>
<tr class="even">
<td align="left">rgl.quads(x, y, z)</td>
<td align="left">Draws quads with nodes (xi, yi, zi), i = 1, 2, 3, 4</td>
</tr>
<tr class="odd">
<td align="left">rgl.spheres(x, y, z, r, …)</td>
<td align="left">Draws spheres with center (x, y, z) and radius r</td>
</tr>
<tr class="even">
<td align="left">rgl.texts(x, y, z, text, …)</td>
<td align="left">Adds text to the scene</td>
</tr>
<tr class="odd">
<td align="left">rgl.surface(x, y, z, …)</td>
<td align="left">Adds surface to the current scene. x and y are two vectors defining the grid. z is a matrix defining the height of each grid point</td>
</tr>
</tbody>
</table>
</div>
<div id="scene-management" class="section level2">
<h2>Scene management</h2>
<table>
<thead>
<tr class="header">
<th align="left">Functions</th>
<th align="left">Description</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left">rgl.clear(type = “shapes”)</td>
<td align="left">Clears the scene from the specified stack (“shapes”, “lights”, “bboxdeco”, “background”)</td>
</tr>
<tr class="even">
<td align="left">rgl.pop(type = “shapes”)</td>
<td align="left">removes the last-added node from stack</td>
</tr>
</tbody>
</table>
</div>
<div id="setup-the-environment" class="section level2">
<h2>Setup the environment</h2>
<table>
<thead>
<tr class="header">
<th align="left">Functions</th>
<th align="left">Description</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left">rgl.viewpoint(theta, phi, fov, zoom, …)</td>
<td align="left">Set the viewpoint orientation. <em>theta</em> and <em>phi</em> are the polar coordinates. <em>fov</em> is the field-of-view angle in degrees. <em>zoom</em>: zoom factor.</td>
</tr>
<tr class="even">
<td align="left">rgl.light(theta, phi, …)</td>
<td align="left">Adds a light source to the scene</td>
</tr>
<tr class="odd">
<td align="left">rgl.bg(…)</td>
<td align="left">Setup the background environment of the scene</td>
</tr>
<tr class="even">
<td align="left">rgl.bbox(…)</td>
<td align="left">Setup the bounding box decoration</td>
</tr>
</tbody>
</table>
</div>
<div id="appearance-setup" class="section level2">
<h2>Appearance setup</h2>
<table>
<thead>
<tr class="header">
<th align="left">Functions</th>
<th align="left">Description</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left">rgl.material(…)</td>
<td align="left">Set material properties for geometry appearance</td>
</tr>
<tr class="even">
<td align="left">aspect3d(x, y, z)</td>
<td align="left">Set the aspect ratios of the x, y and z axes</td>
</tr>
</tbody>
</table>
</div>
<div id="export-screenshot" class="section level2">
<h2>Export screenshot</h2>
<table>
<thead>
<tr class="header">
<th align="left">Functions</th>
<th align="left">Description</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left">rgl.snapshot(“plot.png”)</td>
<td align="left">Saves a screenshot as png file</td>
</tr>
<tr class="even">
<td align="left">rgl.postscript(“plot.pdf”,fmt=“pdf”)</td>
<td align="left">Saves the screenshot to a file in <strong>ps, eps, tex, pdf, svg or pgf</strong> format.</td>
</tr>
</tbody>
</table>
</div>
<div id="assign-focus-to-an-rgl-window" class="section level2">
<h2>Assign focus to an RGL window</h2>
<p><strong>Rgl.bringtotop()</strong>: ‘rgl.bringtotop’ brings the current RGL window to the front of the window stack (and gives it focus).</p>
</div>
</div>
<div id="infos" class="section level1">
<h1>Infos</h1>
<p><strong>References</strong>:</p>
<ul>
<li>Daniel Alder et al., RGL: A R-library for 3D visualization with OpenGL, <a href="http://rgl.neoscientists.org/arc/doc/RGL_INTERFACE03.pdf">http://rgl.neoscientists.org/arc/doc/RGL_INTERFACE03.pdf</a></li>
</ul>
<p><span class="warning"> This analysis has been performed using <strong>R software</strong> (ver. 3.1.2) and <strong>rgl</strong> (ver. 0.93.1098) </span></p>
</div>

<script>jQuery(document).ready(function () {
    jQuery('h1').addClass('wiki_paragraph1');
    jQuery('h2').addClass('wiki_paragraph2');
    jQuery('h3').addClass('wiki_paragraph3');
    jQuery('h4').addClass('wiki_paragraph4');
    });//add phpboost class to header</script>
<style>.content{padding:0px;}</style>
</div><!--end rdoc-->
<!--====================== stop here when you copy to sthda================-->


<!-- END HTML -->]]></description>
			<pubDate>Wed, 15 Apr 2015 22:17:33 +0200</pubDate>
			
		</item>
		
		<item>
			<title><![CDATA[Amazing interactive 3D scatter plots - R software and data visualization]]></title>
			<link>https://www.sthda.com/english/wiki/amazing-interactive-3d-scatter-plots-r-software-and-data-visualization</link>
			<guid>https://www.sthda.com/english/wiki/amazing-interactive-3d-scatter-plots-r-software-and-data-visualization</guid>
			<description><![CDATA[<!-- START HTML -->

  <!--====================== start from here when you copy to sthda================-->  
  <div id="rdoc">


<div id="TOC">
<ul>
<li><a href="#install-and-load-required-packages">Install and load required packages</a></li>
<li><a href="#prepare-the-data">Prepare the data</a></li>
<li><a href="#the-function-scatter3d">The function scatter3d</a></li>
<li><a href="#basic-3d-scatter-plots">Basic 3D scatter plots</a></li>
<li><a href="#plot-the-points-by-groups">Plot the points by groups</a><ul>
<li><a href="#default-plot">Default plot</a></li>
<li><a href="#remove-the-surfaces">Remove the surfaces</a></li>
<li><a href="#add-concentration-ellipsoids">Add concentration ellipsoids</a></li>
<li><a href="#change-point-colors-by-groups">Change point colors by groups</a></li>
</ul></li>
<li><a href="#axes">Axes</a><ul>
<li><a href="#change-axis-labels">Change axis labels:</a></li>
<li><a href="#remove-axis-scales">Remove axis scales</a></li>
<li><a href="#change-axis-colors">Change axis colors</a></li>
</ul></li>
<li><a href="#add-text-labels-for-the-points">Add text labels for the points</a></li>
<li><a href="#export-images">Export images</a></li>
<li><a href="#see-also">See also</a></li>
<li><a href="#infos">Infos</a></li>
</ul>
</div>

<p><br/></p>
<p>I recently posted an article describing how to make easily a 3D scatter plot in <strong>R</strong> using the package <a href="https://www.sthda.com/english/english/wiki/scatterplot3d-3d-graphics-r-software-and-data-visualization"><strong>scatterplot3d</strong></a>.</p>
<p>This <strong>R tutorial</strong> describes how to perform an <strong>interactive</strong> <strong>3d graphics</strong> using <strong>R software</strong> and the function <strong>scatter3d</strong> from the package <strong>car</strong>.</p>
<p><span class="success">The function <strong>scatter3d()</strong> uses the <strong>rgl</strong> package to draw and animate <strong>3D scatter plots</strong>.</span></p>
<p><img src="https://www.sthda.com/english/sthda/RDoc/images/rgl-scatter3d.gif" alt="3d scatter plot rgl" /></p>
<div id="install-and-load-required-packages" class="section level1">
<h1>Install and load required packages</h1>
<p>The packages <strong>rgl</strong> and <strong>car</strong> are required for this tutorial:</p>
<pre class="r"><code>install.packages(c("rgl", "car"))</code></pre>
<br/>
<div class="warning">
<p>Note that, on Linux operating system, the <strong>rgl</strong> package can be installed as follow:</p>
<p><strong>sudo apt-get install r-cran-rgl</strong></p>
</div>
<p><br/></p>
<p>Load the packages:</p>
<pre class="r"><code>library("car")</code></pre>
</div>
<div id="prepare-the-data" class="section level1">
<h1>Prepare the data</h1>
<p>We’ll use the <em>iris</em> data set in the following examples :</p>
<pre class="r"><code>data(iris)
head(iris)</code></pre>
<pre><code>  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa</code></pre>
<pre class="r"><code>sep.l <- iris$Sepal.Length
sep.w <- iris$Sepal.Width
pet.l <- iris$Petal.Length</code></pre>
<p><span class="notice"><em>iris</em> 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.</span></p>
</div>
<div id="the-function-scatter3d" class="section level1">
<h1>The function scatter3d</h1>
<p>The simplified formats are:</p>
<pre class="r"><code>scatter3d(formula, data)

scatter3d(x, y, z)</code></pre>
<br/>
<div class="block">
<ul>
<li><strong>x, y, z</strong> are respectively the coordinates of points to be plotted. The arguments <em>y</em> and <em>z</em> can be optional depending on the structure of <em>x</em>.</li>
<li><strong>formula</strong>: a model formula of form <strong>y ~ x + z</strong>. If you want to plot the points by groups, you can use <strong>y ~ x + z | g</strong> where <em>g</em> is a factor dividing the data into groups</li>
<li><strong>data</strong>: data frame within which to evaluate the formula</li>
</ul>
</div>
<p><br/></p>
</div>
<div id="basic-3d-scatter-plots" class="section level1">
<h1>Basic 3D scatter plots</h1>
<pre class="r"><code>library(car)
# 3D plot with the regression plane
scatter3d(x = sep.l, y = pet.l, z = sep.w)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/scatter3d-example-scatter3d-r-data-visualization-1.png" title="Scatter3d - R software and data visualization" alt="Scatter3d - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
<p><span class="warning">Note that, the plot can be manually rotated by holding down on the mouse or touchpad. It can be also zoomed using the scroll wheel on a mouse or pressing ctrl + using the touchpad on a PC or two fingers (up or down) on a mac.</span></p>
<p><strong>Change point colors and remove the regression surface</strong>:</p>
<pre class="r"><code>scatter3d(x = sep.l, y = pet.l, z = sep.w,
        point.col = "blue", surface=FALSE)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/scatter3d-change-point-color-r-data-visualization-1.png" title="Scatter3d - R software and data visualization" alt="Scatter3d - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
</div>
<div id="plot-the-points-by-groups" class="section level1">
<h1>Plot the points by groups</h1>
<div id="default-plot" class="section level2">
<h2>Default plot</h2>
<pre class="r"><code>scatter3d(x = sep.l, y = pet.l, z = sep.w, groups = iris$Species)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/scatter3d-groups-r-data-visualization-1.png" title="Scatter3d - R software and data visualization" alt="Scatter3d - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
</div>
<div id="remove-the-surfaces" class="section level2">
<h2>Remove the surfaces</h2>
<ul>
<li>To <strong>remove the grids</strong> only, the argument <strong>grid = FALSE</strong> can be used as follow:</li>
</ul>
<pre class="r"><code>scatter3d(x = sep.l, y = pet.l, z = sep.w, groups = iris$Species,
          grid = FALSE)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/scatter3d-remove-grid-r-data-visualization-1.png" title="Scatter3d - R software and data visualization" alt="Scatter3d - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
<p><span class="warning">Note that, the display of the surface(s) can be changed using the argument <strong>fit</strong>. Possible values for <em>fit</em> are <strong>“linear”</strong>, <strong>“quadratic”</strong>, <strong>“smooth”</strong> and <strong>“additive”</strong></span></p>
<pre class="r"><code>scatter3d(x = sep.l, y = pet.l, z = sep.w, groups = iris$Species,
          grid = FALSE, fit = "smooth")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/scatter3d-smooth-r-data-visualization-1.png" title="Scatter3d - R software and data visualization" alt="Scatter3d - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
<ul>
<li><strong>Remove surfaces</strong>. The argument <strong>surface = FALSE</strong> is used.</li>
</ul>
<pre class="r"><code>scatter3d(x = sep.l, y = pet.l, z = sep.w, groups = iris$Species,
          grid = FALSE, surface = FALSE)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/scatter3d-remove-surface-r-data-visualization-1.png" title="Scatter3d - R software and data visualization" alt="Scatter3d - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
</div>
<div id="add-concentration-ellipsoids" class="section level2">
<h2>Add concentration ellipsoids</h2>
<pre class="r"><code>scatter3d(x = sep.l, y = pet.l, z = sep.w, groups = iris$Species,
          surface=FALSE, ellipsoid = TRUE)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/scatter3d-add-ellipsoid-r-data-visualization-1.png" title="Scatter3d - R software and data visualization" alt="Scatter3d - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
<p>Remove the grids from the ellipsoids:</p>
<pre class="r"><code>scatter3d(x = sep.l, y = pet.l, z = sep.w, groups = iris$Species,
          surface=FALSE, grid = FALSE, ellipsoid = TRUE)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/scatter3d-remove-grid-ellipsoid-r-data-visualization-1.png" title="Scatter3d - R software and data visualization" alt="Scatter3d - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
</div>
<div id="change-point-colors-by-groups" class="section level2">
<h2>Change point colors by groups</h2>
<p>The argument <strong>surface.col</strong> is used. <strong>surface.col</strong> is a vector of colors for the regression planes.</p>
<p>For <strong>multi-group plots</strong>, the colors are used for the regression surfaces and for the points in the several groups.</p>
<pre class="r"><code>scatter3d(x = sep.l, y = pet.l, z = sep.w, groups = iris$Species,
          surface=FALSE, grid = FALSE, ellipsoid = TRUE,
          surface.col = c("#999999", "#E69F00", "#56B4E9"))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/scatter3d-color-by-groups-r-data-visualization-1.png" title="Scatter3d - R software and data visualization" alt="Scatter3d - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
<p>Read more about colors in R: <a href="https://www.sthda.com/english/english/wiki/colors-in-r">colors in R</a></p>
<p>It’s also possible to use color palettes from the <strong>RColorBrewer</strong> package:</p>
<pre class="r"><code>library("RColorBrewer")
colors <- brewer.pal(n=3, name="Dark2")
scatter3d(x = sep.l, y = pet.l, z = sep.w, groups = iris$Species,
          surface=FALSE, grid = FALSE, ellipsoid = TRUE,
          surface.col = colors)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/scatter3d-rcolorbrewe-r-data-visualizationr-1.png" title="Scatter3d - R software and data visualization" alt="Scatter3d - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
</div>
</div>
<div id="axes" class="section level1">
<h1>Axes</h1>
<div id="change-axis-labels" class="section level2">
<h2>Change axis labels:</h2>
<p>The arguments <strong>xlab</strong>, <strong>ylab</strong> and <strong>zlab</strong> are used:</p>
<pre class="r"><code>scatter3d(x = sep.l, y = pet.l, z = sep.w,
        point.col = "blue", surface=FALSE,
        xlab = "Sepal Length (cm)", ylab = "Petal Length (cm)",
        zlab = "Sepal Width (cm)")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/scatter3d-title-axis-labels-r-data-visualization-1.png" title="Scatter3d - R software and data visualization" alt="Scatter3d - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
</div>
<div id="remove-axis-scales" class="section level2">
<h2>Remove axis scales</h2>
<p><strong>axis.scales = FALSE</strong></p>
<pre class="r"><code>scatter3d(x = sep.l, y = pet.l, z = sep.w,
        point.col = "blue", surface=FALSE, 
        axis.scales = FALSE)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/scatter3d-axis-scales-r-data-visualization-1.png" title="Scatter3d - R software and data visualization" alt="Scatter3d - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
</div>
<div id="change-axis-colors" class="section level2">
<h2>Change axis colors</h2>
<p>By default, different colors are used for the 3 axes. The argument <strong>axis.col</strong> is used to specify colors for the 3 axes:</p>
<pre class="r"><code>scatter3d(x = sep.l, y = pet.l, z = sep.w, groups = iris$Species,
          surface=FALSE, grid = FALSE, ellipsoid = TRUE,
          axis.col = c("black", "black", "black"))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/scatter3d-change-axis-col-r-data-visualization-1.png" title="Scatter3d - R software and data visualization" alt="Scatter3d - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
</div>
</div>
<div id="add-text-labels-for-the-points" class="section level1">
<h1>Add text labels for the points</h1>
<p>The arguments below are used:</p>
<ul>
<li><strong>labels</strong>: text labels for the points, one for each point</li>
<li><strong>id.n</strong>: Number of relatively extreme points to identify automatically</li>
</ul>
<pre class="r"><code>scatter3d(x = sep.l, y = pet.l, z = sep.w, 
          surface=FALSE, labels = rownames(iris), id.n=nrow(iris))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/scatter3d-add-text-labels-r-data-visualization-1.png" title="Scatter3d - R software and data visualization" alt="Scatter3d - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
</div>
<div id="export-images" class="section level1">
<h1>Export images</h1>
<p>The plot can be saved as png or pdf.</p>
<ul>
<li>The function <strong>rgl.snapshot()</strong> is used to save the screenshot as png file:</li>
</ul>
<pre class="r"><code>rgl.snapshot(filename = "plot.png")</code></pre>
<ul>
<li>The function <strong>rgl.postscript()</strong> is used to saves the screenshot to a file in <strong>ps, eps, tex, pdf, svg or pgf</strong> format:</li>
</ul>
<pre class="r"><code>rgl.postscript("plot.pdf",fmt="pdf")</code></pre>
</div>
<div id="see-also" class="section level1">
<h1>See also</h1>
<p>The function <strong>Identify3d()</strong>[ <em>car</em> package] allows to label points interactively with the mouse.</p>
</div>
<div id="infos" class="section level1">
<h1>Infos</h1>
<p><span class="warning"> This analysis has been performed using <strong>R software</strong> (ver. 3.1.2) and <strong>car</strong> (ver. 2.0-25) </span></p>
</div>

<script>jQuery(document).ready(function () {
    jQuery('h1').addClass('wiki_paragraph1');
    jQuery('h2').addClass('wiki_paragraph2');
    jQuery('h3').addClass('wiki_paragraph3');
    jQuery('h4').addClass('wiki_paragraph4');
    });//add phpboost class to header</script>
<style>.content{padding:0px;}</style>
</div><!--end rdoc-->
<!--====================== stop here when you copy to sthda================-->


<!-- END HTML -->]]></description>
			<pubDate>Sun, 12 Apr 2015 19:31:07 +0200</pubDate>
			
		</item>
		
		<item>
			<title><![CDATA[Scatterplot3d: 3D graphics - R software and data visualization]]></title>
			<link>https://www.sthda.com/english/wiki/scatterplot3d-3d-graphics-r-software-and-data-visualization</link>
			<guid>https://www.sthda.com/english/wiki/scatterplot3d-3d-graphics-r-software-and-data-visualization</guid>
			<description><![CDATA[<!-- START HTML -->
<!--====================== start from here when you copy to sthda================-->  
  <div id="rdoc">

<div id="TOC">
<ul>
<li><a href="#install-and-load-scaterplot3d">Install and load scaterplot3d</a></li>
<li><a href="#prepare-the-data">Prepare the data</a></li>
<li><a href="#the-function-scatterplot3d">The function scatterplot3d()</a></li>
<li><a href="#basic-3d-scatter-plots">Basic 3D scatter plots</a></li>
<li><a href="#change-the-main-title-and-axis-labels">Change the main title and axis labels</a></li>
<li><a href="#change-the-shape-and-the-color-of-points">Change the shape and the color of points</a></li>
<li><a href="#change-point-shapes-by-groups">Change point shapes by groups</a></li>
<li><a href="#change-point-colors-by-groups">Change point colors by groups</a></li>
<li><a href="#change-the-global-appearance-of-the-graph">Change the global appearance of the graph</a><ul>
<li><a href="#remove-the-box-around-the-plot">Remove the box around the plot</a></li>
<li><a href="#add-grids-on-scatterplot3d">Add grids on scatterplot3d</a></li>
</ul></li>
<li><a href="#add-bars">Add bars</a></li>
<li><a href="#modification-of-scatterplot3d-output">Modification of scatterplot3d output</a><ul>
<li><a href="#add-legends">Add legends</a><ul>
<li><a href="#specify-the-legend-position-using-xyz.convert">Specify the legend position using xyz.convert()</a></li>
<li><a href="#specify-the-legend-position-using-keywords">Specify the legend position using keywords</a></li>
<li><a href="#customize-the-legend-position">Customize the legend position</a></li>
</ul></li>
<li><a href="#add-point-labels">Add point labels</a></li>
<li><a href="#add-regression-plane-and-supplementary-points">Add regression plane and supplementary points</a></li>
</ul></li>
<li><a href="#infos">Infos</a></li>
</ul>
</div>

<p><br/></p>
<p>There are many packages in R (<em>RGL</em>, <em>car</em>, <em>lattice</em>, <em>scatterplot3d</em>, …) for creating <strong>3D graphics</strong>.</p>
<p>This <strong>tutorial</strong> describes how to generate a scatter pot in the <strong>3D space</strong> using <strong>R software</strong> and the package <strong>scatterplot3d</strong>.</p>
<p><strong>scaterplot3d</strong> is very simple to use and it can be easily extended by adding supplementary points or regression planes into an already generated graphic.</p>
<p>It can be easily installed, as it requires only an installed version of R.</p>
<p><img src="https://www.sthda.com/english/sthda/RDoc/images/scatterplot3d.gif" alt="3d scatter plot" /></p>
<div id="install-and-load-scaterplot3d" class="section level1">
<h1>Install and load scaterplot3d</h1>
<pre class="r"><code>install.packages("scatterplot3d") # Install

library("scatterplot3d") # load</code></pre>
</div>
<div id="prepare-the-data" class="section level1">
<h1>Prepare the data</h1>
<p>The <em>iris</em> data set will be used:</p>
<pre class="r"><code>data(iris)
head(iris)</code></pre>
<pre><code>  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa</code></pre>
<p><span class="notice"><em>iris</em> 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.</span></p>
</div>
<div id="the-function-scatterplot3d" class="section level1">
<h1>The function scatterplot3d()</h1>
<p>A simplified format is:</p>
<pre class="r"><code>scatterplot3d(x, y=NULL, z=NULL)</code></pre>
<p><span class="success">x, y, z are the coordinates of points to be plotted. The arguments <em>y</em> and <em>z</em> can be optional depending on the structure of <em>x</em>.</span></p>
<p><span class="question">In what cases, <em>y</em> and <em>z</em> are optional variables?</span></p>
<ul>
<li><strong>Case 1 : x is a formula</strong> of type <em>zvar ~ xvar + yvar</em>. xvar, yvar and zvar are used as x, y and z variables</li>
<li><strong>Case 2 : x is a matrix</strong> containing at least 3 columns corresponding to x, y and z variables, respectively</li>
</ul>
</div>
<div id="basic-3d-scatter-plots" class="section level1">
<h1>Basic 3D scatter plots</h1>
<pre class="r"><code># Basic 3d graphics
scatterplot3d(iris[,1:3])</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/scatterplot3d-scatter-plot-3d-r-data-visualization-1.png" title="Scatterplot3d - R software and data visualization" alt="Scatterplot3d - R software and data visualization" width="432" style="margin-bottom:10px;" /></p>
<pre class="r"><code># Change the angle of point view
scatterplot3d(iris[,1:3], angle = 55)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/scatterplot3d-scatter-plot-3d-r-data-visualization-2.png" title="Scatterplot3d - R software and data visualization" alt="Scatterplot3d - R software and data visualization" width="432" style="margin-bottom:10px;" /></p>
</div>
<div id="change-the-main-title-and-axis-labels" class="section level1">
<h1>Change the main title and axis labels</h1>
<pre class="r"><code>scatterplot3d(iris[,1:3],
              main="3D Scatter Plot",
              xlab = "Sepal Length (cm)",
              ylab = "Sepal Width (cm)",
              zlab = "Petal Length (cm)")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/scatterplot3d-title-1.png" title="Scatterplot3d - R software and data visualization" alt="Scatterplot3d - R software and data visualization" width="432" style="margin-bottom:10px;" /></p>
</div>
<div id="change-the-shape-and-the-color-of-points" class="section level1">
<h1>Change the shape and the color of points</h1>
<p>The argument <em>pch</em> and <em>color</em> can be used:</p>
<pre class="r"><code>scatterplot3d(iris[,1:3], pch = 16, color="steelblue")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/scatterplot3d-scatter-plot-3d-shape-r-data-visualization-1.png" title="Scatterplot3d - R software and data visualization" alt="Scatterplot3d - R software and data visualization" width="432" style="margin-bottom:10px;" /></p>
<p>Read more on the different point shapes available in R : <a href="https://www.sthda.com/english/english/wiki/r-plot-pch-symbols-the-different-point-shapes-available-in-r">Point shapes in R</a></p>
</div>
<div id="change-point-shapes-by-groups" class="section level1">
<h1>Change point shapes by groups</h1>
<pre class="r"><code>shapes = c(16, 17, 18) 
shapes <- shapes[as.numeric(iris$Species)]
scatterplot3d(iris[,1:3], pch = shapes)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/scatterplot3d-scatter-plot-3d-shape-by-groups-r-data-visualization-1.png" title="Scatterplot3d - R software and data visualization" alt="Scatterplot3d - R software and data visualization" width="432" style="margin-bottom:10px;" /></p>
<p>Read more on the different point shapes available in R : <a href="https://www.sthda.com/english/english/wiki/r-plot-pch-symbols-the-different-point-shapes-available-in-r">Point shapes in R</a></p>
</div>
<div id="change-point-colors-by-groups" class="section level1">
<h1>Change point colors by groups</h1>
<pre class="r"><code>colors <- c("#999999", "#E69F00", "#56B4E9")
colors <- colors[as.numeric(iris$Species)]
scatterplot3d(iris[,1:3], pch = 16, color=colors)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/scatterplot3d-scatter-plot-3d-color-by-groups-r-data-visualization-1.png" title="Scatterplot3d - R software and data visualization" alt="Scatterplot3d - R software and data visualization" width="432" style="margin-bottom:10px;" /></p>
<p>Read more about colors in R: <a href="https://www.sthda.com/english/english/wiki/colors-in-r">colors in R</a></p>
</div>
<div id="change-the-global-appearance-of-the-graph" class="section level1">
<h1>Change the global appearance of the graph</h1>
<p>The arguments below can be used:</p>
<ul>
<li><strong>grid</strong>: a logical value. If TRUE, a grid is drawn on the plot.</li>
<li><strong>box</strong>: a logical value. If TRUE, a box is drawn around the plot</li>
</ul>
<div id="remove-the-box-around-the-plot" class="section level2">
<h2>Remove the box around the plot</h2>
<pre class="r"><code>scatterplot3d(iris[,1:3], pch = 16, color = colors,
              grid=TRUE, box=FALSE)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/scatterplot3d-remove-box-grid-1.png" title="Scatterplot3d - R software and data visualization" alt="Scatterplot3d - R software and data visualization" width="432" style="margin-bottom:10px;" /></p>
<p><span class="warning">Note that, the argument <strong>grid = TRUE</strong> 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.</span></p>
</div>
<div id="add-grids-on-scatterplot3d" class="section level2">
<h2>Add grids on scatterplot3d</h2>
<p>This section describes how to add <em>xy-</em>, <em>xz-</em> and <em>yz-</em> to <strong>scatterplot3d</strong> graphics.</p>
<p>We’ll use a custom function named <strong>addgrids3d()</strong>. The source code is available here : <a href="https://www.sthda.com/sthda/RDoc/functions/addgrids3d.r">addgrids3d.r</a>. The function is inspired from the discussion on this <a href="http://stackoverflow.com/questions/20448539/add-yz-and-xz-grid-to-scatterplot3d">forum</a>.</p>
<p>A simplified format of the function is:</p>
<pre class="r"><code>addgrids3d(x, y=NULL, z=NULL, grid = TRUE,
           col.grid = "grey", lty.grid=par("lty"))</code></pre>
<br/>
<div class="block">
<ul>
<li><strong>x, y, and z</strong> 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</li>
<li><strong>grid</strong> 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.</li>
<li><strong>col.grid, lty.grid</strong>: the color and the line type to be used for grids</li>
</ul>
</div>
<p><br/></p>
<p><strong>Add grids on the different factes of scatterplot3d graphics</strong>:</p>
<pre class="r"><code># 1. Source the function
source('https://www.sthda.com/sthda/RDoc/functions/addgrids3d.r')
# 2. 3D scatter plot
scatterplot3d(iris[, 1:3], pch = 16, grid=FALSE, box=FALSE)
# 3. Add grids
addgrids3d(iris[, 1:3], grid = c("xy", "xz", "yz"))</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/scatterplot3d-add-grids-1.png" title="Scatterplot3d - R software and data visualization" alt="Scatterplot3d - R software and data visualization" width="432" style="margin-bottom:10px;" /></p>
<p><span class="warning">The problem on the above plot is that the grids are drawn over the points.</span></p>
<p>The <strong>R code</strong> below, we’ll put the points in the foreground using the following steps:</p>
<ol style="list-style-type: decimal">
<li>An empty scatterplot3 graphic is created and the result of <strong>scatterplot3d()</strong> is assigned to <em>s3d</em></li>
<li>The function <strong>addgrids3d()</strong> is used to add grids</li>
<li>Finally, the function <strong>s3d$points3d</strong> is used to add points on the 3D scatter plot</li>
</ol>
<pre class="r"><code># 1. Source the function
source('~/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 grids
addgrids3d(iris[, 1:3], grid = c("xy", "xz", "yz"))
# 4. Add points
s3d$points3d(iris[, 1:3], pch = 16)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/scatterplot3d-add-grids2-1.png" title="Scatterplot3d - R software and data visualization" alt="Scatterplot3d - R software and data visualization" width="432" style="margin-bottom:10px;" /></p>
<p><span class="notice">The function <strong>points3d()</strong> is described in the next sections.</span></p>
</div>
</div>
<div id="add-bars" class="section level1">
<h1>Add bars</h1>
<p>The argument <strong>type = “h”</strong> is used. This is useful to see very clearly the x-y location of points.</p>
<pre class="r"><code>scatterplot3d(iris[,1:3], pch = 16, type="h", 
              color=colors)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/scatterplot3d-add-bars-r-data-visualization-1.png" title="Scatterplot3d - R software and data visualization" alt="Scatterplot3d - R software and data visualization" width="432" style="margin-bottom:10px;" /></p>
</div>
<div id="modification-of-scatterplot3d-output" class="section level1">
<h1>Modification of scatterplot3d output</h1>
<p><strong>scatterplot3d</strong> returns a list of function closures which can be used to add elements on a existing plot.</p>
<p>The returned functions are :</p>
<ul>
<li><strong>xyz.convert()</strong>: 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.</li>
<li><strong>points3d()</strong>: to add <em>points</em> or <em>lines</em> into the existing plot</li>
<li><strong>plane3d()</strong>: to add a <em>plane</em> into the existing plot</li>
<li><strong>box3d()</strong>: to add or refresh a <em>box</em> around the plot</li>
</ul>
<div id="add-legends" class="section level2">
<h2>Add legends</h2>
<div id="specify-the-legend-position-using-xyz.convert" class="section level3">
<h3>Specify the legend position using xyz.convert()</h3>
<ol style="list-style-type: decimal">
<li>The result of <strong>scatterplot3d()</strong> is assigned to <em>s3d</em></li>
<li>The function <strong>s3d$xyz.convert()</strong> is used to specify the coordinates for legends</li>
<li>the function <strong>legend()</strong> is used to add legends to plots</li>
</ol>
<pre class="r"><code>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)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/scatterplot3d-add-legend-r-data-visualization-1.png" title="Scatterplot3d - R software and data visualization" alt="Scatterplot3d - R software and data visualization" width="432" style="margin-bottom:10px;" /></p>
<br/>

<div class="block">
<p>It’s also possible to specify the <strong>position of legends</strong> using the following keywords: “bottomright”, “bottom”, “bottomleft”, “left”, “topleft”, “top”, “topright”, “right” and “center”.</p>
Read more about <strong>legend</strong> in R: <a href="https://www.sthda.com/english/english/wiki/add-legends-to-plots-in-r-software-the-easiest-way">legend in R</a>.

</div>
<p><br/></p>
</div>
<div id="specify-the-legend-position-using-keywords" class="section level3">
<h3>Specify the legend position using keywords</h3>
<pre class="r"><code># "right" position
s3d <- scatterplot3d(iris[,1:3], pch = 16, color=colors)
legend("right", legend = levels(iris$Species),
      col =  c("#999999", "#E69F00", "#56B4E9"), pch = 16)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/scatterplot3d-change-legend-position-right-r-data-visualization-1.png" title="Scatterplot3d - R software and data visualization" alt="Scatterplot3d - R software and data visualization" width="432" style="margin-bottom:10px;" /></p>
<pre class="r"><code># Use the argument inset
s3d <- scatterplot3d(iris[,1:3], pch = 16, color=colors)
legend("right", legend = levels(iris$Species),
  col = c("#999999", "#E69F00", "#56B4E9"), pch = 16, inset = 0.1)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/scatterplot3d-change-legend-position-right-r-data-visualization-2.png" title="Scatterplot3d - R software and data visualization" alt="Scatterplot3d - R software and data visualization" width="432" style="margin-bottom:10px;" /></p>
<p><span class="question">What means the argument <strong>inset</strong> in the R code above?</span></p>
<p>The argument <strong>inset</strong> 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 <em>inset</em> argument using negative or positive values.</p>
<pre class="r"><code># "bottom" position
s3d <- scatterplot3d(iris[,1:3], pch = 16, color=colors)
legend("bottom", legend = levels(iris$Species),
      col = c("#999999", "#E69F00", "#56B4E9"), pch = 16)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/scatterplot3d-change-legend-position-r-data-visualization-1.png" title="Scatterplot3d - R software and data visualization" alt="Scatterplot3d - R software and data visualization" width="432" style="margin-bottom:10px;" /></p>
<p>Using <em>keywords</em> to specify the <em>legend position</em> is very simple. However, sometimes, there is an overlap between some points and the legend box or between the axis and legend box.</p>
<p><span class="question">Is there any solution to avoid this overlap?</span></p>
<p>Yes, there are several solutions using the combination of the following arguments for the function <strong>legend()</strong>:</p>
<ul>
<li><strong>bty = “n”</strong> : to <strong>remove the box around the legend</strong>. In this case the background color of the legend becomes transparent and the overlapping points become visible.</li>
<li><strong>bg = “transparent”</strong>: to change the background color of the legend box to <em>transparent</em> color (this is only possible when bty != “n”).</li>
<li><strong>inset</strong>: to modify the distance(s) between plot margins and the legend box.</li>
<li><strong>horiz</strong>: a logical value; if TRUE, set the legend horizontally rather than vertically</li>
<li><strong>xpd</strong>: a logical value; if TRUE, it enables the legend items to be drawn outside the plot.</li>
</ul>
</div>
<div id="customize-the-legend-position" class="section level3">
<h3>Customize the legend position</h3>
<pre class="r"><code># Custom point shapes
s3d <- scatterplot3d(iris[,1:3], pch = shapes)
legend("bottom", legend = levels(iris$Species),
       pch = c(16, 17, 18), 
      inset = -0.25, xpd = TRUE, horiz = TRUE)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/scatterplot3d-custom-legend-position-r-data-visualization-1.png" title="Scatterplot3d - R software and data visualization" alt="Scatterplot3d - R software and data visualization" width="432" style="margin-bottom:10px;" /></p>
<pre class="r"><code># Custom colors
s3d <- 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)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/scatterplot3d-custom-legend-position-r-data-visualization-2.png" title="Scatterplot3d - R software and data visualization" alt="Scatterplot3d - R software and data visualization" width="432" style="margin-bottom:10px;" /></p>
<pre class="r"><code># Custom shapes/colors
s3d <- 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)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/scatterplot3d-custom-legend-position-r-data-visualization-3.png" title="Scatterplot3d - R software and data visualization" alt="Scatterplot3d - R software and data visualization" width="432" style="margin-bottom:10px;" /></p>
<p><span class="notice">In the R code above, you can play with the arguments <em>inset</em>, <em>xpd</em> and <em>horiz</em> to see the effects on the appearance of the legend box.</span></p>
</div>
</div>
<div id="add-point-labels" class="section level2">
<h2>Add point labels</h2>
<p>The function <strong>text()</strong> is used as follow:</p>
<pre class="r"><code>scatterplot3d(iris[,1:3], pch = 16, color=colors)
text(s3d$xyz.convert(iris[, 1:3]), labels = rownames(iris),
     cex= 0.7, col = "steelblue")</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/scatterplot3d-text-r-data-visualization-1.png" title="Scatterplot3d - R software and data visualization" alt="Scatterplot3d - R software and data visualization" width="432" style="margin-bottom:10px;" /></p>
</div>
<div id="add-regression-plane-and-supplementary-points" class="section level2">
<h2>Add regression plane and supplementary points</h2>
<ol style="list-style-type: decimal">
<li>The result of <strong>scatterplot3d()</strong> is assigned to <em>s3d</em></li>
<li>A linear model is calculated as follow : lm(zvar ~ xvar + yvar). Assumption : zvar depends on xvar and yvar</li>
<li>The function <strong>s3d$plane3d()</strong> is used to add the regression plane</li>
<li>Supplementary points are added using the function <strong>s3d$points3d()</strong></li>
</ol>
<p>The data sets <em>trees</em> will be used:</p>
<pre class="r"><code>data(trees)
head(trees)</code></pre>
<pre><code>  Girth Height Volume
1   8.3     70   10.3
2   8.6     65   10.3
3   8.8     63   10.2
4  10.5     72   16.4
5  10.7     81   18.8
6  10.8     83   19.7</code></pre>
<p><span class="notice">This data set provides measurements of the girth, height and volume for black cherry trees.</span></p>
<p><strong>3D scatter plot with the regression plane</strong>:</p>
<pre class="r"><code># 3D scatter plot
s3d <- scatterplot3d(trees, type = "h", color = "blue",
    angle=55, pch = 16)
# Add regression plane
my.lm <- lm(trees$Volume ~ trees$Girth + trees$Height)
s3d$plane3d(my.lm)
# Add supplementary points
s3d$points3d(seq(10, 20, 2), seq(85, 60, -5), seq(60, 10, -10),
    col = "red", type = "h", pch = 8)</code></pre>
<p><img src="https://www.sthda.com/english/sthda/RDoc/figure/3d-graphics/scatterplot3d-regression-plane-1.png" title="Scatterplot3d - R software and data visualization" alt="Scatterplot3d - R software and data visualization" width="480" style="margin-bottom:10px;" /></p>
</div>
</div>
<div id="infos" class="section level1">
<h1>Infos</h1>
<p><span class="warning"> This analysis has been performed using <strong>R software</strong> (ver. 3.1.2) and <strong>scatterplot3d</strong> (ver. 0.3-35) </span></p>
</div>

<script>jQuery(document).ready(function () {
    jQuery('h1').addClass('wiki_paragraph1');
    jQuery('h2').addClass('wiki_paragraph2');
    jQuery('h3').addClass('wiki_paragraph3');
    jQuery('h4').addClass('wiki_paragraph4');
    });//add phpboost class to header</script>
<style>.content{padding:0px;}</style>
</div><!--end rdoc-->
<!--====================== stop here when you copy to sthda================-->

<!-- END HTML -->]]></description>
			<pubDate>Tue, 07 Apr 2015 23:39:33 +0200</pubDate>
			
		</item>
		
	</channel>
</rss>
