Search code examples
python-3.xnumpymatplotliblinemask

Connecting masked points with line


How can I connect these points with polyline? I have to connect them in order so that y value in point x=1 connects to y value in point x=2 and so on. Or can I somehow combine those separate plots?

import numpy as np
import matplotlib.pyplot as plt

y = np.random.uniform(-1,1,size=100)
x = np.arange(0,100)
pos = y[y>=0]
neg = y[y<0]


fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot(x[y>=0],pos, 'rs')
ax.plot(x[y<0],neg, 'bo')

Solution

  • You have sepcified a marker using 'rs' (red square). You can add a dash at the beginning of this string to indicate you want these to be joined by a line:

    fig = plt.figure()
    ax = fig.add_subplot(1,1,1)
    ax.plot(x[y>=0], pos, '-rs')
    ax.plot(x[y<0], neg, '-bo')
    

    You could also combine them in to the same call to plot if you like, however it's less readable:

    ax.plot(x[y>=0], pos,'-rs', x[y<0], neg, '-bo')
    

    enter image description here