Matplotlib 3D plot - 2D format for input data?

前端 未结 2 980
执笔经年
执笔经年 2020-12-06 03:44

I am plotting a function of two parameters with matplotlib. I copied an example in matplotlib tutorial and transformed with my own input data: vectors X and Y (equally space

相关标签:
2条回答
  • 2020-12-06 04:05

    You need to generate the meshgrid. X,Y and Z must be 2D arrays

    import numpy
    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import axes3d
    
    def peaks(x,y):
        return x * numpy.sin(y)
    
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    X = Y= numpy.arange(-3, 3, 0.1).tolist()
    X, Y = numpy.meshgrid(X, Y)
    
    Z = []
    for i in range(len(X)):
        Z.append(peaks(X[i],Y[i]))
    
    # Z must be an array
    Z = numpy.array(Z)
    
    ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3)
    cset = ax.contour(X, Y, Z, zdir='z', offset=-8)
    cset = ax.contour(X, Y, Z, zdir='x', offset=-8)
    cset = ax.contour(X, Y, Z, zdir='y', offset=8)
    
    ax.set_xlabel('X')
    ax.set_xlim(-8, 8)
    ax.set_ylabel('Y')
    ax.set_ylim(-8, 8)
    ax.set_zlabel('Z')
    ax.set_zlim(-8, 8)
    
    plt.show()
    

    enter image description here

    0 讨论(0)
  • 2020-12-06 04:14

    The accepted answer no longer works. Sadly reviewers rejected my suggested edit which would have made it a working asnwer. So here is the same answer again but with the small change necessary to make it work in the current release of matplotlib.

        import numpy
        import matplotlib.pyplot as plt
        from mpl_toolkits.mplot3d import axes3d
    
        def peaks(x,y):
            return x * numpy.sin(y)
    
        fig = plt.figure()
        ax = fig.gca(projection='3d')
        X = Y= numpy.arange(-3, 3, 0.1).tolist()
        X, Y = numpy.meshgrid(X, Y)
    
        Z = numpy.zeros(X.shape)
        for i in range(len(X)):
            for j in range(len(Y)):
                Z[i,j] = peaks(X[i,j],Y[i,j])
    
        ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3)
        cset = ax.contour(X, Y, Z, zdir='z', offset=-8)
        cset = ax.contour(X, Y, Z, zdir='x', offset=-8)
        cset = ax.contour(X, Y, Z, zdir='y', offset=8)
    
        ax.set_xlabel('X')
        ax.set_xlim(-8, 8)
        ax.set_ylabel('Y')
        ax.set_ylim(-8, 8)
        ax.set_zlabel('Z')
        ax.set_zlim(-8, 8)
    
        plt.show()
    
    0 讨论(0)
提交回复
热议问题