Correct way to set color to transparent with matplotlib.pcolormesh()?

matplotlib, python

Solution

You can use a masked array:

import matplotlib.pyplot as plt
import numpy as np

z = np.sin(np.arange(100) / 2).reshape(10, 10)
z = np.ma.masked_array(z, z < -.5)

cmap = plt.cm.Reds
plt.pcolormesh(z, vmin=-1, vmax=1, cmap="RdYlBu")
plt.colorbar()

Problem

I would like values under a certain level (in this case `0`) to be plotted as transparent with `matplotlib.pcolormesh()`, and I cannot seem to get anything working with the options that I have found. I have tried setting the `kwarg` `vmin=1`, and I have tried setting the limit with `plt.cm.cmap.set_under(alpha=0)`. Update: After playing around with a sample script, it appears that `vmin` is working correctly for me there, so it appears to be do to some other confounding factor. I am using `Basemap` and attempting to plot a density map, setting the levels based on the min/max values of the data (with everything else being zero). My sample script showing vmin working: ``` import matplotlib.pyplot as plt import random import numpy as np x = np.linspace(1,4,num=4) y = np.linspace(1,6,num=6) x_mesh, y_mesh = np.meshgrid(x,y) ydim, xdim = x_mesh.shape z = np.zeros(((ydim-1),(xdim-1))) for j in range(ydim-1): for i in range(xdim-1): z[j,i] = (random.random())+4. z[1:4,1:2]=0 cmap = plt.cm.Reds plt.pcolormesh(x,y,z, cmap=cmap, vmin=4) plt.show() ``` Output:

Original source