2

Can anyone help me with plotting a 3D surface plot for the equation f(x,y) = (x-y)^2

The Z axis should represent the function f(x,y)

I have the below function:

def fnc(X):
    return (X[0] - X[1]) ** 2

Here X is a numpy array with first parameter as X and the second as Y. I specifically need it to be this way. So please don't suggest me to change the signature. ;)

I tried the below from this solution:

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = y = np.linspace(-5,5,100)
X, Y = np.meshgrid(x, y)
Z = fnc1([np.linspace(-5,5,100) , np.linspace(-6,6,100)])
ax.plot_surface(X, Y, Z)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()

However i get the wrong plot.

This is a wrong plot though

Community
  • 1
  • 1
rapidclock
  • 1,677
  • 2
  • 17
  • 32

2 Answers2

3

Your fnc is wrong. Get your surface just as Z=(X-Y)**2. It is the best solution because of all calculations of Z would be vectorized.

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

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = y = np.linspace(-5,5,100)
X, Y = np.meshgrid(x, y)
Z = (X-Y)**2
ax.plot_surface(X, Y, Z)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()

enter image description here

Serenity
  • 35,289
  • 20
  • 120
  • 115
2

The array Z to be plotted should be a 2D array, just like X and Y are 2D arrays, such that for each pair of values from X and Y you get exactly one point in Z. It therefore makes sense to use those arrays X and Y as input to your fnc function, Z = fnc([X,Y])

The complete code would look like

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


def fnc(X):
    return (X[0] - X[1]) ** 2

fig = plt.figure()
ax = fig.add_subplot(111, projection=Axes3D.name)
x = y = np.linspace(-5,5,100)
X, Y = np.meshgrid(x, y)
Z = fnc([X,Y])
ax.plot_surface(X, Y, Z)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
ax.view_init(elev=15, azim=-118)
plt.show()

enter image description here

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712