Matplotlib set_color_cycle与set_prop_cycle [英] Matplotlib set_color_cycle versus set_prop_cycle
问题描述
在Matplotlib中我最喜欢做的一件事情是设置颜色循环以匹配某些颜色图,以便生成线图,这些线图在各行中具有很好的颜色级数.像这样一个:
One of my favorite things to do in Matplotlib is to set the color-cycle to match some colormap, in order to produce line-plots that have a nice progression of colors across the lines. Like this one:
以前,这是使用set_color_cycle
的一行代码:
Previously, this was one line of code using set_color_cycle
:
ax.set_color_cycle([plt.cm.spectral(i) for i in np.linspace(0, 1, num_lines)])
但是,最近我看到一个警告:
But, recently I see a warning:
MatplotlibDeprecationWarning:
The set_color_cycle attribute was deprecated in version 1.5.
Use set_prop_cycle instead.
使用set_prop_cycle
,可以获得相同的结果,但是我需要import cycler
,语法不太紧凑:
Using set_prop_cycle
, I can achieve the same result, but I need to import cycler
, and the syntax is less compact:
from cycler import cycler
colors = [plt.cm.spectral(i) for i in np.linspace(0, 1, num_lines)]
ax.set_prop_cycle(cycler('color', colors))
所以,我的问题是:
我正确使用set_prop_cycle
吗? (以最有效的方式?)
Am I using set_prop_cycle
correctly? (and in the most efficient way?)
是否有更简单的方法将颜色循环设置为颜色图?换句话说,是否有一些神话般的功能?
Is there an easier way to set the color-cycle to a colormap? In other words, is there some mythical function like this?
ax.set_colorcycle_to_colormap('jet', nlines=30)
以下是完整示例的代码:
Here is the code for the complete example:
import numpy as np
import matplotlib.pyplot as plt
ax = plt.subplot(111)
num_lines = 30
colors = [plt.cm.spectral(i) for i in np.linspace(0, 1, num_lines)]
# old way:
ax.set_color_cycle(colors)
# new way:
from cycler import cycler
ax.set_prop_cycle(cycler('color', colors))
for n in range(num_lines):
x = np.linspace(0,10,500)
y = np.sin(x)+n
ax.plot(x, y, lw=3)
plt.show()
推荐答案
由于新的属性循环程序可以迭代除颜色(例如,线型)以外的其他属性,因此需要指定label
,即要循环的属性.
Because the new property cycler can iterate over other properties than just color (e.g. linestyle) you need to specify the label
, i.e. the property over which to cycle.
ax.set_prop_cycle('color', colors)
尽管没有必要导入和创建循环程序;因此,正如我所看到的那样,新方法的唯一缺点是它使调用时间延长了8个字符.
There is no need to import and create a cycler though; so as I see it the only drawback of the new method it that it makes the call 8 characters longer.
没有一种神奇的方法将色图作为输入并创建循环仪,但是您也可以通过直接将numpy数组提供给色图来缩短颜色列表的创建.
There is no magical method that takes a colormap as input and creates the cycler, but you can also shorten your color list creation by directly supplying the numpy array to the colormap.
colors = plt.cm.Spectral(np.linspace(0,1,30))
或结合使用
ax.set_prop_cycle('color',plt.cm.Spectral(np.linspace(0,1,30)))
这篇关于Matplotlib set_color_cycle与set_prop_cycle的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!