Reputation:
I have a data frame consisting of 400 rows of x, y and z values, and I would like to plot the x column against the y column.
This is what I have got so far:
sample3d = function(n)
{
df = data.frame()
while(n>0)
{
X = runif(1,-1,1)
Y = runif(1,-1,1)
Z = runif(1,-1,1)
a = X^2 + Y^2 + Z^2
if( a < 1 )
{
b = (X^2+Y^2+Z^2)^(0.5)
vector = data.frame(X = X/b, Y = Y/b, Z = Z/b)
df = rbind(vector,df)
n = n- 1
}
}
df
}
sample3d(400)
Upvotes: 1
Views: 708
Reputation: 24480
If you need to draw random points on the surface of a sphere, you need just to extract the polar coordinates. Something like that:
sample3d_v2 <- function(n) {
phi<-runif(n,0,2*pi)
cost<-runif(n,-1,1)
sint<-sqrt(1-cost^2)
data.frame(X=sint*cos(phi),Y=sint*sin(phi),Z=cost)
}
Just some tests:
system.time(old<-sample3d(4000))
# user system elapsed
# 3.895 0.000 3.879
system.time(new<-sample3d_v2(4000))
# user system elapsed
# 0.000 0.000 0.002
As you can see, a gain of thousands of times. Test the results are correct:
require(rgl)
plot3d(old)
open3d();plot3d(new)
Regarding your question: just name the object resulting for your function and plot the X and Y components.
data<-sample3d_v2(400)
plot(data$X,data$Y)
Upvotes: 1
Reputation: 1937
I named the dataframe your function creates data
(data <- sample3d(400)
).
Then, if you need a scatterplot (points at x and y coordinates) of the X and Y column, you can use base R's function plot()
. e.g. plot(x = data$X, y = data$Y)
. If you are like me and don't want to type data$
before every column you can make the columns available to functions as vectors by wrapping everything inside with(data = data, {...})
.
If you want to create a scatterplot of all three coordinates, you might want to check out the packages in the following two examples:
library(scatterplot3d)
with(data = data, {
scatterplot3d(x = X, y = Y, z = Z)
})
library(rgl)
with(data, {
plot3d(X, Y, Z)
})
Upvotes: 0