Is it possible to not plot points if there are a certain value on a line plot in Python?

Example

My data has gaps where there is no good data. When this happens, I would want there to be a gap in the line plot, but right now you can see where this happens due to the long straight lines that go to the next good point. Is there a way to make these gaps instead using matplotlib? Currently, I am using the standard code…

plt.plot(x, y)
plt.show()

I have not seen anywhere that has a good answer to this. Maybe it is just not possible?

Answer

Create a list of chunks where each sublist contains a consecutive number of points and create the corresponding x-axis list. Plot each list one after the other on the same figure with the same color. You will get a plot with gaps.

Example:

from matplotlib import pyplot as plt

f, ax = plt.subplots(1, 1)
ax.plot([1, 2, 3], [1, 2, 3], color='teal')
ax.plot([5, 6, 7], [1, 2, 3], color='teal')

plot

I suggest creating a list X and Y which contains the sublists to plot individually. It comes down to manipulating your data in a format that is suited for plotting with matplotlib.

for k, _ in enumerate(X):
    ax.plot(X[k], Y[k], color='teal')

Leave a Reply

Your email address will not be published. Required fields are marked *