3D surface plot from 2D matrix
Asked Answered
E

2

14

Using a 2d matrix in R, how can I create a 3d surface plot, where columns=x, rows=y and the values are the heights in z?

In the example below, x values would be 1:5, y value would be 1:5, and the numbers would represent heights/values in z.

> m<-matrix(rnorm(25),nrow=5,ncol=5)
> m
             [,1]       [,2]       [,3]        [,4]       [,5]
[1,] -1.495513045  0.8000040 -1.1499261  1.65661138  0.8140510
[2,] -1.150018195 -0.7582933  0.8306922  0.16026908  0.3913198
[3,] -0.852609406  0.5525621  0.3585986 -0.45054768 -1.2259927
[4,] -0.001926297 -0.5857351  2.1518281  0.03192463  0.2065039
[5,] -1.641128610  0.4333973 -1.0616628 -0.92143426 -0.9598991
Extravasate answered 20/6, 2013 at 23:57 Comment(0)
S
10

Package rgl should get you started...

require(rgl)
#  open renderer
open3d()
#  plot surface
rgl.surface( 1:10 , 1:10 , runif(100))
#  Export to png
rgl.snapshot( "sample.png" , fmt="png", top=TRUE )

enter image description here

Shep answered 21/6, 2013 at 0:11 Comment(0)
G
9

To get a 3D surface plot of a 2D matrix that contains the Z-values, try:

require(plot3D)

persp3D(z = TheMatrix2D, theta = 120)

Use theta to adjust the viewing angle. With my data, I get the following plot:

enter image description here

Gherlein answered 28/7, 2016 at 23:14 Comment(1)
this seems like better syntax (since it accepts a matrix as input), and has better default settings.Sik

© 2022 - 2024 — McMap. All rights reserved.