<p>巴特的解决方案很好也很简单,但有两个缺点。</p>
<ol>
<li><p><code>plt.colorbar()</code>不会很好地工作,因为线图是不可映射的(与图像相比)</p></li>
<li><p>由于for循环的原因,对于大量的行来说,它可能会很慢(尽管这对于大多数应用程序来说可能不是问题?)</p></li>
</ol>
<p>这些问题可以通过使用<a href="https://matplotlib.org/gallery/shapes_and_collections/line_collection.html" rel="noreferrer">^{<cd2>}</a>来解决。不过,在我看来,这不太方便使用。有一个打开的<a href="https://github.com/matplotlib/matplotlib/issues/6040" rel="noreferrer">suggestion on GitHub</a>用于添加多色线条图函数,类似于<code>plt.scatter(...)</code>函数。</p>
<p>下面是一个我可以一起破解的工作示例</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
def multiline(xs, ys, c, ax=None, **kwargs):
"""Plot lines with different colorings
Parameters
----------
xs : iterable container of x coordinates
ys : iterable container of y coordinates
c : iterable container of numbers mapped to colormap
ax (optional): Axes to plot on.
kwargs (optional): passed to LineCollection
Notes:
len(xs) == len(ys) == len(c) is the number of line segments
len(xs[i]) == len(ys[i]) is the number of points for each line (indexed by i)
Returns
-------
lc : LineCollection instance.
"""
# find axes
ax = plt.gca() if ax is None else ax
# create LineCollection
segments = [np.column_stack([x, y]) for x, y in zip(xs, ys)]
lc = LineCollection(segments, **kwargs)
# set coloring of line segments
# Note: I get an error if I pass c as a list here... not sure why.
lc.set_array(np.asarray(c))
# add lines to axes and rescale
# Note: adding a collection doesn't autoscalee xlim/ylim
ax.add_collection(lc)
ax.autoscale()
return lc
</code></pre>
<p>下面是一个非常简单的例子:</p>
<pre class="lang-py prettyprint-override"><code>xs = [[0, 1],
[0, 1, 2]]
ys = [[0, 0],
[1, 2, 1]]
c = [0, 1]
lc = multiline(xs, ys, c, cmap='bwr', lw=2)
</code></pre>
<p>产生:</p>
<p><a href="https://i.stack.imgur.com/fXxAZ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/fXxAZ.png" alt="Example 1"/></a></p>
<p>还有一些更复杂的东西:</p>
<pre class="lang-py prettyprint-override"><code>n_lines = 30
x = np.arange(100)
yint = np.arange(0, n_lines*10, 10)
ys = np.array([x + b for b in yint])
xs = np.array([x for i in range(n_lines)]) # could also use np.tile
colors = np.arange(n_lines)
fig, ax = plt.subplots()
lc = multiline(xs, ys, yint, cmap='bwr', lw=2)
axcb = fig.colorbar(lc)
axcb.set_label('Y-intercept')
ax.set_title('Line Collection with mapped colors')
</code></pre>
<p>产生:</p>
<p><a href="https://i.stack.imgur.com/D8b2G.png" rel="noreferrer"><img src="https://i.stack.imgur.com/D8b2G.png" alt="enter image description here"/></a></p>
<p>希望这有帮助!</p>