Dkova Dkova - 3 months ago 8
R Question

3 variable plot in R

I have a table that going like this:

| X | Y | Z | Value |
|:---:|:---:|:---:|:-----:|
| 0.1 | 0.1 | 0.1 | A |
| 0.2 | 0.2 | 0.4 | A |
| 0.1 | 0.3 | 0.4 | B |
| 0.4 | 0.2 | 0.3 | B |
| 0.3 | 0.1 | 0.4 | C |


(there is about 1000 rows)

The value column can get only {A,B,C}

I need to find a way to plot this table, so it is a 3D axis (X, Y, Z) and in each 3-cordinations will be the value/a color. (For e.x. in (0.1,0.1,0.1) the value is A)

Is there a way to do it in R (or any other software)?

Answer

You can use scatterplot3d library to do the same. For illustration purpose, I've used the following data set; where I've represented classes 'A', 'B', and 'C' by factors '1', '2', and '3' respectively:

x1 = c(0.1, 0.2, 0.3, 0.19, 0.34, 0.4)
x2 = c(0.3, 0.2, 0.1, 0.23, 0.43 , 0.4)
x3 = c(0.4, 0.2, 0.1, 0.2, 0.4, 0.35)
x4 = c('A', 'B', 'C', 'A', 'B', 'A') or 
x4 = c(1, 2, 3, 1, 2, 1)
data = data.frame(x1, x2, x3, x4)


library(scatterplot3d)
scatterplot3d(data$x1, data$x2, data$x3, # data
          main = "3D Scatter Plot", # title
          xlab = "First",           # x label
          ylab = "Second",          # y label   
          zlab = "Third",           # z label
          #pch = data$x4,        # the "fourth" column for the marks
          color = data$x4,      # the "fourth" column for the colours
          angle = 45,               # angle of the camera

)

Other libraries such as rgl or rcmdr can also be useful.

Comments