Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multidimensional (2D) function plot in R

Tags:

plot

r

I'm looking into plotting functions and I've run into persp and curve but I'm not able to follow them to plot a 2D function.

They are for surface plots, yes?

If I had a function like x^2 + y^2 [x,y] in [-3,3] how do I go about it? Any links will be much appreciated and critique on existing packages (if multiple) ? gold.

Thanks.

like image 748
Raaj Avatar asked Mar 03 '14 15:03

Raaj


1 Answers

To use persp, you need to supply values of x, values of y, and values of z for each combination of x and y. The easiest way to do this is to define x and y and then use outer to create a matrix that crosses x and y. You need to specify the way the two variables should be combined as the third argument to outer, in this case the function +:

x <- seq(-3,3,length.out=100)
y <- seq(-3,3,length.out=100)
z <- outer(x^2,y^2,`+`)
persp(x,y,z, col='blue')

enter image description here

You may also be interested in rotating the results. Here are some examples using the theta parameter:

par(mar=c(1,1,1,1))
layout(matrix(1:4, nrow=2))
s=lapply(c(0,30,60,90), function(t) persp(x,y,z, col='blue', theta=t))

enter image description here

EDIT: I understand from your comment you would like a 2D representation of this surface. The easiest way to get that in base R is with image of your z matrix:

image(z)

enter image description here

like image 143
Thomas Avatar answered Nov 15 '22 17:11

Thomas