Search code examples
rplotlyr-plotly

COLOR OF Mesh3d objects with plotly


I am trying to draw ellipsoids using Mesh3d plotly. Only problem, I can't change the color. There is a lot of parameters for the colour (colorscale, colorface, colorbar, ...), is there any way to control the color of each ellipsoid ?

My code:

Color1<-c("#A6CEE3","#1F78B4","#8DA0CB","#33A02C","#FB9A99","#E31A1C","#FDBF6F","#FF7F00",
          "#CAB2D6","#6A3D9A","#FFFF99","#B15928","#66C2A5","#FC8D62","B2DF8A","#E78AC3")

fig <- plot_ly(x = BD_PCA[,1], y = BD_PCA[,2], z = BD_PCA[,3])
fig <- fig %>% layout(scene = list(xaxis = list(title = 'PCA1'),
                                   yaxis = list(title = 'PCA2'),
                                   zaxis = list(title = 'PCA3')))

for(i in levels(data_CSV$groups)){
      ellipse <- ellipse3d(cov(cbind(x = BD_PCA[data_CSV$groups==i,1],
                                     y = BD_PCA[data_CSV$groups==i,2],
                                     z = BD_PCA[data_CSV$groups==i,3])),
                           centre=c(mean(BD_PCA[data_CSV$groups==i,1]),
                                    mean(BD_PCA[data_CSV$groups==i,2]),
                                    mean(BD_PCA[data_CSV$groups==i,3])), level = 0.4)
      
      
      fig <- fig %>% add_trace(x=ellipse$vb [1,], y=ellipse$vb [2,], z=ellipse$vb [3,],
                               type='mesh3d', alphahull = 0, opacity = 0.3,name=i,showlegend = T,
                               autocolorscale=FALSE,color=Color1[strtoi(i)]),cauto=FALSE)
}
fig <- fig %>%
  add_trace(
    x = BD_PCA[nrow(BD_PCA),1],y = BD_PCA[nrow(BD_PCA),2],z = BD_PCA[nrow(BD_PCA),3],
    marker = list(color = 'black',symbol='square-dot',size = 5),name="Tested results",showlegend = F)

fig <- fig %>% layout(legend = list(x = 1, y = 1))
plot(fig)

Ellipses with autocolor: ellipses with autocolor


Solution

  • The doc says that the argument color sets the color of the whole mesh, but I tried and it didn't work. You can use facecolor, but then you must provide one color for each face:

    library(plotly)
    library(rgl)
    
    Sigma <- matrix(c(10, 3, 0, 3, 2, 0, 0, 0, 1), 3, 3)
    Mean <- 1:3
    ellipsoid <- 
      ellipse3d(Sigma, centre = Mean, subdivide = 5) # this is a mesh of quads
    ellipsoid <- Morpho::quad2trimesh(ellipsoid) # we triangulate it
    
    plot_ly(
      x = ellipsoid$vb[1,], y = ellipsoid$vb[2,], z = ellipsoid$vb[3,],
      i = ellipsoid$it[1,]-1, j = ellipsoid$it[2,]-1, k = ellipsoid$it[3,]-1,
      type = "mesh3d",
      facecolor = rep("#ff0000", ncol(ellipsoid$it))
    ) %>% layout(scene = list(aspectmode = "data"))
    

    enter image description here