user4421975 user4421975 - 26 days ago 6
Python Question

matplotlib pcolormesh artifact

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

Answer

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