0

Please consider this code:

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

x = np.array([0,1,2,3,4,5])
y = np.array([1,2,3])            
z = np.array([[ 0,  1,  4,  9, 16, 25],
       [ 0,  2,  8, 18, 32, 50],
       [ 0,  3, 12, 27, 48, 75]])

plt.figure().add_subplot(111, projection='3d').plot_surface(x, y, z, rstride=1, cstride=1,cmap='viridis')

This will return: shape mismatch: objects cannot be broadcast to a single shape. If you google Python 3D plot for help mostly you will find how to plot from functions by generating data with meshgrid. However my question is. What is the easiest way to plot when you have an array? The solution to this problem should look something like this: enter image description here

For instance one point is (x=3,y=2,z=18)

k.dkhk
  • 481
  • 1
  • 11
  • 24
  • Doesn't Matplotlib plot points, so this is really just a meshgrid but spaced out entirely too far? – Bryce Wayne Jul 04 '19 at 21:10
  • I think you are right. And that's even more confusing to me that this will not work? – k.dkhk Jul 04 '19 at 21:14
  • 2
    You find functions in most examples, simply because people are too lazy to type in a complete array. Matplotlib itself plots points. For `plot_surface` all input arrays must be 2D. That is shown in the existent examples, so closing this as duplicate. – ImportanceOfBeingErnest Jul 04 '19 at 21:30

1 Answers1

1

You need to match the shapes for each axis. You can do this using numpy.meshgrid which makes a mesh grid with x and y:

x = np.array([0,1,2,3,4,5])
y = np.array([1,2,3])
x, y = np.meshgrid(x, y) # make a meshgrid out of x and y
z = np.array([[ 0,  1,  4,  9, 16, 25],
       [ 0,  2,  8, 18, 32, 50],
       [ 0,  3, 12, 27, 48, 75]])

plt.figure().add_subplot(111, projection='3d').plot_surface(x, y, z, rstride=1, cstride=1,cmap='viridis')
plt.show()

x after meshgrid:

 [[0 1 2 3 4 5]
 [0 1 2 3 4 5]
 [0 1 2 3 4 5]]

y after meshgrid:

[[1 1 1 1 1 1]
 [2 2 2 2 2 2]
 [3 3 3 3 3 3]]
Ricky Kim
  • 1,992
  • 1
  • 9
  • 18