1

I'm trying to make a 3d plot from a list of lists of values. All the sublists have the same number of values.

I tried this: Plot a 3d surface from a 'list of lists' using matplotlib , but I get the error:

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

Here is how to reproduce:

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

list_of_lists = [[1,2,3,4,1,2,3,4,1,2,3,4],[2,3,5,9,2,3,5,9,2,3,5,9],[5,9,8,1,5,9,8,1,5,9,8,1],[1,2,3,4,1,2,3,4,1,2,3,4],[2,3,5,9,2,3,5,9,2,3,5,9],[5,9,8,1,5,9,8,1,5,9,8,1]]

data = np.array(list_of_lists)
length = data.shape[0]
width = data.shape[1]
x, y = np.meshgrid(np.arange(length), np.arange(width))

fig = plt.figure()
ax = fig.add_subplot(1,1,1, projection='3d')
ax.plot_surface(x, y, data)
plt.show()

Thank you

Community
  • 1
  • 1
GeoffreyB
  • 536
  • 1
  • 7
  • 17

1 Answers1

2

Due to default cartesian indexing of meshgrid output (see docs for more info) your data has shape of (6, 12), but x and y have shapes of (12, 6). The easiest way to solve the problem is to transpose data array:

ax.plot_surface(x, y, data.T)

Or you can apply matrix indexing notation to meshgrid output:

x, y = np.meshgrid(np.arange(length), np.arange(width), indexing='ij')
Andrey Sobolev
  • 12,353
  • 3
  • 48
  • 52