tolo9397 - 2 months ago 20

R Question

I am looking to plot a 3-D overlay of the mass spectra of different samples in R, much like the following figure:(https://www.researchgate.net/publication/7662272/figure/fig1/AS:280563387781122@1443902932685/Figure-4-3D-overlay-zoom-plot-of-mass-spectra-of-a-serum-sample-from-one-person.png)

I have been trying to use packages such as 'plot3D' but the final plot does not look as presentable. Are there any alternative packages that can produce a similar/identical plot to the one in the link?

Answer

I suggest `rgl`

package.

```
library(rgl)
# example data
df <- cbind(expand.grid(x = 1:20, y = c(1,2,4,5)),
z = c(dnorm(1:20, 18), dnorm(1:20, 14), dnorm(1:20, 6), dnorm(1:20, 2)))
open3d()
plot3d(df, type="n", axes=F, ylab="", ylim=c(0.5, 5.5), zlim = c(0, 1)) # a draft
axes3d(edge="bbox", xat=-10, yat=-10, zat=-10) # make a piece of box
axes3d(c("x", "z")) # x and z axis
axis3d("y+-", at = c(1,2,4,5), label = c("t = 5", "t = 4", "t = 15", "t = 20")) # y axis
for(i in c(1,2,4,5)) lines3d(df[df$y == i,], col=i+1)
text3d(5, 3, 0, "test", font=2)
```

additional example;

```
library(rgl); library(dplyr)
# example data
df <- cbind(expand.grid(x = 1:20, y = c(1,2,4,5)),
z = c(dnorm(1:20, 18), dnorm(1:20, 14), dnorm(1:20, 6), dnorm(1:20, 2)))
df2 <- df %>% mutate(z = jitter(z) + 0.1)
my.open3d() # type = "h" draw segments from z = 0. If you want another value for `from`, `segments3d()` achieves it.
plot3d(df2, type="h", axes=F, ylab="", ylim=c(0.5, 5.5), col="gray30", zlim=c(0, 1), lwd=3)
axes3d(edge="bbox", xat=-10, yat=-10, zat=-10) # make a piece of box
axes3d(c("x", "z")) # x and z axis
axis3d("y+-", at = c(1,2,4,5), label = c("t = 5", "t = 4", "t = 15", "t = 20")) # y axis
for(i in c(1,2,4,5)) lines3d(df2[df2$y == i,], col=i+1, lwd=2)
text3d(5, 3, 0.05, "test", font=2)
```

Source (Stackoverflow)

Comments