pythonnumpymatplotlib

Trying to plot a function using python (matplotlib and numpy) and am running into a Value Errors and a Type Error if I alter it slightly


I am trying to graph this equation and am currently running into these errors. I am importing numpy and matplotlib with python. I am not sure how to fix these errors

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np


def equation(delta=0.05):
    #for K = 3
    #from matplotlib.mlab import bivariate_normal

    x = y = np.arange(0,1,delta)
    #y = np.arange(0,1,delta)
    #x = np.arange(0.4,1,delta)
    X,Y = np.meshgrid(x,y)

    Z = (3*y-y-9*x+2*3*x)**2 - 4(9*x-3*x)(y-3*y+3-3*x)
    return X, Y, Z
#x = F
#y = P

fig = plt.figure()
#ax = fig.add_subplot(111, projection'3d')
ax = Axes3D(equation(0.05))

x,y,z = Axes3D.equation(0.05)
ax.plot_wireframe(x,y,z, rstride=5, cstride=5)
plt.show()

There is a Type Error when using x = y = np.arange(0,1,delta) which says that int is not callable. When using y = np.arange(0,1,delta) and x = np.arange(0.4,1,delta) instead, I am getting a Value Error

ValueError: operands could not be broadcast together with shapes (20,) (12,).


Solution

  • welcome to StackOverflow!

    There are several things that need fixing with your code-

    1. As mentioned by Le Hoang Giang your multiplications are missing a couple of asterixes. When you write 4(9*x-3*x) python tries to use the "4" as a function, which is not callable, hence the error.

    2. You need to calculate Z using X & Y (caps) not x,y, so you get a 2d surface.

    3. Your usage of Axes3D is not according to the reference.

    Please find below a working version of your code.

    from mpl_toolkits.mplot3d import Axes3D
    import matplotlib.pyplot as plt
    import numpy as np
    
    
    def equation(delta=0.05):
        #for K = 3
        #from matplotlib.mlab import bivariate_normal
    
        x = y = np.arange(0,1,delta)
        #y = np.arange(0,1,delta)
        #x = np.arange(0.4,1,delta)
        X,Y = np.meshgrid(x,y)
    
        Z = (3*Y-Y-9*X+2*3*X)**2 - 4*(9*X-3*X)*(Y-3*Y+3-3*X)
    
    
        return X, Y, Z
    #x = F
    #y = P
    
    fig = plt.figure()
    #ax = fig.add_subplot(111, projection'3d')
    ax = Axes3D(fig)
    
    x,y,z = equation(0.05)
    ax.plot_wireframe(x,y,z, rstride=5, cstride=5)
    plt.show()