You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在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:

  • ellipse3d gives us two key pieces of data: vb (vertex coordinates) and ib (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_mesh renders these triangles as a continuous surface, and we set opacity = 0.3 to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:34:00