标题:如何在 Plotly 中将平面 y = x 添加到 3D 曲面图中?

问题描述 投票:0回答:1

我目前正在使用 Python 中的 Plotly 绘制 3D 曲面图。下面是我到目前为止的代码:

import numpy as np
import plotly.graph_objects as go

# Definition of the domain
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)

# Definition of the function, avoiding division by zero
Z = np.where(X**2 + Y**2 != 0, (X * Y) / (X**2 + Y**2), 0)

# Creation of the interactive graph
fig = go.Figure(data=[go.Surface(z=Z, x=X, y=Y, colorscale='Viridis')])

# Add title and axis configurations
fig.update_layout(
    title='Interactive graph of f(x, y) = xy / (x^2 + y^2)',
    scene=dict(
        xaxis_title='X',
        yaxis_title='Y',
        zaxis_title='f(X, Y)'
    ),
)

# Show the graph
fig.show()

我想将平面 (y = x) 添加到该图中。但是,我无法弄清楚如何做到这一点。

任何人都可以提供有关如何将此平面添加到我现有的曲面图中的指导吗?任何帮助将不胜感激!

谢谢!

python numpy plotly
1个回答
0
投票

要将“𝑦=𝑥”添加到 Plotly 中的 3D 曲面图,您可以为此平面定义一个单独的曲面,并使用另一个“go.Surface”对象将其添加到图形中。

这是我修改的新代码,

import numpy as np
import plotly.graph_objects as go

# Definition of the domain
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)

# Definition of the function, avoiding division by zero
Z = np.where(X**2 + Y**2 != 0, (X * Y) / (X**2 + Y**2), 0)

# Creation of the main surface plot
fig = go.Figure(data=[go.Surface(z=Z, x=X, y=Y, colorscale='Viridis')])

# Define the plane y = x over the same domain
Y_plane = X  # Since y = x
Z_plane = np.zeros_like(X)  # For a flat plane at Z=0 or another value

# Add the plane to the plot
fig.add_trace(go.Surface(z=Z_plane, x=X, y=Y_plane, colorscale='Reds', opacity=0.5))

# Add title and axis configurations
fig.update_layout(
    title='3D Surface Plot with Plane y = x',
    scene=dict(
        xaxis_title='X',
        yaxis_title='Y',
        zaxis_title='f(X, Y)'
    ),
)

# Show the graph
fig.show()

输出是 output

© www.soinside.com 2019 - 2024. All rights reserved.