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

如何在Plotly 3D曲面图中添加指定曲线?求其他工具方案

在R中给3D曲面添加空间曲线x*y=10的解决方案

一、Plotly实现方案(延续你的现有工作)

核心思路:x*y=10是3D空间中的曲线,每个点的z值由曲面公式z = sin(sqrt(x^2 + y^2))/sqrt(x^2 + y^2)计算得出。先生成曲线上的点数据,再用add_trace添加连线轨迹即可。

library(plotly)

# 1. 生成3D曲面数据
x <- seq(-15, 15, length.out = 50)
y <- seq(-15, 15, length.out = 50)
df_surface <- expand.grid(x = x, y = y)
df_surface$z <- with(df_surface, sin(sqrt(x^2 + y^2))/sqrt(x^2 + y^2))
# 处理原点的NaN(sin(0)/0的极限为1)
df_surface$z[is.na(df_surface$z)] <- 1

# 2. 生成曲线x*y=10的点数据(包含正负两支)
# 正分支
x_curve_pos <- seq(1, 10, length.out = 100)
y_curve_pos <- 10 / x_curve_pos
z_curve_pos <- sin(sqrt(x_curve_pos^2 + y_curve_pos^2))/sqrt(x_curve_pos^2 + y_curve_pos^2)
# 负分支
x_curve_neg <- seq(-10, -1, length.out = 100)
y_curve_neg <- 10 / x_curve_neg
z_curve_neg <- sin(sqrt(x_curve_neg^2 + y_curve_neg^2))/sqrt(x_curve_neg^2 + y_curve_neg^2)
# 合并曲线数据
df_curve <- rbind(
  data.frame(x = x_curve_pos, y = y_curve_pos, z = z_curve_pos),
  data.frame(x = x_curve_neg, y = y_curve_neg, z = z_curve_neg)
)

# 3. 绘制曲面并叠加曲线
p <- plot_ly() %>%
  add_surface(data = df_surface, z = ~z, x = ~x, y = ~y, colorscale = "Viridis", opacity = 0.7) %>%
  add_trace(data = df_curve, x = ~x, y = ~y, z = ~z, type = "scatter3d", mode = "lines",
            line = list(color = "red", width = 4)) %>%
  layout(scene = list(xaxis = list(title = "X"), yaxis = list(title = "Y"), zaxis = list(title = "Z")))

p

二、其他R工具替代方案

方案1:plot3D包(静态3D绘图)

plot3D语法更贴近传统绘图逻辑,适合快速生成静态3D图:

library(plot3D)
library(viridis)

# 曲面数据
x <- seq(-15, 15, length.out = 50)
y <- seq(-15, 15, length.out = 50)
z <- outer(x, y, function(x, y) sin(sqrt(x^2 + y^2))/sqrt(x^2 + y^2))
z[is.na(z)] <- 1

# 曲线数据
x_curve <- c(seq(1,10,length.out=100), seq(-10,-1,length.out=100))
y_curve <- 10 / x_curve
z_curve <- sin(sqrt(x_curve^2 + y_curve^2))/sqrt(x_curve^2 + y_curve^2)

# 绘制曲面+曲线
persp3D(x, y, z, colvar = z, col = viridis(100), theta = 30, phi = 30,
        xlab = "X", ylab = "Y", zlab = "Z", box = TRUE)
lines3D(x_curve, y_curve, z_curve, col = "red", lwd = 3, add = TRUE)

方案2:rgl包(交互式3D绘图)

rgl支持鼠标拖拽旋转视图,交互性更强:

library(rgl)
library(viridis)

# 曲面数据
x <- seq(-15, 15, length.out = 50)
y <- seq(-15, 15, length.out = 50)
z <- outer(x, y, function(x, y) sin(sqrt(x^2 + y^2))/sqrt(x^2 + y^2))
z[is.na(z)] <- 1

# 绘制曲面
surface3d(x, y, z, col = viridis(100)[cut(z, 100)], alpha = 0.7)
# 添加曲线
x_curve <- c(seq(1,10,length.out=100), seq(-10,-1,length.out=100))
y_curve <- 10 / x_curve
z_curve <- sin(sqrt(x_curve^2 + y_curve^2))/sqrt(x_curve^2 + y_curve^2)
lines3d(x_curve, y_curve, z_curve, color = "red", lwd = 3)
# 添加坐标轴与标题
axes3d()
title3d(xlab = "X", ylab = "Y", zlab = "Z")

内容的提问来源于stack exchange,提问作者yuw444

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 19:17:49