在R Plotly中实现rgl风格的3D椭球曲面绘制求助
Hey there! I've got you covered. Instead of messing with converting to a grid for add_surface, we can use Plotly's add_mesh function which plays nicely with the triangular face data that ellipse3d generates. This lets us recreate that translucent ellipsoid surface just like in rgl, while keeping your internal data points visible.
Here's the complete working code:
library(plotly) library(rgl) # Generate your sample data dt <- cbind(x = rnorm(100), y = rnorm(100), z = rnorm(100)) # Create the 3D ellipse with rgl (including the data mean as the centre) ellipse <- ellipse3d(cov(dt), centre = colMeans(dt)) # Extract vertex coordinates (rgl stores them as a 4xN matrix; we only need the first 3 rows for x/y/z) vertices <- t(ellipse$vb[1:3, ]) # Extract triangular face indices (rgl uses 1-based indexing, Plotly needs 0-based so we subtract 1) faces <- t(ellipse$ib) - 1 # Build the Plotly figure p <- plot_ly() %>% # Add the translucent ellipsoid mesh add_mesh( x = vertices[, 1], y = vertices[, 2], z = vertices[, 3], i = faces[, 1], j = faces[, 2], k = faces[, 3], opacity = 0.3, # Adjust transparency here color = "red", showscale = FALSE ) %>% # Add your original data points add_trace( type = "scatter3d", x = dt[, 1], y = dt[, 2], z = dt[, 3], mode = "markers", marker = list(size = 3, color = "blue") ) %>% # Clean up the scene layout layout( scene = list( xaxis = list(title = "X"), yaxis = list(title = "Y"), zaxis = list(title = "Z") ) ) # Display the plot p
A quick breakdown of what's happening:
ellipse3dgives us two key pieces of data:vb(vertex coordinates) andib(indices defining each triangular face of the ellipsoid)- We convert the vertex matrix to a format Plotly understands, and adjust the face indices from rgl's 1-based to Plotly's 0-based numbering
add_meshrenders these triangles as a continuous surface, and we setopacity = 0.3to keep the internal data points visible- Finally, we add your original scatter points on top (they'll show clearly through the translucent surface)
If you want to tweak the appearance, just adjust the opacity value, color, or marker size to match your needs.
内容的提问来源于stack exchange,提问作者adrienne
相关产品推荐
相关产品推荐

