2

I have 500 points in space with lat, lng as :

lng=runif(100,1,4)
lat=runif(100,40,40.1)

Let's say that we have there (density) as

z=rnorm(1000)

I've tried to plot 3d surface using persp

persp(lng,lat,z)

But I have this error :

Error : increasing 'x' and 'y' values expected

I sorted x and y using

data=data.frame(lng,lat)
data=data[ order(data[,1],data[,2]), ]

And I tried again

persp(data[,1],data[,2],z)

But I still have the same problem.

How can I do it ?

Thank you.

LyzandeR
  • 37,047
  • 12
  • 77
  • 87
Math
  • 1,274
  • 3
  • 14
  • 32

1 Answers1

1

The problem is the argument z and the ordering of both x and y. As shadow mentions in the comments this needs to be a matrix of dim(z) = length(x) x length(y) in this case 100x100. And apparently x and y need to be both ordered at the same time exactly as shadow mentions above which is seen in the source code of persp.default as.well:

if (any(diff(x) <= 0) || any(diff(y) <= 0)) #both need to be ordered
        stop("increasing 'x' and 'y' values expected")

So the following works:

lng=runif(100,1,4)
lat=runif(100,40,40.1)
z=matrix(rnorm(10000),ncol=100,nrow=100) #use the correct z as matrix
data=data.frame(lng,lat)
data=data[ order(data[,1],data[,2]), ]   #just order lng as you do 
data$lat <- sort(data$lat)               #you need to sort lat too

persp(data[,1] ,data[,2], z) 

And this works now.

enter image description here

Edit

I think what you really want to do is to have you lan/lng coordinates in z and plot them. The z argument needs to carry the coordinates. the x and y arguments just carry the values of the x and y axes respectively. You can use the default x and y argumens (i.e. leave them blank) or just sort lan and lng separately to provide the real values. So, the solution you are looking for is:

lng=runif(100,1,4)
lat=runif(100,40,40.1)
z= as.matrix(data.frame(lng=lng,lat=lat))
z=matrix(rnorm(10000),ncol=100,nrow=100) #z contains lan and lng

#plot z with default x and y values (or use sorted lng and lat instead)
persp( z = z)  

Which outputs:

enter image description here

LyzandeR
  • 37,047
  • 12
  • 77
  • 87
  • Thank you , But when you do : data$lat <- sort(data$lat) , this could change your data. – Math Feb 04 '15 at 11:30
  • 1
    Yes I know it changes the order of the pairs (the x,y co-ordinates). I think the way you need to use this function is to have your x, y co-ordinates in the z matrix. x and y values are only the corresponding values of the x and y axes. Try having x and y as the default values i.e. do not use those and use z as the lng, lan coordinates. I think this is what you need. – LyzandeR Feb 04 '15 at 11:45