Dotted lines instead of a missing value in matplotlib

Viewed 2590

I have an array of some data, where some of the values are missing

y = np.array([np.NAN, 45, 23, np.NAN, 5, 14, 22, np.NAN, np.NAN, 18, 23])

When I plot it, I have these NANs missing (which is expected)

fig, ax = plt.subplots()
ax.plot(y)
plt.show()

enter image description here

What I would like to have is a dotted line connecting the missing segments. For example in case of missing datapoint for 3, there should be a dotted line which connects existing points between 2 and 4, (the same for missing datapoints 7 and 8. If the datapoint is on the edge of the interval (datapoint 0) I would like to have a horizontal line connecting them (imagine previous/next datapoint the same as the available edge).


The questions I saw here ask how to remove these empty segments (not what I want). I can solve it by creating another array which will have missing values interpolated and all other values NAN, but it looks to complex to me.

Because this looks like a common case, I hope there is an easier approach.

3 Answers

Here is a solution that works with multiple NaN on the edges. To show that, i added one NaN on each side.

import numpy as np
import matplotlib.pyplot as plt

y = np.array([np.NAN, np.NAN, 45, 23, np.NAN, 5, 14, 22, np.NAN, np.NAN, 18, 23, np.NAN])
x = np.arange(0, len(y))

mask = np.isfinite(y)

# get first value in list
for i in range(len(mask)):
    if mask[i]:
        first = i
        break

# get last vaue in list
for i in range(len(mask)-1, -1, -1):
    if mask[i]:
        last = i
        break

# fill NaN with near known value on the edges
yp = np.copy(y)
yp[:first] = yp[first]
yp[last + 1:] = yp[last]

mask = np.isfinite(yp)

fig, ax = plt.subplots()
line, = ax.plot(x[mask],yp[mask], ls="--",lw=1)
ax.plot(x,y, color=line.get_color(), lw=1.5)

plt.show()

plot

You could use numpy.where, to have less code, but a simple python iteration is actually more efficient here. See comparison in my comment here.

ind = np.where(y)[0]
first, last = ind[0], ind[-1]
Related