python - pcolormesh with masked invalid values -
i'm trying plot one-dimensional array pcolormesh (so color varies along x-axis, constant in y-axis each x). data has bad values, i'm using masked array , customized colormap masked values set blue:
import numpy np import matplotlib.pyplot plt import matplotlib.cm cm import copy = np.array([3, 5, 10, np.inf, 5, 8]) = np.ma.masked_where(np.isinf(a), a) imdata = np.vstack((a, a)) myhot = copy.copy(cm.hot) myhot.set_bad('b', 1) fig, ax = plt.subplots() im = ax.pcolormesh(imdata, cmap=myhot) plt.colorbar(im) plt.show() it works fine if don't have np.inf value, blank plot if do. seem have misunderstood way set_bad works because additional warning:
runtimewarning: invalid value encountered in true_divide resdat /= (vmax - vmin) what should doing effect want?
you need mask imdata, not a:
import numpy np import matplotlib.pyplot plt = np.array([3, 5, 10, np.inf, 5, 8]) imdata = np.ma.masked_invalid(np.atleast_2d(a)) cmap = plt.cm.hot cmap.set_bad('b', 1) fig, ax = plt.subplots() im = ax.pcolormesh(imdata, cmap=cmap) plt.colorbar(im) plt.show() 
if @ imdata in interactive session, you'll see
in [185]: imdata out[185]: masked_array(data = [[ 3. 5. 10. inf 5. 8.] [ 3. 5. 10. inf 5. 8.]], mask = false, fill_value = 1e+20) above, mask=false means nothing masked. if wrap np.ma.masked_invalid then:
in [186]: np.ma.masked_invalid(imdata) out[186]: masked_array(data = [[3.0 5.0 10.0 -- 5.0 8.0] [3.0 5.0 10.0 -- 5.0 8.0]], mask = [[false false false true false false] [false false false true false false]], fill_value = 1e+20) the problem masking a np.vstack not respect mask. alternatively, have used np.ma.vstack. speaking, functions in np.ma namespace respect mask.
however, don't need use vstack here; np.atleast_2d do. vstack creates array of shape (2, n), while np.atleast_2d creates array of shape (1, n).
another alternative use set_over instead of set_bad. allow avoid needing masked array altogether:
import numpy np import matplotlib.pyplot plt = np.array([3, 5, 10, np.inf, 5, 8]) imdata = np.atleast_2d(a) cmap = plt.cm.hot cmap.set_over('b') cmap.set_under('g') fig, ax = plt.subplots() b = a[np.isfinite(a)] im = ax.pcolormesh(imdata, cmap=cmap, vmin=b.min(), vmax=b.max()) plt.colorbar(im, extend='both') plt.show() 
the extend='both' in conjunction set_over , set_under give little colored arrows on colorbar indicate color used values beyond colorbar's range.
Comments
Post a Comment