3d scatterplot with colored spheres with R and Rgl

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-31 17:37:50

问题


I want to create a 3d scatter plot of spheres with their color being the fourth dimension. I have the data in a csv file where each line indicates the x,y,z position of a particle and I have a column which tells me the value of the particle (1,2 or 3). I want to color the balls in one color if their value is 1 or in another color otherwise.

Edit:

I created the following code:

library(rgl)
m <- read.csv(file="mem0.csv", sep = ",", head=TRUE)
mcol = m$val
i = 1 
mdim = dim(m)

while (i <= mdim[1] ){
   if (mcol[i] == 1){
      mcol[i] = "red"
   }else {
      mcol[i] = "blue"
   }
   i = i +1
}

plot3d(m$x, m$y, m$z, col = mcol, type='s', size=0.1)

Edit number 2:

I use the rgl.snapshot() to export to an svg file:

The data should display a layer of red balls, 4 layers of blue balls and a layer of red balls again.


回答1:


The plot3d() function of the rgl package allows to do such a thing quite easily. And you can even explore your plot interactively :

R> library(rgl)

R> df <- data.frame(x=runif(10,0,1),
+                  y=runif(10,0,1),
+                  z=runif(10,0,1),
+                  color=round(runif(10,1,3)))
R> df
            x         y          z color
1  0.73518229 0.1385970 0.69053482     2
2  0.88789302 0.6872121 0.54734176     2
3  0.79402546 0.5771570 0.89613292     1
4  0.19922140 0.2117405 0.25116078     1
5  0.31825325 0.7449661 0.01174593     2
6  0.64614521 0.4704698 0.68905621     1
7  0.15242295 0.6461338 0.77896858     1
8  0.32698024 0.4548752 0.33969754     3
9  0.00793849 0.6557488 0.75901935     2
10 0.20460232 0.9302882 0.23413984     3

You can call plot3d() like this :

R> plot3d(df$x, df$y, df$z, col=df$color, size=2, type='s')

Which will give you something like :



来源:https://stackoverflow.com/questions/5221283/3d-scatterplot-with-colored-spheres-with-r-and-rgl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!