Pytstud
Pytstud

Reputation: 55

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')

Upvotes: 2

Views: 61

Answers (2)

DavidG
DavidG

Reputation: 25362

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

Upvotes: 1

Rocky Li
Rocky Li

Reputation: 5958

You're almost there!

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

This will connect the dots - you can add as many artist as you want to a ax individually. and each plot will create an artist.

enter image description here

Upvotes: 1

Related Questions