2

I have a file describing a grid over the earth with the format:

lon1,lat1,value1
lon2,lat2,value2
...

I wrote the following script in order to plot it:

import matplotlib.pyplot as plt
import numpy as np
import numpy.ma as ma


lons,lats,grads=np.loadtxt('surface.txt',dtype=str).T
lons=lons.astype(float).reshape(715,252)
lats=lats.astype(float).reshape(715,252)
grads[grads=='NA'] = np.nan
grads=grads.astype(float).reshape(715,252)
grads=ma.masked_where(np.isnan(grads),grads)

fig=plt.figure()
ax=plt.gca()
im=ax.pcolormesh(lons,lats,grads)
plt.colorbar(im)
plt.title('pcolormesh')

enter image description here

everything is working fine except for the artifact appearing at around y=-5.

I have plotted the same data with with contourf to make sure it's not in the data and the artifact is gone but I want to do it using pcolormesh.

fig=plt.figure()
ax=plt.gca()
im=ax.contourf(lons,lats,grads)
plt.colorbar(im)
plt.title('contourf')

enter image description here

I've found this related question but can't figure out a solution from it: matplotlib pcolormesh creates data artifacts

Community
  • 1
  • 1
OMRY VOLK
  • 1,429
  • 11
  • 24
  • Can you slice your data to a smaller rectangle, and still get this effect? – Eric Nov 08 '16 at 12:22
  • 2
    Your problem is that latitudes and longitudes are cyclic, and your largest longitude value wraps around – Eric Nov 08 '16 at 12:28
  • It's also worth noting that in this case `ax.pcolormesh(lons,lats,grads)` is the same as `ax.pcolormesh(lons,lats,grads[:-1,:-1])`, ie the last row and column of your data are being discarded – Eric Nov 08 '16 at 12:31
  • @Eric you are right about **"Your problem is that latitudes and longitudes are cyclic"** but I still can't figure out how to use that information to solve this problem – OMRY VOLK Nov 09 '16 at 15:47
  • Your x coordinates look like `[-30, 0, 30, .., 240, 270, -60]` (for example). That red box is `pcolor` drawing a rectangle from `270` to `-60` – Eric Nov 09 '16 at 16:44
  • @Eric you were right I sorted the longitudes to be continuous and it worked. I think this is worth a "real" answer – OMRY VOLK Nov 11 '16 at 13:06

1 Answers1

0

Following the comment by @Eric

Your problem is that latitudes and longitudes are cyclic, and your largest longitude value wraps around

I've changed the code to reorder the longitudes before plotting so that they are continuous.

data=np.loadtxt('surface.txt',dtype=str)
lons=data.T[0].astype(float)

#reorder the data so that lons smaller than 180 are before larger ones
data=np.hstack((data[lons<180].T,data[lons>=180].T))

lons,lats,grads=data
lons=lons.astype(float).reshape(715,252)
lats=lats.astype(float).reshape(715,252)
grads[grads=='NA']=np.nan
grads=grads.astype(float).reshape(715,252)

grads=ma.masked_where(np.isnan(grads),grads)

fig=plt.figure()
ax=plt.gca()
im=ax.pcolormesh(lons,lats,grads)
plt.colorbar(im)
plt.title('pcolormesh')

enter image description here

OMRY VOLK
  • 1,429
  • 11
  • 24