1
                                                                                                                                                                                                                                                                                                                                  
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!

4
  • 1
    You error is telling you much: lats is a 1D array with 4 Elements. It cannot be reshaped into a 4x4 matrix Commented Jan 14, 2022 at 6:58
  • So file1.txt is not correct then. Could you please give example how the data file should look like to make this code work? thanks, Commented Jan 14, 2022 at 12:06
  • 1
    No, there is no problem with your data file but how you intend to construct your contour plot. Commented Jan 14, 2022 at 12:07
  • How is that traceback related to your original question? Please don't add additional info in comments. Edit your question if neccessary, but don't ask new questions through edits. Commented Jan 14, 2022 at 12:29

1 Answer 1

2

Matplotlib expects a contour plot to receive data in a specific format. Your approach does not provide the data in this format; you have to transform your data like this:

import numpy as np
import matplotlib.pyplot as plt
#from matplotlib.colors import LogNorm
data = np.genfromtxt('test.txt', delimiter=' ')
#print(data)
lats =  data[:,0]
## lon => x                                                                                                                                                               
lons =  data[:,1]
## values => z                                                                                                                                                            
values = data[:,2]
###     
#get unique lat lon values and their index positions                                                                                                                                                                 
lat_uniq, lat_idx = np.unique(lats, return_inverse=True)
lon_uniq, lon_idx = np.unique(lons, return_inverse=True)

#create 2D array necessary for the contour plot
xre, yre = np.meshgrid(lon_uniq, lat_uniq)
zre = np.full(xre.shape, np.nan)
#or if you know the standard value of the array, fill it with that
#zre = np.full(xre.shape, 0)
zre[lat_idx, lon_idx] = values
print(zre)

#you can fill in missing data with interpolation
from scipy.interpolate import griddata 
zre_interpolated = griddata((lons, lats), values, (xre, yre), method = "linear")
print(zre_interpolated)

#### later in the defined map                                                                                                                                             
fig, (ax1, ax2) = plt.subplots(1,2, figsize = (10, 5))

cp1 = ax1.contourf(xre, yre, zre, levels=4)
plt.colorbar(cp1, ax=ax1)
ax1.set_title("data are not interpolated")

cp2 = ax2.contourf(xre, yre, zre_interpolated, levels=4)
plt.colorbar(cp2, ax=ax2)
ax2.set_title("interpolated data")

plt.show()

Example output: 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
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks, the code works by using your txt data file. But why it doesn't work if I use my txt file?
I cannot guess what your text file contains. I also do not know what "doesn't work" mean. No output, unexpected output, error message? How about asking a separate question with this code and a link to your input file or, if it is large, a smaller file that reproduces the problem.
Post the link to the new question, and I will have a look at it, if I have time. Initial guesses: 1) The data are not uniformly stored as lat lon val rows. 2) numpy misinterprets some numerical data as string or other values.
Sorry for the late reply, I'm trying to post the new question, getting "It looks like your post is mostly code; please add some more details." error.
Describe that you want to create a contour plot, link to the file that is problematic, link to this answer, and describe the nature of the problem for your file in contrast to my test file. That should do. I hope it is not the data 1 2 3/4 5 6/.... above - they are just discrete points from which no contour can be generated.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.