<p>@tcaswell已经回答了,但我正在输入我的答案,所以我将继续发布它。。。</p>
<p>有很多不同的方法可以做到这一点。首先,<code>matplotlib</code>将自动循环显示颜色。默认情况下,它在蓝色、绿色、红色、青色、洋红、黄色、黑色之间循环:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 1, 10)
for i in range(1, 6):
plt.plot(x, i * x + i, label='$y = {i}x + {i}$'.format(i=i))
plt.legend(loc='best')
plt.show()
</code></pre>
<p><img src="https://i.stack.imgur.com/KO1kx.png" alt="enter image description here"/></p>
<p>如果要控制matplotlib循环使用的颜色,请使用<code>ax.set_color_cycle</code>:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 1, 10)
fig, ax = plt.subplots()
ax.set_color_cycle(['red', 'black', 'yellow'])
for i in range(1, 6):
plt.plot(x, i * x + i, label='$y = {i}x + {i}$'.format(i=i))
plt.legend(loc='best')
plt.show()
</code></pre>
<p><img src="https://i.stack.imgur.com/yi93O.png" alt="enter image description here"/></p>
<p>如果要显式指定要使用的颜色,只需将其传递给<code>color</code>kwarg(接受html颜色名称,rgb元组和十六进制字符串也是如此):</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 1, 10)
for i, color in enumerate(['red', 'black', 'blue', 'brown', 'green'], start=1):
plt.plot(x, i * x + i, color=color, label='$y = {i}x + {i}$'.format(i=i))
plt.legend(loc='best')
plt.show()
</code></pre>
<p><img src="https://i.stack.imgur.com/jzQUP.png" alt="enter image description here"/></p>
<p>最后,如果要自动从<a href="https://matplotlib.org/examples/color/colormaps_reference.html" rel="noreferrer">existing colormap</a>中选择指定数量的颜色:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 1, 10)
number = 5
cmap = plt.get_cmap('gnuplot')
colors = [cmap(i) for i in np.linspace(0, 1, number)]
for i, color in enumerate(colors, start=1):
plt.plot(x, i * x + i, color=color, label='$y = {i}x + {i}$'.format(i=i))
plt.legend(loc='best')
plt.show()
</code></pre>
<p><img src="https://i.stack.imgur.com/GPFpt.png" alt="enter image description here"/></p>