0

I have data in Matlab for which I want to create a heat map style graph. The usual way to do this is with imagesc and possibly a custom color map. (See, for example, the accepted answer on this question: MATLAB heat map.) If the data contains NaNs, however, this does not necessarily do what I want. The MathWorks Documentation claims that the behavior is undefined for NaN. In practice, the result seems to be that the color is assigned that of the smallest value in your color map.

In cases where the NaN is marking that no value was available, this can be misleading. It would be preferable to have this show as something other than the colors in the color map. How to do it?

I note this other question (Assign different color to NaN values in Matlab images), which is somewhat similar. In my view that's not a duplicate, however, because it creates the image via a different function call, potentially with its own underlying structures.

Community
  • 1
  • 1
Brick
  • 3,998
  • 8
  • 27
  • 47
  • Also related to [this](http://stackoverflow.com/questions/38851267/matlab-imshow-omit-nan/38851344#38851344) – Suever Feb 15 '17 at 19:21

1 Answers1

1

After running through many answers on the MathWorks site that claimed this wasn't possible, I found the following solution: You can change the transparency of each color patch however you want. The default is to make everything opaque, but I set the values where the the data is NaN to be transparent. This is different than explicitly setting the color of the patch to something outside the color map, but it works great if you don't have anything else in the figure that might "show through" and cause confusion. In such cases, the areas corresponding to NaN appear to be "holes" in the surface, showing the background color of the axis. With data in variable data and axis values given (respective) in x and y:

h = imagesc(x, y, data);
h.AlphaData = ones(size(h.CData)); 
h.AlphaData(isnan(h.CData)) = 0;

The first line creates the image, the second line sets all patches to be opaque, and the last sets the patches corresponding to NaN to be transparent. The second line appears to be necessary despite replicating the default behavior because the default value for AlphaData is a scalar 1 whereas we need it to be a matrix of ones in order for the third line to work.

Brick
  • 3,998
  • 8
  • 27
  • 47