在 matplotlib 中绘制不同的颜色 [英] plotting different colors in matplotlib
问题描述
假设我有一个 for 循环,我想用不同的颜色绘制点:
Suppose I have a for loop and I want to plot points in different colors:
for i in range(5):
plt.plot(x,y,col=i)
如何在 for 循环中自动更改颜色?
How do I automatically change colors in the for loop?
推荐答案
@tcaswell 已经回答了,但我正在输入我的答案,所以我会继续发布......
@tcaswell already answered, but I was in the middle of typing my answer up, so I'll go ahead and post it...
有多种不同的方法可以做到这一点.首先,matplotlib
将自动循环显示颜色.默认情况下,它会在蓝色、绿色、红色、青色、洋红色、黄色、黑色之间循环:
There are a number of different ways you could do this. To begin with, matplotlib
will automatically cycle through colors. By default, it cycles through blue, green, red, cyan, magenta, yellow, black:
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()
如果你想控制matplotlib循环的颜色,使用ax.set_color_cycle
:
If you want to control which colors matplotlib cycles through, use ax.set_color_cycle
:
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()
如果您想明确指定将使用的颜色,只需将其传递给 color
kwarg(接受 html 颜色名称,如 rgb 元组和十六进制字符串):>
If you'd like to explicitly specify the colors that will be used, just pass it to the color
kwarg (html colors names are accepted, as are rgb tuples and hex strings):
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()
最后,如果您想从现有颜色图中自动选择指定数量的颜色:
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()
这篇关于在 matplotlib 中绘制不同的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!