pythonnumpymatplotlib

Plot 3D graph using Python


I trying to plot a graph of a function f(x, y) = x**x*y, but I'm getting an error:

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

def f(x,y):
    return x**x*y

x = np.arange(-4.0, 4.0, 0.1)
y = np.arange(-4.0, 4.0, 0.1)
z = f(x, y)
X, Y, Z = np.meshgrid(x, y, z)

fig = plt.figure()
ax = Axes3D(fig)
ax.plot_surface(X, Y, Z)
plt.xlabel('x')
plt.ylabel('y')
plt.show()

First error is:

/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:2: RuntimeWarning: invalid value encountered in power

And the second is:

ValueError: Argument Z must be 2-dimensional.


Solution

  • You can try:

    X, Y = np.meshgrid(x, y)
    Z = f(X, Y)
    

    The meshgrid function returns coordinate matrices from coordinate vectors.. Then, you can apply the function and plot it.

    For the "RuntimeWarning: invalid value encountered in power" warning, that is related to the decimal power on numpy objects. Please have a look at this topic NumPy, RuntimeWarning: invalid value encountered in power for more details.


    Full code:

    import matplotlib.pyplot as plt
    import numpy as np
    from mpl_toolkits.mplot3d import Axes3D
    
    def f(x,y):
        return x**x*y
    
    x = np.arange(-4.0, 4.0, 0.1)
    y = np.arange(-4.0, 4.0, 0.1)
    X, Y = np.meshgrid(x, y)
    Z = f(X, Y)
    
    fig = plt.figure()
    ax = Axes3D(fig)
    ax.plot_surface(X, Y, Z)
    plt.xlabel('x')
    plt.ylabel('y')
    plt.show()
    

    Output:

    enter image description here