Gotey
Gotey

Reputation: 639

How to use persp() with R to graph three variables in a dataset

I have this data:

wine <-read.table("http://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data",sep=",")
attach(wine)

and I am trying to prompt a 3D plot of the variables V2, V3 and V4 with the persp() function

I get this error:

Error in persp.default(v2, v3, v4) : 
  increasing 'x' and 'y' values expected

Although I already sorted each variable with the sort() function.

How should I proceed?

Upvotes: 2

Views: 13034

Answers (2)

Sandipan Dey
Sandipan Dey

Reputation: 23109

As per Zheyuan's reply, persp is not the rigth choice for scatterplot in 3d, you can use rgl instead with your wine data:

library(rgl)
plot3d(wine$V1, wine$V2, wine$V3, type='s', size=2, col=wine$V1)

enter image description here

Upvotes: 4

Zheyuan Li
Zheyuan Li

Reputation: 73385

This is some conceptual mistake. persp is used for surface plot, but your data only support scatter plot.

For a surface plot, we need the surface values on a grid expanded by x, y. In other words, we are plotting a 2D function f(x, y) on a grid: expand.grid(x = sort(x), y = sort(y)). We need to know this function f and (in almost all situation) use outer to evaluate it on such grid. Consider this example:

x <- seq(-10, 10, length = 30)  ## already in increasing order
y <- x  ## already in increasing order
f <- function(x, y) {r <- sqrt(x ^ 2 + y ^ 2); 10 * sin(r) / r}
z <- outer(x, y, f)  ## evaluation on grid; obtain a matrix `z`
persp(x, y, z)

enter image description here

Scatter plot on the other hand, is only restricted to (x, y):

library(scatterplot3d)
scatterplot3d(V2, V3, V4)  ## your `wine` data

enter image description here

Upvotes: 2

Related Questions