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

Plotly在VS Code中仅显示坐标轴,等值面无法渲染问题排查

问题:Plotly等值面仅显示坐标轴无内容的排查与解决

问题场景

运行以下Python代码后,Plotly绘图区域仅显示坐标轴,无等值面内容,但通过np.any((r > 0.1) & (r < 0.5))验证确认存在符合等值面条件的数据点。

原代码

import numpy as np
import plotly.graph_objects as go

# Create a three-dimensional grid of points.
x = np.linspace(-1, 1, 100)
y = np.linspace(-1, 1, 100)
z = np.linspace(-1, 1, 100)

# Calculate the distance from each point to the origin.
r = np.sqrt(x**2 + y**2 + z**2)

# Create an isosurface trace.
isosurface_trace = go.Isosurface(
    x=x,
    y=y,
    z=z,
    value=r,
    surface_count=10,
    opacity=0.5,
    isomin=0.1,
    isomax=0.5
)

# Create a figure and add the isosurface trace.
fig = go.Figure()
fig.add_trace(isosurface_trace)

# Add axes and a title.
fig.update_layout(
    scene=dict(
        xaxis=dict(title="X"),
        yaxis=dict(title="Y"),
        zaxis=dict(title="Z"),
    ),
    title="Isosurface of a sphere",
)

# Display the figure.
fig.show()

运行截图

VS Code中运行后的空白坐标轴输出

问题原因

代码存在逻辑错误,未生成正确的三维网格数据:

  • 原代码中x、y、z均为一维数组,直接计算r = np.sqrt(x**2 + y**2 + z**2)时,是按一维数组的元素对应位置计算,得到的r也是一维数组。
  • Plotly的Isosurface组件需要的是三维网格数据(即每个点的x、y、z坐标构成三维空间中的网格点),一维数组无法构建出等值面所需的三维空间结构。

修正后的代码

使用np.meshgrid生成三维网格数据,再计算每个网格点到原点的距离:

import numpy as np
import plotly.graph_objects as go

# 生成一维坐标数组
x = np.linspace(-1, 1, 50)
y = np.linspace(-1, 1, 50)
z = np.linspace(-1, 1, 50)

# 转换为三维网格数据
X, Y, Z = np.meshgrid(x, y, z)

# 计算每个网格点到原点的距离
r = np.sqrt(X**2 + Y**2 + Z**2)

# 创建等值面轨迹
isosurface_trace = go.Isosurface(
    x=X.flatten(),
    y=Y.flatten(),
    z=Z.flatten(),
    value=r.flatten(),
    surface_count=10,
    opacity=0.5,
    isomin=0.1,
    isomax=0.5
)

# 创建图并添加轨迹
fig = go.Figure()
fig.add_trace(isosurface_trace)

# 更新布局
fig.update_layout(
    scene=dict(
        xaxis=dict(title="X"),
        yaxis=dict(title="Y"),
        zaxis=dict(title="Z"),
    ),
    title="Isosurface of a sphere",
)

# 显示图形
fig.show()

关键修改说明

  1. 用np.meshgrid(x, y, z)将一维坐标转换为三维网格矩阵X、Y、Z,每个矩阵对应三维空间中所有点的x、y、z坐标。
  2. 计算r时基于三维网格矩阵,得到每个网格点的距离值。
  3. 将三维网格矩阵和r通过flatten()转换为一维数组,符合Plotly Isosurface组件的参数要求。

修改后运行代码,即可正常显示0.1到0.5之间的球形等值面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 05:46:30