Bird
0
0

Why does this code raise an error?

medium📝 Debug Q7 of 15
Matplotlib - 3D Plotting
Why does this code raise an error?
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X = np.linspace(-1, 1, 10)
Y = np.linspace(-1, 1, 10)
Z = np.sin(X * Y)
ax.plot_surface(X, Y, Z)
plt.show()
Aplot_surface requires integer arrays
Bsin function cannot be applied element-wise
CMissing import for mpl_toolkits.mplot3d
DX, Y, Z must be 2D arrays of the same shape, but here they are 1D or mismatched
Step-by-Step Solution
Solution:
  1. Step 1: Check shapes of X, Y, Z

    X and Y are 1D arrays; Z is computed element-wise but results in 1D array, not 2D meshgrid shape.
  2. Step 2: plot_surface requires 2D arrays

    plot_surface needs X, Y, Z as 2D arrays of the same shape, usually created by meshgrid.
  3. Final Answer:

    X, Y, Z must be 2D arrays of the same shape, but here they are 1D or mismatched -> Option D
  4. Quick Check:

    Use meshgrid to create 2D arrays for surface plots [OK]
Quick Trick: Use meshgrid to create 2D arrays for X, Y, Z [OK]
Common Mistakes:
  • Passing 1D arrays directly to plot_surface
  • Assuming sin cannot be applied element-wise
  • Forgetting to import 3D toolkit

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Matplotlib Quizzes