import matplotlib.pyplot as plt
import numpy as np
num_plots = 20
# Have a look at the colormaps here and decide which one you'd like:
# http://matplotlib.org/1.2.1/examples/pylab_examples/show_colormaps.html
colormap = plt.cm.gist_ncar
plt.gca().set_color_cycle([colormap(i) for i in np.linspace(0, 0.9, num_plots)])
# Plot several different functions...
x = np.arange(10)
labels = []
for i in range(1, num_plots + 1):
plt.plot(x, i * x + 5 * i)
labels.append(r'$y = %ix + %i$' % (i, 5*i))
# I'm basically just demonstrating several different legend options here...
plt.legend(labels, ncol=4, loc='upper center',
bbox_to_anchor=[0.5, 1.1],
columnspacing=1.0, labelspacing=0.0,
handletextpad=0.0, handlelength=1.5,
fancybox=True, shadow=True)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
for i in range(1,15):
ax1.plot(np.array([1,5])*i,label=i)
您需要的一段代码:
colormap = plt.cm.gist_ncar #nipy_spectral, Set1,Paired
colors = [colormap(i) for i in np.linspace(0, 1,len(ax1.lines))]
for i,j in enumerate(ax1.lines):
j.set_color(colors[i])
ax1.legend(loc=2)
...
# Plot several different functions...
labels = []
plotHandles = []
for i in range(1, num_plots + 1):
x, = plt.plot(some x vector, some y vector) #need the ',' per ** below
plotHandles.append(x)
labels.append(some label)
plt.legend(plotHandles, labels, 'upper left',ncol=1)
In [14]: fig, axes = plt.subplots(2,3)
In [15]: for ax, short_color_name in zip(axes.flatten(), 'brgkyc'):
...: ax.plot((0,1), (0,1), short_color_name)
4 回答
Matplotlib默认执行此操作 .
例如 . :
而且,正如您可能已经知道的那样,您可以轻松添加图例:
如果要控制将循环的颜色:
希望那有所帮助!如果你不熟悉matplotlib,the tutorial is a good place to start .
Edit:
首先,如果你想要在一个数字上绘制很多(> 5)的东西,可以:
将它们放在不同的图上(考虑在一个图上使用一些子图),或
使用颜色以外的其他颜色(即标记样式或线条粗细)来区分它们 .
否则,你将陷入一个非常混乱的阴谋!很高兴谁会读到你想要将15种不同的东西塞进一个人物中的任何东西!
除此之外,许多人在不同程度上都是色盲,区分众多微妙不同的颜色对于更多的人来说比你可能意识到的要困难 .
话虽如此,如果你真的想在一个轴上放20条线,并且有20种相对不同的颜色,这是一种方法:
稍后设置它们
如果您不知道要绘制的图的数量,可以在绘制它们直接从图中使用
.lines
检索数字后更改颜色,我使用此解决方案:一些随机数据
您需要的一段代码:
结果如下:
我想对上一篇文章中给出的最后一个循环答案提供一个小的改进(该帖子是正确的,仍然应该被接受) . 标记最后一个示例时所隐含的假设是
plt.label(LIST)
将标签号X放在LIST
中,并且调用了对应于第X时间plot
的行 . 我之前遇到过这种方法的问题 . 根据matplotlibs文档(http://matplotlib.org/users/legend_guide.html#adjusting-the-order-of-legend-item)构建图例和自定义标签的推荐方法是让人感觉标签与您认为的标签一致:**:Matplotlib Legends not working
TL;DR 不,它不能自动完成 . 对的,这是可能的 .
图(
figure
)中的每个绘图(axes
)都有自己的颜色循环 - 如果不为每个绘图强制使用不同的颜色,则所有绘图都共享相同的颜色顺序 .只有当我们伸展一点"automatically"的意思时,才能自动实现每个绘图中的不同颜色 .
OP写道
但是...... Matplotlib会自动为每条不同的曲线生成不同的颜色
那么为什么OP请求呢?如果我们继续阅读,我们有
并且它是有道理的,因为每个绘图(在Matplotlib的用语中每个
axes
)都有自己的color_cycle
(或者更确切地说,在2018年,它的prop_cycle
),并且每个绘图(axes
)以相同的顺序重复使用相同的颜色 .如果这是原始问题的含义,一种可能性是为每个图明确命名不同的颜色 .
如果在循环中生成绘图(通常发生),我们必须有一个额外的循环变量来覆盖Matplotlib自动选择的颜色 .