pythonmatplotlibplanematplotlib-3d

Plot a surface passing through all the data points in 3D space


I am not really sure if this is possible to do, but essentially I have a list of data corresponding to x, y and z coordinates.

Below image shows the result when I plot these points using a scatter graph (which I created using Python pyplot library).

enter image description here

My question is, is there any way of plotting the graph of a plane that passes through all of these points instead of plotting them as single points?

When I searched online all I found was resources telling me how to find equation of plane passing though 3 points but as you can see I have many points.


Solution

  • Let's say that to have your plot you use this code

    fig, ax = plt.subplots(subplot_kw=dict(projection='3d'))
    ax.scatter(x, y, z)
    plt.show()
    

    and let's say that you know nrows, ncols, the number of rows (y) and columns (x) of your base grid.

    If these assumptions are correct, then you can use this code to plot a surface connecting the points

    fig, ax = plt.subplots(subplot_kw=dict(projection='3d'))
    ax.plot_surface(*(v.reshape(nrows, ncols) for v in (x, y, z)))
    plt.xlabel('x') ; plt.ylabel('y')
    plt.show()
    

    enter image description here

    or, if you want something fancier,

    fig, ax = plt.subplots(subplot_kw=dict(projection='3d'),
                           layout='constrained')
    surf = ax.plot_surface(*(v.reshape(nrows, ncols) for v in(x, y, z)),
                           cmap='Blues_r', ec='gray', lw=0.2)
    plt.xlabel('x') ; plt.ylabel('y')
    plt.colorbar(surf)
    plt.show()
    

    enter image description here


    The prelude to my code, if you want to check my results, is

    import numpy as np
    import matplotlib.pyplot as plt
    
    nrows, ncols = 63, 126
    x = np.linspace(0, 12.5, ncols)
    y = np.linspace(-6.2, 6.2, nrows)
    
    X, Y = np.meshgrid(x, y)
    x, y = (V.flatten() for V in (X, Y))
    z = np.sin(x)-np.cos(y)
    
    fig, ax = ...
    ...