0

I've got a set of x values, y values and the corresponding z value at each (X,Y)

I'm trying to plot a contour plot in matplotlib but whenever I try to plot the contours I get the following error:-

TypeError: Input z must be 2D, not 1D

I don't understand how I'm supposed to input a 2D array of z values when I only have one value for each (x,y) point

Edit: Apologies for not including my code

x= [7.7, 7.7, 7.7, 7.7, 7.7, 6.7, 6.7, 6.7, 6.7, 6.7, 5.8, 5.8, 5.8, 5.8, 5.8, 4.8, 4.8, 4.8, 4.8, 4.8, 3.9, 3.9, 3.9, 3.9, 3.9, 2.9, 2.9, 2.9, 2.9, 2.9]
y= [3, 4, 5, 6, 7, 2, 4.5, 5, 6.7, 8, 3.2, 4.5, 5.5, 6, 7.5, 4.3, 8.5, 7, 6.4, 3.5, 2.4, 4.5, 6.8, 7.5, 8, 2.5, 4.3, 5.4, 7.6, 8.2]
z= [1, 1, 1, 1, 1, 1.5, 1.5, 1.5, 1.5, 1.5, 2, 2, 2, 2, 2, 2.5, 2.5, 2.5, 2.5, 2.5, 3, 3, 3, 3, 3, 3.5, 3.5, 3.5, 3.5, 3.5]

X, Y = np.meshgrid(x, y)

fig,ax=plt.subplots(1,1)
ax.plot(X,Y,color='green')
cp = ax.contourf(X, Y, z)
fig.colorbar(cp) # Add a colorbar to a plot
plt.show()
blackraven
  • 5,284
  • 7
  • 19
  • 45
codin
  • 3
  • 2
  • Please show us a minimal version of your code so that the community can analyze it and offer suggestions. – NoDakker Aug 11 '22 at 16:41
  • Hi, sorry about that. I've included my code in the original post – codin Aug 11 '22 at 16:49
  • If you follow python's error stack trace it should give you something like `../site-packages/matplotlib/contour.py", line 1508, in _check_xyz raise TypeError(f"Input z must be 2D, not {z.ndim}D")` open that file and read that code, there's a clue written in comments by the programmer who wrote it, see: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.contour.html and https://matplotlib.org/stable/gallery/images_contours_and_fields/contour_demo.html and your answer becomes clear. Wrap Z in a meshgrid which promotes your 1D list to 2D, and then `_check_xyz` stops complaining. – Eric Leschinski Aug 11 '22 at 17:13
  • Does this answer your question? [Contour/imshow plot for irregular X Y Z data](https://stackoverflow.com/questions/27004422/contour-imshow-plot-for-irregular-x-y-z-data) – Jody Klymak Aug 11 '22 at 21:28

1 Answers1

1

You must check the contour function in Matplotlib there (same for contourf). Z must me a 2D array whereas X,Y could be one dimensional array-like.

In your case :

X.shape = (30, 30)
Y.shape = (30, 30)
len(z) = 30

I would suggest you to reshape your Z array using np.reshape() to have the dimension you want or duplicate (np.tile) the vector to create a 30 by 30 matrix matrix but it depends of what is exactly Z for your data and X,Y coordinates.

Only god knows
  • 307
  • 1
  • 10