<p>有几种不同的方法可以做到这一点。“最佳”方法主要取决于要绘制多少线段。</p>
<p>如果您只是要绘制一些(例如10条)线段,则只需执行以下操作:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
def uniqueish_color():
"""There're better ways to generate unique colors, but this isn't awful."""
return plt.cm.gist_ncar(np.random.random())
xy = (np.random.random((10, 2)) - 0.5).cumsum(axis=0)
fig, ax = plt.subplots()
for start, stop in zip(xy[:-1], xy[1:]):
x, y = zip(start, stop)
ax.plot(x, y, color=uniqueish_color())
plt.show()
</code></pre>
<p><img src="https://i.stack.imgur.com/CA3gu.png" alt="enter image description here"/></p>
<p>不过,如果绘制的是具有一百万条线段的图形,则绘制速度会非常慢。在这种情况下,使用<code>LineCollection</code>。E、 g</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
xy = (np.random.random((1000, 2)) - 0.5).cumsum(axis=0)
# Reshape things so that we have a sequence of:
# [[(x0,y0),(x1,y1)],[(x0,y0),(x1,y1)],...]
xy = xy.reshape(-1, 1, 2)
segments = np.hstack([xy[:-1], xy[1:]])
fig, ax = plt.subplots()
coll = LineCollection(segments, cmap=plt.cm.gist_ncar)
coll.set_array(np.random.random(xy.shape[0]))
ax.add_collection(coll)
ax.autoscale_view()
plt.show()
</code></pre>
<p><img src="https://i.stack.imgur.com/WIgP9.png" alt="enter image description here"/></p>
<p>对于这两种情况,我们只是从“gist-ncar”coloramp中随机绘制颜色。看看这里的彩色地图(要点是大约2/3的路下来):<a href="http://matplotlib.org/examples/color/colormaps_reference.html" rel="noreferrer">http://matplotlib.org/examples/color/colormaps_reference.html</a></p>