使用R在3D透明球体内部的轨迹图

时间:2015-07-11 06:46:32

标签: r plot transparency rgl

我想在透明的3d球体内制作df的轨迹图。

我搜索了stackoverflow但找不到相同的问题。因此,对于对其载体轨迹感兴趣的每个人都可能会有所帮助。

df可能就像这样

df <- data.frame(mx=runif(100,-0.05,0.05),
             my=runif(100,-1,1),
             mz=runif(100,-0.5,0.5))

enter image description here

2 个答案:

答案 0 :(得分:4)

我同意弗兰克的回答。如果你想要做的是在像所提供的图像一样的球体上绘制轨迹,你应该更加小心,因为普通插值不会在球体上给出路径。有不同的选项,但最简单的可能只是将路径投影到球体上。

require(rgl)

# Construct a Brownian motion on a sphere
n <- 100
sigma <- 0.5

df <- array(NA, dim = c(n, 3))
df[1, ] <- rnorm(3, sd = sigma) # Starting point
df[1, ] <- df[1, ] / sqrt(sum(df[1, ]^2))
for (i in 2:n) {
  df[i, ] <- rnorm(3, sd = sigma) + df[i - 1, ]
  df[i, ] <- df[i, ] / sqrt(sum(df[i, ]^2))
}

# Linear interpolation of observed trajectories, but projected onto sphere
times <- seq(1, n, length = 1000)

xx <- approx(1:n, df[, 1], xout = times)$y
yy <- approx(1:n, df[, 2], xout = times)$y
zz <- approx(1:n, df[, 3], xout = times)$y
df_proj <- cbind(xx, yy, zz)
df_proj <- df_proj / sqrt(rowSums(df_proj ^2))

# Plot
plot3d(df_proj, type = 'l', col = heat.colors(1000), lwd = 2, xlab = 'x', ylab = 'y', zlab = 'z')
rgl.spheres(0, 0, 0, radius = 0.99, col = 'red', alpha = 0.6, back = 'lines')

trajectories on sphere

你可以用弗兰克回答的平滑轨迹做同样的事情:

# Smooth trajectories plot

times <- seq(1, n, length = 1000)
xx <- spline(1:n, df[, 1], xout = times)$y
yy <- spline(1:n, df[, 2], xout = times)$y
zz <- spline(1:n, df[, 3], xout = times)$y

df_smooth <- cbind(xx, yy, zz)
df_smooth <- df_smooth / sqrt(rowSums(df_smooth^2))

plot3d(df_smooth, type = 'l', col = heat.colors(1000), lwd = 2, xlab = 'x', ylab = 'y', zlab = 'z')
rgl.spheres(0, 0, 0, radius = 0.99, col = 'red', alpha = 0.6, back = 'lines')

enter image description here

答案 1 :(得分:3)

您可以使用type="l"中的plot3d连接球体内的点,并使用spheres3d绘制球体:

library(rgl)
plot3d(df, type="l", axes=FALSE) # type="l" is for "line"
spheres3d(0,0,0, radius=1, alpha=0.3, back="cull") # transparency set by alpha from 0 to 1

enter image description here

或者使用样条线来制作一个平滑的&#34;轨迹,取自Duncan Murdoch

xx <- splinefun(seq_along(df$mx), df$mx)
yy <- splinefun(seq_along(df$my), df$my)
zz <- splinefun(seq_along(df$mz), df$mz)
times<-seq(1, dim(df)[1], len=2000) # vary length to change smoothness

plot3d(xx(times), yy(times), zz(times), type="l", axes=FALSE) 
spheres3d(0,0,0, radius=1, alpha=0.3, back="cull")

enter image description here

正如您所看到的,这样,您可能最终得到半径为1的线,因此您可以通过输入更大的半径数来简单地增加球体的半径或者使用radius=max(xx(times), yy(times), zz(times))