Color matplotlib plot_surface command with surface gradient

后端 未结 1 1117
一个人的身影
一个人的身影 2020-11-29 03:18

I would like to convert surf command from MATLAB to plot_surface command in matplotlib.

The challenge I am facing is when using

相关标签:
1条回答
  • 2020-11-29 03:34

    First, it looks like you want the colors mapped from gradient magnitude. You are trying to use the gradient vectors which is why you are getting the 'list' error.

    Second, you can supply a cmap, but it only defines how you want the Z values mapped to a color. If you want new face colors then use the facecolors argument.

    Third, you'll want to normalize the values to 0..1 then map them thru a colormap. (I think there is another way, but dividing the magnitude by the max is pretty simple)

    Here's the code:

    # Python-matplotlib Commands
    from mpl_toolkits.mplot3d import Axes3D
    from matplotlib import cm
    import matplotlib.pyplot as plt
    import numpy as np
    
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    X = np.arange(-5, 5, .25)
    Y = np.arange(-5, 5, .25)
    X, Y = np.meshgrid(X, Y)
    R = np.sqrt(X**2 + Y**2)
    Z = np.sin(R)
    Gx, Gy = np.gradient(Z) # gradients with respect to x and y
    G = (Gx**2+Gy**2)**.5  # gradient magnitude
    N = G/G.max()  # normalize 0..1
    surf = ax.plot_surface(
        X, Y, Z, rstride=1, cstride=1,
        facecolors=cm.jet(N),
        linewidth=0, antialiased=False, shade=False)
    plt.show()
    

    And the result:

    enter image description here

    0 讨论(0)
提交回复
热议问题