Noor
Noor

Reputation: 365

How to plot 3D in R with multi-conditions

I have data set with 3 features as below:

V1       V2      V3
0.268   0.917   0.191
0.975   0.467   0.447
0.345   0.898   0.984
0.901   0.043   0.456
0.243   0.453   0.964
0.001   0.464   0.953
0.998   0.976   0.978
0.954   0.932   0.923

How to plot this data in 3D graphic based on the following conditions giving different colour for each condition.

(v1>=0.90 && v3>=0.90  && v3>=0.90) || (v1>=0.90 && v3< 0.50  && v3< 0.50) || (v1 < 0.50 && v3>=0.90  && v3< 0.50)|| (v1< 0.50 && v3< 0.50  && v3>=0.90)

Upvotes: 0

Views: 41

Answers (2)

Fino
Fino

Reputation: 1784

I assumed the second statement in each condition is referring to V2, which makes more sense. To color the points according to which condition is met first you need to create a column with that value:

df = data.frame(
  "V1" = c(0.268,0.975,0.345,0.901,0.243,0.001,0.998,0.954),
  "V2" = c(0.917,0.467,0.898,0.043,0.453,0.464,0.976,0.932),
  "V3" = c(0.191,0.447,0.984,0.456,0.964,0.953,0.978,0.923)
)


df = df %>% 
  mutate(
    group = case_when(
      V1 >= 0.9 & V2 >= 0.9 & V3 >=0.9 ~ "1",
      V1 >= 0.9 & V2 < 0.5 & V3 < 0.5 ~ "2",
      V1 < 0.5 & V2 >= 0.9 & V3 <0.5 ~ "3",
      V1 <0.5 & V2 <0.5 & V3 >=0.9 ~ "4",
      T ~ "5"
))

Then we can use the plotlyor scatterplot3d packages to build the graph:

scatterplot3d(x=df$V1,y=df$V2,z=df$V3,color=df$group)
plot_ly(x=df$V1,y=df$V2,z=df$V3,color = df$group)

enter image description here enter image description here

Upvotes: 1

niko
niko

Reputation: 5281

You can start by creating a logical vector using the vectorized &;|

# Create the logical vector
ind <- (mat$v1>=0.90 & mat$v3>=0.90  & mat$v3>=0.90) | (mat$v1>=0.90 & mat$v3< 0.50  & mat$v3< 0.50) | 
    (mat$v1 < 0.50 & mat$v3>=0.90  & mat$v3< 0.50) | (mat$v1< 0.50 & mat$v3< 0.50  & mat$v3>=0.90)

And now one can plot it e.g. using the plotly

# plot
plotly::plot_ly(x = mat$v1[ind], y = mat$v2[ind], z = mat$v3[ind])

RPlot

With the data

mat = structure(list(v1 = c(0.268, 0.975, 0.345, 0.901, 0.243, 0.001, 
  0.998, 0.954), v2 = c(0.917, 0.467, 0.898, 0.043, 0.453, 0.464, 
  0.976, 0.932), v3 = c(0.191, 0.447, 0.984, 0.456, 0.964, 0.953, 
  0.978, 0.923)), class = "data.frame", row.names = c(NA, -8L))

Upvotes: 0

Related Questions