【发布时间】:2011-08-27 00:40:27
【问题描述】:
我正在使用 matplotlib.pyplot 比较一些算法结果,但是很难理解发生了什么,因为几行具有相同的确切颜色。有没有办法避免这种情况?我不认为 pyplot 只有七种颜色,是吗?
【问题讨论】:
-
我建议你看看这个帖子:stackoverflow.com/questions/4805048/…
标签: python colors matplotlib plot
我正在使用 matplotlib.pyplot 比较一些算法结果,但是很难理解发生了什么,因为几行具有相同的确切颜色。有没有办法避免这种情况?我不认为 pyplot 只有七种颜色,是吗?
【问题讨论】:
标签: python colors matplotlib plot
对于 Python 3,您可以从上述解决方案中使用:
colormap = plt.cm.nipy_spectral
colors = [colormap(i) for i in np.linspace(0, 1,number_of_plots)]
ax.set_prop_cycle('color', colors)
或:
import seaborn as sns
colors = sns.color_palette("hls", number_of_plots)
ax.set_prop_cycle('color', colors)
【讨论】:
我还建议使用Seaborn。使用这个库,可以很容易地生成具有所需颜色数量的顺序或定性调色板。还有一个可视化调色板的工具。例如:
import seaborn as sns
colors = sns.color_palette("hls", 4)
sns.palplot(colors)
plt.savefig("pal1.png")
colors = sns.color_palette("hls", 8)
sns.palplot(colors)
plt.savefig("pal2.png")
colors = sns.color_palette("Set2", 8)
sns.palplot(colors)
plt.savefig("pal3.png")
这些是生成的调色板:
【讨论】:
如果您知道要绘制多少个图,最好的办法是在之前定义颜色图:
import matplotlib.pyplot as plt
import numpy as np
fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
number_of_plots=10
colormap = plt.cm.nipy_spectral #I suggest to use nipy_spectral, Set1,Paired
ax1.set_color_cycle([colormap(i) for i in np.linspace(0, 1,number_of_plots)])
for i in range(1,number_of_plots+1):
ax1.plot(np.array([1,5])*i,label=i)
ax1.legend(loc=2)
使用nipy_spectral
【讨论】:
set_color_cycle() 在version 1.5 中已被弃用? plt 建议改用set_prop_cycle()(但我还没试过)。
Matplotlib 有超过七种颜色。您可以通过多种方式指定颜色(请参阅http://matplotlib.sourceforge.net/api/colors_api.html)。
例如,您可以使用 html 十六进制字符串指定颜色:
pyplot.plot(x, y, color='#112233')
【讨论】: