这些问题可以通过使用^{}来解决。不过,在我看来,这不太方便使用。有一个打开的suggestion on GitHub用于添加多色线条图函数,类似于plt.scatter(...)函数。
下面是一个我可以一起破解的工作示例
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
def multiline(xs, ys, c, ax=None, **kwargs):
"""Plot lines with different colorings
Parameters
----------
xs : iterable container of x coordinates
ys : iterable container of y coordinates
c : iterable container of numbers mapped to colormap
ax (optional): Axes to plot on.
kwargs (optional): passed to LineCollection
Notes:
len(xs) == len(ys) == len(c) is the number of line segments
len(xs[i]) == len(ys[i]) is the number of points for each line (indexed by i)
Returns
-------
lc : LineCollection instance.
"""
# find axes
ax = plt.gca() if ax is None else ax
# create LineCollection
segments = [np.column_stack([x, y]) for x, y in zip(xs, ys)]
lc = LineCollection(segments, **kwargs)
# set coloring of line segments
# Note: I get an error if I pass c as a list here... not sure why.
lc.set_array(np.asarray(c))
# add lines to axes and rescale
# Note: adding a collection doesn't autoscalee xlim/ylim
ax.add_collection(lc)
ax.autoscale()
return lc
n_lines = 30
x = np.arange(100)
yint = np.arange(0, n_lines*10, 10)
ys = np.array([x + b for b in yint])
xs = np.array([x for i in range(n_lines)]) # could also use np.tile
colors = np.arange(n_lines)
fig, ax = plt.subplots()
lc = multiline(xs, ys, yint, cmap='bwr', lw=2)
axcb = fig.colorbar(lc)
axcb.set_label('Y-intercept')
ax.set_title('Line Collection with mapped colors')
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2*np.pi, 64)
y = np.cos(x)
n = 20
ax = plt.axes()
ax.set_prop_cycle('color',[plt.cm.jet(i) for i in np.linspace(0, 1, n)])
for i in range(n):
plt.plot(x, i*y)
import numpy as np
import matplotlib.pylab as pl
x = np.linspace(0, 2*np.pi, 64)
y = np.cos(x)
pl.figure()
pl.plot(x,y)
n = 20
colors = pl.cm.jet(np.linspace(0,1,n))
for i in range(n):
pl.plot(x, i*y, color=colors[i])
巴特的解决方案很好也很简单,但有两个缺点。
plt.colorbar()
不会很好地工作,因为线图是不可映射的(与图像相比)由于for循环的原因,对于大量的行来说,它可能会很慢(尽管这对于大多数应用程序来说可能不是问题?)
这些问题可以通过使用^{} 来解决。不过,在我看来,这不太方便使用。有一个打开的suggestion on GitHub用于添加多色线条图函数,类似于
plt.scatter(...)
函数。下面是一个我可以一起破解的工作示例
下面是一个非常简单的例子:
产生:
还有一些更复杂的东西:
产生:
希望这有帮助!
与Bart的回答相反,在对
plt.plot
的每次调用中,您没有指定颜色,而是使用set_prop_cycle
定义一个新的颜色循环。他的示例可以转换为以下代码(我还将matplotlib的导入更改为推荐的样式):Matplotlib颜色映射接受用于从颜色映射获取颜色的参数(
0..1
,标量或数组)。例如:为您提供一个具有(两)种RGBA颜色的数组:
您可以使用它来创建不同的颜色:
相关问题 更多 >
编程相关推荐