Home > Software engineering >  Draw a line between points, ignoring missing data, with matplotlib
Draw a line between points, ignoring missing data, with matplotlib

Time:04-22

Numerous similar questions have been asked over the years, such as this one enter image description here

However, I want to force a line to be drawn between the first and third elements of y1[], without affecting how y2[] is plotted. Is this possible? I could remove the second element of x[], but this would also prevent me from plotting x[] against y2[].

CodePudding user response:

You can use a simple function to keep only the valid data:

x=[0, 0.02, 0.05, 0.08, 0.11, 0.14]
y1=[31.15, None, 15.24, 11.65, 13.54, 9.55]
y2=[20.3, 14.2, 5.6, 3.10, 8.8, 10.45]

def dropnone(X, Y):
    return zip(*((a,b) for a,b in zip(X,Y) if None not in [a,b]))

plt.plot(*dropnone(x, y1), linestyle='-',marker='o',color='red')
plt.plot(*dropnone(x, y2), linestyle='-',marker='o',color='blue')

output:

enter image description here

  • Related