Alexander K
Alexander K

Reputation: 137

Creating a matplotlib 3D surface plot from lists

i want to create a surface plot of the lists shown in the code. It's a simplification of data i'll import from an excel file once i figured out how to plot it.

x and y should represent the plane from which the z-values emerge. I created a random matrix to pair up with the 3x10 values from x,y.

This is the error Message:

ValueError: shape mismatch: objects cannot be broadcast to a single shape

import matplotlib.pyplot as plt
import numpy as np


x = [0,1,2,3,4,5,6,7,8,9,10] #creating random data
y = [0,1,2,3]
a = np.random.rand (3, 10)

z = np.array(a, ndmin=2) #not really sure if this piece is necessary. 


fig = plt.figure()
ax = fig.add_subplot(1,1,1, projection='3d')

x, y = np.meshgrid(x, y)
ax.plot_surface(x, y, z)
plt.show()

ValueError: shape mismatch: objects cannot be broadcast to a single shape

I've already tried to leave z = np.array(a, ndmin=2) out. Didn't work either.

Upvotes: 2

Views: 209

Answers (1)

Sheldore
Sheldore

Reputation: 39072

The problem is two-fold:

  • First, you have 4x11 points and not 3x10 points
  • Second, you need to import Axes3D for enabling the 3d plotting. You don't need to use additionally z = np.array(a, ndmin=2) I think

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

x = [0,1,2,3,4,5,6,7,8,9,10] #creating random data
y = [0,1,2,3]
a = np.random.rand(4, 11)
x, y = np.meshgrid(x, y)

fig = plt.figure()
ax = fig.add_subplot(1,1,1, projection='3d')

ax.plot_surface(x, y, a)
plt.show()

enter image description here

Upvotes: 1

Related Questions