pythonnumpyplotly

How to add the plane y = x to a 3D surface plot in Plotly?


I am currently working on a 3D surface plot using Plotly in Python. Below is the code I have so far:

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()

I would like to add the plane (y = x) to this plot. However, I am having trouble figuring out how to do this.

Can anyone provide guidance on how to add this plane to my existing surface plot? Any help would be greatly appreciated!


Solution

  • To add '𝑦=𝑥' to your 3D surface plot in Plotly, you can define a separate surface for this plane and add it to the figure using another 'go.Surface' object.

    In Plotly, the Surface plot requires explicit values for 𝑍 to display a plane. To achieve the 𝑦=𝑥 plane across a given 𝑍 range, we need to set both 𝑋 and 𝑌 to represent 𝑦=𝑥 over a flat range of 𝑍.

    Here is the new code that I modified,

    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 y = x plane
    x_plane = np.linspace(-5, 5, 100)
    y_plane = x_plane  # y = x
    X_plane, Z_plane = np.meshgrid(x_plane, np.linspace(-1, 1, 2))  # Z range can be adjusted as needed
    Y_plane = X_plane  # Since y = x
    
    # Add the y = x plane to the plot
    fig.add_trace(go.Surface(z=Z_plane, x=X_plane, 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()
    

    and the output is output