How to get a masked rgba array from a ScalarMappable object
<p>The docs for <code>to_rgba</code> state:</p>

<blockquote>
  <p>Note: this method assumes the input is well-behaved; it does not check
  for anomalies such as x being a masked rgba array, or being an integer
  type other than uint8, or being a floating point rgba array with
  values outside the 0-1 range.</p>
</blockquote>

<p>But that's exactly what I need: a masked rgba array. The following was adapted from <a href="http://stackoverflow.com/questions/15140072/how-to-map-number-to-color-using-matplotlibs-colormap">this post</a> and gives me the correct values, except the values that are <code>nan</code> (that I make zero on the first line) should be black rgba values in <code>spc_map_color</code>     </p>

<pre><code>spc_map[np.isnan(spc_map)] = 0
gradient_range = matplotlib.colors.Normalize(-1.0, 1.0)
cmap = matplotlib.cm.ScalarMappable(
  gradient_range, self.cm_type)
spc_map_color = cmap.to_rgba(spc_map, bytes=True)
</code></pre>

<p>So as you can see, the colourmap used is variable, but the rgba value that is returned for values outside the mask (that are <code>nan</code>) should be invariant, i.e. always black.</p>

<p>Answers for how to do this for <code>linearsegmentedcolourmap</code> objects exists <a href="http://stackoverflow.com/questions/18718101/applying-different-color-map-to-mask">here</a> and <a href="http://stackoverflow.com/questions/22548813/python-color-map-but-with-all-zero-values-mapped-to-black">here</a>. But this is done if you want to output the image with <code>imshow</code>. I don't want to do that. I want the rgba values in an array.</p>

<p>I've tried <code>cmap.set_bad(color='black')</code> for instance with cmap as my <code>ScalarMappable</code> above before converting to rgba, but <code>ScalarMappable</code> doesn't have a <code>set_bad</code> function.</p>

<p>I missed something obvious?</p>

<p>You can use
<code>spc_map = np.random.randn(256,256)</code> and then do something like set all values below some value to zero to test solutions you may have</p>

<p>Black typically corresponds to [0, 0, 0, 1] in an RGBA array. So just set all masked positions to these values ex post.</p>

<pre><code># get mask of masked array
mask = spc_map.mask 

# RGBA array should have one more dimension than spc_map with length 4 
spc_map_color[mask] = np.array([0, 0, 0, 1])
</code></pre>

python matplotlib