2

I'm trying to contour plot some data with NaNs (no solution). I want to indicate the border of the NaNs with a black line. So far I've only found how to hatch the whole NaN region (hatch a NaN region in a contourplot in matplotlib) but I just want the outline.

fig, ax = plt.subplots()

d = np.random.rand(10, 10)
d[2, 2], d[3, 5] = np.nan, np.nan

plt.contour(d)
plt.show()

I get:

enter image description here

I would want:

enter image description here

DavidG
  • 24,279
  • 14
  • 89
  • 82
an1234
  • 23
  • 3

1 Answers1

3

You could draw another contour of the masked out regions. To this end one would mask the data out with a numpy.ma array. Then use its mask to plot another contour at a level close to (but not exactly) zero.

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

d = np.random.rand(10, 10)

mask = np.zeros(d.shape, dtype=bool)
mask[2, 2], mask[3, 5] = 1, 1

masked_d = np.ma.array(d, mask=mask)

plt.contour(masked_d)

plt.contour(mask, [0.01], colors="k", linewidths=3)

plt.show()

enter image description here

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712