Octave 3D mesh, data from file - plot

I have a big file with 3 columns: density, dimension, value.
example:
10 0.3 200
10 0.4 300
20 0.3 250
20 0.4 320
I am trying to draw a 3d plot - mesh with mesh() function in octave, like this:
data = load ("file.txt");
mesh(data(:,1), data (:,2), data (:,3));
Problem I have is , I always get error:
rows (z) must be the same as length (y), columns (z) must be the same as length (x).
It worked with function plot3(), but I would like a mesh kind of plot.

The problem is that mesh(X,Y,Z) is expecting your X and Y matrices to be generated using X = meshgrid(x) and Y = meshgrid(y) where x and y only contain unique points. Your data basically already defines the meshgrid, but it is difficult to get it out.
I suggest using reshape as:
X = reshape(data(:,1),m,n);
Y = reshape(data(:,2),m,n); % might be reshape(data(:,2),n,m)
Z = reshape(data(:,3),m,n);
mesh(X,Y,Z);
In this case the assumption is that you have m unique values in Y, and n unique values in X. You may have to transpose these in your call to mesh as mesh(X',Y',Z) or something like that.

Related

Plot a 3d graph with a slider to control number of points plotted

I have data which is movement of an object in 3D space at regular time intervals. Data is as below:
Time X Y Z
1 1 1 1
2 2 1 2
3 2 0 1
4 3 2 1
.....
(x,y,z) is the position of object at time t. I want to plot a 3D graph where it shows the complete movement of object in 3d space, but to have a slider or something of that sort where I can select a time range (say 500 to 750) and see the movement of the object in 3D space. So, here we have 4 dimensions: x,y,z are positions and time as 4th dimension and use a slider to control the plotting of points with in that time. [Example in Mathematica below gives a good idea about this]
To make it more clear. We first draw the complete movement of the object in 3D space from time 1 to N. Then, by controlling the slider, we draw the movement of same object between t1 to t2 time stamps. It is also important to display at what time the slider is at (as I have to make a note of some interested time stamps based on the movement).
I have Googled the same, but no example was close enough to get me what I want. All of those bind the slider to one of the axis variables (say x or y which might be time) but we have to bind it to 4th dimension, time. dygraphs was promising but I had similar issues as discussed above (also, didn't find any 3d support).
This one in Mathematica is interesting. But I don't have license for it. It just moves a point on the 3D path traced. This can solve my problem as well, but I should be able to know the time-stamp values when I pause it.
Solution in R is good for me because it does not have any licensing issues. Or in Matlab if it does not use any advanced visualization toolboxes. Or Python.
Thanks in Advance.
This is a raw example that can be customized as desired. It uses manipulate and plot3D
library(manipulate)
library(plot3D)
min_time <- 1
max_time <- 100
time_interval <- min_time:max_time
# Create data frame
DF <- data.frame(t = time_interval)
# Time parametric functions
X <- function(t) {
return(2 * t)
}
Y <- function(t) {
return(t ** 2)
}
Z <- function(t) {
return(10 * cos(t / 100))
}
# Update data frame
DF$x <- sapply(DF$t, X)
DF$y <- sapply(DF$t, Y)
DF$z <- sapply(DF$t, Z)
# Use manipulate with RStudio
manipulate({
lines3D(x = DF$x, y = DF$y, z = DF$z)
scatter3D(
x = DF$x[t],
y = DF$y[t],
z = DF$z[t],
add = TRUE
)
}, t = slider(min_time, max_time))

Levelplot in R on irregular grid

I would like to create a 2D levelplot in R where the x and y coordinates are from an irregular grid without using interpolation. The grid is given below:
grid<-cbind(seq(from=0.05,to=0.5,by=0.05),seq(from=0.05,to=0.5,by=0.05))
grid<-rbind(grid,cbind(seq(from=0.0,to=0.95,by=0.05),seq (from=0.05,to=1,by=0.05)))
grid<-rbind(grid,cbind(seq(from=0,to=0.9,by=0.05),seq (from=0.1,to=1,by=0.05)))
grid<-rbind(grid,cbind(seq(from=0,to=0.85,by=0.05),seq(from=0.15,to=1,by=0.05)))
grid<-rbind(grid,cbind(seq(from=0,to=0.75,by=0.05),seq(from=0.25,to=1,by=0.05)))
grid<-rbind(grid,cbind(seq(from=0,to=0.80,by=0.05),seq(from=0.20,to=1,by=0.05)))
grid<-rbind(grid,cbind(seq(from=0,to=0.70,by=0.05),seq(from=0.30,to=1,by=0.05)))
grid<-rbind(grid,cbind(seq(from=0,to=0.65,by=0.05),seq(from=0.35,to=1,by=0.05)))
grid<-rbind(grid,cbind(seq(from=0,to=0.60,by=0.05),seq(from=0.40,to=1,by=0.05)))
grid<-rbind(grid,cbind(seq(from=0,to=0.55,by=0.05),seq(from=0.45,to=1,by=0.05)))
grid<-rbind(grid,cbind(seq(from=0,to=0.50,by=0.05),seq(from=0.50,to=1,by=0.05)))
grid<-rbind(grid,cbind(seq(from=0,to=0.40,by=0.05),seq(from=0.60,to=1,by=0.05)))
grid<-rbind(grid,cbind(seq(from=0,to=0.45,by=0.05),seq(from=0.55,to=1,by=0.05)))
grid<-rbind(grid,cbind(seq(from=0,to=.35,by=0.05),seq(from=0.65,to=1,by=0.05)))
grid<-rbind(grid,cbind(seq(from=0,to=0.30,by=0.05),seq(from=0.70,to=1,by=0.05)))
x=grid[,1]
y=grid[,2]
The Z-values are stored in another vector. I have tried to use the image-function, but without any luck. For instance, if I try
image(x,y,height.vals)
where
height.vals=matrix(runif(dim(grid)[1]),nrow=dim(grid)[1],ncol=1)
I get an error message saying that x and y should be increasing.
One could use the akima function interp, but then I get interpolated data.
Looks like you have points on a 20 x 20 grid. So, you can create a 20 x 20 matrix and fill it with the values from height.vals.
With a little bit of tweaking, you can turn the x and y values into indices of the matrix and use those indices to assign height.vals to the appropriate places in the matrix.
# Turn the x and y values into integers.
# R doesn't take 0 as an index, so add 1 to the x values to get rid of the 0s
inds <- cbind(x = as.integer(20*x + 1), y = as.integer(20*y))
# create the 20 x 20 matrix
m <- matrix(nrow = 20, ncol = 20)
# fill the matrix with height.vals based on the indices
m[inds] <- height.vals
Then, you can use m as an input to functions like image, filled.contour, and lattice::levelplot
image(m)

Wireframe plot with small values in R

I have data with very small values between -1 to 1 in X, Y and Z values between -1 to 1 like below
X,Y,Z
-0.858301,-1,1.00916
-0.929151,-1,1.0047
-0.896405,-0.940299,1.00396
-0.960967,-0.944075,1.00035
wireframe(Z~X+Y,data=sol)
Seems wireframe works only with larger values (1, 2, 3...) , How do I plot small values?
wireframe might be use in one of two ways -
With a rectangular data matrix where the values of x and y are implied by the shape of the matrix.
wireframe(matrix(rnorm(100),ncol=5),drape=TRUE)
Or with a dataframe, where the values of x and y are explicit, and here you can use a formula for the relationships between the columns.
df<-expand.grid(x = seq(0,.1,.01), y = seq(0,.1,.01))
df$z<-rnorm(121)
wireframe(z~x*y,data=df,drape=TRUE)
I've found that if you include the line defining the z axis limits, then you can't draw it below 1. But if you take out the defined axis limits, and let R graph it itself, then it works and you can graph small numbers.

create hexagonal cells grid using lat/lon coordinates

I would like to create a spatial grid with hexagonal cells using WGS84 coordinates (ie cells defined by 2 coordinates X=Latitude and Y=Longitude)
So, this is what I was thinkin about :
library(ggplot2);library(hexbin)
X<-seq(-10,20,by=0.1) # create coordinates vectors X and Y
Y<-seq(35,65,by=0.1)
z<-rnorm(301,0.5,1)
df<-as.data.frame(cbind(X,Y,z)) # create data frame with a z value for each cells (X,Y)
pl<-ggplot2(data=mat,aes(x=X,y=Y,z=z))+stat_summury_hex(fun=function(x) sum(x))
plot(pl)
But doing this does not provide what I wanted.
So, my question is : how to do a spatial grid with hexagonal cells using lat/lon coordinates ?
And second question : how to create a grid centered from one point (that would represent the centroid, and not the left bottom corner as usual?)
If I understand properly, you're looking for expand.grid():
xy <- expand.grid(X=X,Y=Y)
z<-rnorm(nrow(xy),0.5,1)
df<-as.data.frame(cbind(xy,z)) # create data frame with a z value for each cells (X,Y)
head(df)
pl<-ggplot(data=df,aes(x=X,y=Y,z=z))+stat_summary_hex(fun=function(x) sum(x))
plot(pl)
As for the second question, I'm not sure, but since all hexagons are the same size and will require the same operation to center, you can shift them uniformly by changing X and Y appropriately. Perhaps this can also be done via arguments also, not sure.
[[Edit July 23]]
second question was how to get a data.frame of hex coordinates. Took some digging, but here's an example:
library(hexbin)
coords <- hcell2xy( hexbin(x=X,y=Y))
head(coords)
x y
1 -10.0 35.00000
2 -9.5 35.86603
3 -8.5 35.86603
4 -9.0 36.73205
5 -8.0 36.73205
6 -7.5 37.59808
hcell2xy() is the key function called by ggplot2, and you may need to be explicit about specifying the argument xbins, which is determined automatically inside ggplot2, but appears to default to 30 in both cases.
[[Edit 3, to include z level]]
This is an answer to the comment asking for z levels as well. Ripped from ggplot2:::hexBin
hb <- hexbin(x=X,y=Y)
# Convert to data frame
data.frame(
hcell2xy(hb),
count = hb#count,
density = hb#count / sum(hb#count, na.rm=TRUE)
)
You can choose whether to use count or density for colors later, but warning: those are different from your z variable fed to ggplot2. If you'd like to summarize based on some other statistic, then I suggest you also look into the guts of those functions to see how things are passed around. That's what I've been doing.

R: Converting cartesian coordinates to polar coordinates, and then calculating distance from origin

I've been looking for a solution to convert cartesian coordinates (lat, long) that I have to polar coordinates in order to facilitate a simulation that I want to run, but I haven't found any questions or answers here for doing this in R. There are a number of options, including the built in function cart2pol in Matlab, but all of my data are in R and I'd like to continue getting comfortable working in this framework.
Question:
I have lat/long coordinates from tagging data, and I want to convert these to polar coordinates (meaning jump size and angle: http://en.wikipedia.org/wiki/Polar_coordinate_system) so that I can then shuffle or bootstrap them (haven't decided which) about 1,000 times, and calculate the straight-line distance of each simulated track from the starting point. I have a true track, and I'm interested in determining if this animal is exhibiting site affinity by simulating 1,000 random tracks with the same jump sizes and turning angles, but in completely different orders and combinations. So I need 1,000 straight-line distances from the origin to create a distribution of distances and then compare this to my true data set's straight-line distance.
I'm comfortable doing the bootstrapping, but I'm stuck at the very first step, which is converting my cartesian lat/long coordinates to polar coordinates (jump size and turning angle). I know there are built in functions to do this in other programs such as Matlab, but I can't find any way to do it in R. I could do it manually by hand in a for-loop, but if there's a package out there or any easier way to do it, I'd much prefer that.
Ideally I'd like to convert the data to polar coordinates, run the simulation, and then for each random track output an end point as cartesian coordinates, lat/long, so I can then calculate the straight-line distance traveled.
I didn't post any sample data, as it would just be a two-column data frame of lat and long coordinates.
Thanks for any help you can provide! If there's an easy explanation somewhere on this site or others that I missed, please point me in that direction! I couldn't find anything.
Cheers
For x-y coordinates that are in the same units (e.g. meters rather than degrees of latitude and degrees of longitude), you can use this function to get a data.frame of jump sizes and turning angles (in degrees).
getSteps <- function(x,y) {
d <- diff(complex(real = x, imaginary = y))
data.frame(size = Mod(d),
angle = c(NA, diff(Arg(d)) %% (2*pi)) * 360/(2*pi))
}
## Try it out
set.seed(1)
x <- rnorm(10)
y <- rnorm(10)
getSteps(x, y)
# size angle
# 1 1.3838360 NA
# 2 1.4356900 278.93771
# 3 2.9066189 101.98625
# 4 3.5714584 144.00231
# 5 1.6404354 114.73369
# 6 1.3082132 135.76778
# 7 0.9922699 74.09479
# 8 0.2036045 141.67541
# 9 0.9100189 337.43632
## A plot helps check that this works
plot(x, y, type = "n", asp = 1)
text(x, y, labels = 1:10)
You can do a transformation bewteen cartesian and polar this way:
polar2cart <- function(r, theta) {
data.frame(x = r * cos(theta), y = r * sin(theta))
}
cart2polar <- function(x, y) {
data.frame(r = sqrt(x^2 + y^2), theta = atan2(y, x))
}
Since it is fairly straight forward, you can write your own function. Matlab-like cart2pol function in R:
cart2pol <- function(x, y)
{
r <- sqrt(x^2 + y^2)
t <- atan(y/x)
c(r,t)
}
I used Josh O'Brien's code and got what appear to be reasonable jumps and angles—they match up pretty well to eyeballing the rough distance and heading between points. I then used a formula from his suggestions to create a function to turn the polar coordinates back to cartesian coordinates, and a for loop to apply the function to the data frame of all of the polar coordinates. The loops appear to work, and the outputs are in the correct units, but I don't believe the values that it's outputting are corresponding to my data. So either I did a miscalculation with my formula, or there's something else going on. More details below:
Here's the head of my lat long data:
> head(Tag1SSM[,3:4])
lon lat
1 130.7940 -2.647957
2 130.7873 -2.602994
3 130.7697 -2.565903
4 130.7579 -2.520757
5 130.6911 -2.704841
6 130.7301 -2.752182
When I plot the full dataset just as values, I get this plot:
which looks exactly the same as if I were to plot this using any spatial or mapping package in R.
I then used Josh's function to convert my data to polar coordinates:
x<-Tag1SSM$lon
y<-Tag1SSM$lat
getSteps <- function(x,y) {
d <- diff(complex(real = x, imaginary = y))
data.frame(size = Mod(d),
angle = c(NA, diff(Arg(d)) %% (2*pi)) * 360/(2*pi))
}
which produced the following polar coordinates appropriately:
> polcoords<-getSteps(x,y)
> head(polcoords)
size angle
1 0.04545627 NA
2 0.04103718 16.88852
3 0.04667590 349.38153
4 0.19581350 145.35439
5 0.06130271 59.37629
6 0.01619242 31.86359
Again, these look right to me, and correspond well to the actual angles and relative distances between points. So far so good.
Now I want to convert these back to cartesian coordinates and calculate a euclidian distance from the origin. These don't have to be in true lat/long, as I'm just comparing them amongst themselves. So I'm happy for the origin to be set as (0,0) and for distances to be calculated in reference x,y values instead of kilometers or something like that.
So, I used this function with Josh's help and a bit of web searching:
polar2cart<-function(x,y,size,angle){
#convert degrees to radians (dividing by 360/2*pi, or multiplying by pi/180)
angle=angle*pi/180
if(is.na(x)) {x=0} #this is for the purpose of the for loop below
if(is.na(y)) {y=0}
newx<-x+size*sin(angle) ##X #this is how you convert back to cartesian coordinates
newy<-y+size*cos(angle) ##Y
return(c("x"=newx,"y"=newy)) #output the new x and y coordinates
}
And then plugged it into this for loop:
u<-polcoords$size
v<-polcoords$angle
n<-162 #I want 162 new coordinates, starting from 0
N<-cbind(rep(NA,163),rep(NA,163)) #need to make 163 rows, though, for i+1 command below— first row will be NA
for(i in 1:n){
jump<-polar2cart(N[i,1],N[i,2],u[i+1],v[i+1]) #use polar2cart function above, jump from previous coordinate in N vector
N[i+1,1]<-jump[1] #N[1,] will be NA's which sets the starting point to 0,0—new coords are then calculated from each previous N entry
N[i+1,2]<-jump[2]
Dist<-sqrt((N[163,1]^2)+(N[163,2]^2))
}
And then I can take a look at N, with my new coordinates based on those jumps:
> N
[,1] [,2]
[1,] NA NA
[2,] 0.011921732 0.03926732
[3,] 0.003320851 0.08514394
[4,] 0.114640605 -0.07594871
[5,] 0.167393509 -0.04472125
[6,] 0.175941466 -0.03096891
This is where the problem is... the x,y coordinates from N get progressively larger—there's a bit of variation in there, but if you scroll down the list, y goes from 0.39 to 11.133, with very few backward steps to lower values. This isn't what my lat/long data do, and if I calculated the cart->pol and pol->cart properly, these new values from N should match my lat/long data, just in a different coordinate system. This is what the N values look like plotted:
Not the same at all... The last point in N is the farthest point from the origin, while in my lat/long data, the last point is actually quite close to the first point, and definitely not the farthest point away. I think the issue must be in my conversion from polar coordinates back to cartesian coordinates, but I'm not sure how to fix it...
Any help in solving this would be much appreciated!
Cheers
I think this code I wrote converts to polar coordinates:
# example data
x<-runif(30)
y<-runif(30)
# center example around 0
x<-x-mean(x)
y<-y-mean(y)
# function to convert to polar coordinates
topolar<-function(x,y){
# calculate angles
alphas<-atan(y/x)
# correct angles per quadrant
quad2<-which(x<0&y>0)
quad3<-which(x<0&y<0)
quad4<-which(x>0&y<0)
alphas[quad2]<-alphas[quad2]+pi
alphas[quad3]<-alphas[quad3]+pi
alphas[quad4]<-alphas[quad4]+2*pi
# calculate distances to 0,0
r<-sqrt(x^2+y^2)
# create output
polar<-data.frame(alphas=alphas,r=r)
}
# call function
polar_out<-topolar(x,y)
# get out angles
the_angles<-polar_out$alphas
Another option only in degree
pol2car = function(angle, dist){
co = dist*sin(angle)
ca = dist*cos(angle)
return(list(x=ca, y=co))
}
pol2car(angle = 45, dist = sqrt(2))
cart2sph {pracma} Transforms between cartesian, spherical, polar, and cylindrical coordinate systems in two and three dimensions.

Resources