0

I am trying to plot a heatmap using patches. However, the data contains NaNs and sets all colours to the minimum value if the NaN values are included. If I set NaNs to 0, the plot is illustrated correctly. But I do not wish to set NaNs to a value, as this is misleading. Ideally, I would like to skip NaN values, if not at least set it to a desired colour

I have made sure to use nanmin/nanmax for the color bar to exclude NaN values from the scale.

Plotting from -2000:2000 across 400 elements, I have set index values 200:250 to NaN

The above code was used to produce below: https://www.pastepic.xyz/images/2019/10/17/image9347fc65ec10705e.png

However, the inclusion of NaNS leads to this https://www.pastepic.xyz/images/2019/10/17/imagef0c34416d84b669d.png

tono1
  • 1
  • 1

1 Answers1

1

Hey I cannot see your code, so I assume that you are using numpy, and then we can just remove the nans from the data like so if the data is one dimensional

x = x[~numpy.isnan(x)]

We can also use a mask to remove the nans in the following manner if the data has x and y.

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(10)
y = np.array([1, 4, 3, None, None, 5, 8, 9, 4, 7])
mask = np.isfinite(y)

Then the data for x and y becomes

x = x[mask] 
y = y[mask]

let me know how it works for you

Shadesfear
  • 749
  • 4
  • 17
  • Sorry about the missing code, the plot is created within a function with numerous inputs to generate the array. I have attached the code for the plotting section of the heatmap, which uses patches. https://i.ibb.co/9w0TMP6/image.png My issue isn't removing NaNs from an array. I want to keep NaNs in the data array and illustrate that the corresponding position is a NaN in the plot. Sorry for the confusion. – tono1 Oct 17 '19 at 22:53
  • A Similar question has been asked here (https://stackoverflow.com/questions/2578752/how-can-i-plot-nan-values-as-a-special-color-with-imshow-in-matplotlib). However, masking the NaNs still produced minimum values across the plot. – tono1 Oct 18 '19 at 00:31
  • 1
    I havent tested this, but would it be possible for you to mask out the nans and then in a seperate layer if you will plot them with the color you want? So you plot it correcly without the nans, and then plot them later with a static color? – Shadesfear Oct 18 '19 at 07:29
  • I'll give that a go, thanks for that. I've currently set NaNs to be 5% above the maximum value and set the top 99% of the color bar to be a distinct color. – tono1 Oct 19 '19 at 08:35