Home > Back-end >  ValueError: cannot reshape array - contour plot python
ValueError: cannot reshape array - contour plot python

Time:01-15

                                                                                                                                                                                                                                                                                                                                  
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
data = np.genfromtxt('file1.txt',delimiter=' ')
lats =  data[:,0]
## lon => x                                                                                                                                                               
lons =  data[:,1]
## values => z                                                                                                                                                            
values = data[:,2]
###                                                                                                                                                                       
lat_uniq = list(set(lats.tolist()))
nlats = len(lat_uniq)
print(nlats)
print(lat_uniq)
lon_uniq = list(set(lons.tolist()))
print(lon_uniq)
nlons = len(lon_uniq)
print(nlons)
print (lats.shape, nlats, nlons)
yre = lats.reshape(nlats,nlons)
xre = lons.reshape(nlats,nlons)
zre = values.reshape(nlats,nlons)
#### later in the defined map                                                                                                                                             
fig,ax=plt.subplots(1,1)
cp = ax.contourf(xre, yre, zre)
fig.colorbar(cp)
plt.savefig('f1.pdf')

file1.txt

1 2 3

4 5 6

7 8 9

10 11 12 ..

First column - x values, Second - y values, third - z values

I'm using the code to make a contour plot in python, but getting the following error:

Traceback (most recent call last): File "./yut.py", line 21, in yre = lats.reshape(nlats,nlons) ValueError: cannot reshape array of size 4 into shape (4,4)

Could you please help to fix this error? Thanks in advance!

CodePudding user response:

Matplotlib expects a enter image description here

The example output was generated using the following data in the txt file:

1 1 1
1 2 2
2 4 9
4 5 2
6 1 1
6 2 8
6 4 9
6 5 2
2 5 3
4 2 5
4 3 8
4 4 5 
1 3 4
1 5 2
2 1 1
2 3 4

CodePudding user response:

The variable "lats" you get is a 4 * 1 NumPy array. It only has 4 elements. If you want to reshape it into 4 * 4 array, you need 16 elements(16 * 1 NumPy array). Add another 12 rows to "file1.txt" will fix this error since the "lats" you read will be 16 * 1 NumPy array.

  •  Tags:  
  • Related