Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: 4D plot, x, y, z, colours

Tags:

plot

r

Could you give me an example on how to use rgl to plot 3 variables at the axes x, y and z and a fourth one with different colours?

thanks

like image 477
skan Avatar asked Sep 24 '10 10:09

skan


People also ask

How do I add color to a plot in R?

In R, the color black is denoted by col = 1 in most plotting functions, red is denoted by col = 2 , and green is denoted by col = 3 . So if you're plotting multiple groups of things, it's natural to plot them using colors 1, 2, and 3.

How do you color a plot by a variable in R?

One of the ways to add color to scatter plot by a variable is to use color argument inside global aes() function with the variable we want to color with. In this scatter plot we color the points by the origin airport using color=origin. The color argument has added colors to scatterplot with default colors by ggplot2.

How do you add color to a scatter plot in R?

To change scatter plot color according to the group, you have to specify the name of the data column containing the groups using the argument groupName . Use the argument groupColors , to specify colors by hexadecimal code or by name .


1 Answers

You use a combination of persp and colour according to a separate function. Here's some example code:

## Create a simple surface  f(x,y) = -x^2 - y^2
## Colour the surface according to x^2 only
nx = 31; ny = 31
x = seq(-1, 1, length = nx)
y = seq(-1, 1, length = ny)
z = outer(x, y, function(x,y) -x^2  -y^2)
## Fourth dim
z_col = outer(x, y, function(x,y) x^2)

## Average the values at the corner of each facet
## and scale to a value in [0, 1].  We will use this
## to select a gray for colouring the facet. 
hgt = 0.25 * (z_col[-nx,-ny] + z_col[-1,-ny] + z_col[-nx,-1] + z_col[-1,-1])
hgt = (hgt - min(hgt))/ (max(hgt) - min(hgt))

##  Plot the surface with the specified facet colours.
persp(x, y, z, col = gray(1 - hgt))
persp(x, y, z, col=cm.colors(32)[floor(31*hgt+1)], theta=-35, phi=10)

This gives:

Sample output

RGL

It's fairly straightforward to use the above technique with the rgl library:

library(rgl)
## Generate the data using the above commands
## New window
open3d()

## clear scene:
clear3d("all")

## setup env:
bg3d(color="#887777")
light3d()

surface3d(x, y, z, color=cm.colors(32)[floor(31*hgt+1)], alpha=0.5)
like image 160
csgillespie Avatar answered Sep 28 '22 09:09

csgillespie