我有一个颜色值列表(格式为:hex(' #ffffff')或rgb(255,255,255),如果有帮助的话)。这些颜色明确对应于点之间的线段。目前,我通过以下方式绘制一条线作为线段的集合:
import matplotlib.pyplot as plt
import itertools
colors = itertools.cycle('#ffffff', '#ffffff', '#ff0320', '#452143', ...)
t = (0, 1, 2, 3, ...)
var1 = (43, 15, 25, 9, ...)
ax = plt.subplot2grid((3,1), (0,0), colspan=3, rowspan=1)
ps = [(t,var1) for (t,var1) in zip(t, val)]
for start, end in zip(ps[:-1], ps[1:]):
t, var1 = zip(start, end)
c = next(colors)
ax.plot(t, var1, color=c)
然而,由于每个点都有一个颜色,我更喜欢为绘图设置一个cmap。如何将颜色列表转换为cmap,我可以在绘制直线时使用?
答案 0 :(得分:1)
正如 tcaswell 所说,请使用LineCollection
:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.collections import LineCollection
# a random walk
xy = np.cumsum(np.random.randn(1000, 2), axis=0)
z = np.linspace(0, 1, 1000)
lc = LineCollection(zip(xy[:-1], xy[1:]), array=z, cmap=plt.cm.hsv)
fig, ax = plt.subplots(1, 1)
ax.add_collection(lc)
ax.margins(0.1)
plt.show()