用线连接蒙版点

Connecting masked points with line

如何用折线连接这些点?我必须按顺序连接它们,以便点 x=1 中的 y 值连接到点 x=2 中的 y 值,依此类推。或者我能以某种方式组合这些单独的地块吗?

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

你快完成了!

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

这将把点连接起来 - 您可以根据需要将任意数量的 artist 添加到一个 ax 中。每个 plot 将创建一个艺术家。

您已使用 'rs'(红色方块)指定了一个标记。您可以在此字符串的开头添加破折号,以指示您希望用一行将它们连接起来:

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

如果您愿意,您也可以将它们组合到对 plot 的同一个调用中,但是它的可读性较差:

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