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.
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')
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))
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.