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()
...
# 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)
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)
默认情况下,Matplotlib会执行此操作。
例如:
而且,如您所知,您可以轻松添加一个图例:
如果要控制将循环使用的颜色:
希望有帮助!如果您不熟悉matplotlib,the tutorial is a good place to start。
编辑:
首先,如果要在一个图形上绘制很多东西(>;5),请执行以下操作:
否则,你会得到一个非常混乱的情节!要善待那些将要阅读你正在做的任何事情的人,不要试图把15种不同的东西塞进一个数字里!!
除此之外,许多人在不同程度上都是色盲,对更多的人来说,区分许多细微不同的颜色比你可能意识到的要困难。
也就是说,如果你真的想在一个轴上画20条线,有20种相对不同的颜色,这里有一种方法:
我想在上一篇文章中给出的最后一个循环答案的基础上提出一个小的改进(这篇文章是正确的,应该仍然被接受)。在标记最后一个示例时所做的隐式假设是
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
以后再设置
如果您不知道要绘制的绘图的数量,可以在绘制颜色后更改颜色,然后使用
.lines
直接从绘图中检索数字,我使用以下解决方案:一些随机数据
你需要的代码:
结果如下:
相关问题 更多 >
编程相关推荐