我将一系列行存储在这样的列表中:
line_list = [line_1, line_2, line_3, ..., line_M]
其中每个line_i
是一个由两个子列表组成的子列表,一个用于x坐标,另一个用于y坐标:
line_i = [[x_1i, x2_i, .., x_Ni], [y_1i, y_2i, .., y_Ni]]
我还有一个line_list
与花车组成长度相同的列表:
floats_list = [0.23, 4.5, 1.6, ..., float_M]
我想绘制每条线,使其颜色取自颜色图,并与其索引在floats_list
列表中的位置有关。因此line_j
其颜色将由数字决定floats_list[j]
。我还需要在侧面显示一个彩条
该代码想要这样的东西,除了它应该可以工作:)
import matplotlib.pyplot as plt
line1 = [[0.5,3.6,4.5],[1.2,2.0,3.6]]
line2 = [[1.5,0.4,3.1,4.9],[5.1,0.2,7.4,0.3]]
line3 = [[1.5,3.6],[8.4,2.3]]
line_list = [line1,line2,line3]
floats_list = [1.2,0.3,5.6]
# Define colormap.
cm = plt.cm.get_cmap('RdYlBu')
# plot all lines.
for j,lin in enumerate(line_list):
plt.plot(lin[0], lin[1], c=floats_list[j])
# Show colorbar.
plt.colorbar()
plt.show()
LineCollection
为此最容易使用。实际上,它希望这些行的格式与您已有的格式相似。要使用第三个变量为线条着色,只需指定array=floats_list
。举个例子:
import numpy
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
# The line format you curently have:
lines = [[(0, 1, 2, 3, 4), (4, 5, 6, 7, 8)],
[(0, 1, 2, 3, 4), (0, 1, 2, 3, 4)],
[(0, 1, 2, 3, 4), (8, 7, 6, 5, 4)],
[(4, 5, 6, 7, 8), (0, 1, 2, 3, 4)]]
# Reformat it to what `LineCollection` expects:
lines = [zip(x, y) for x, y in lines]
z = np.array([0.1, 9.4, 3.8, 2.0])
fig, ax = plt.subplots()
lines = LineCollection(lines, array=z, cmap=plt.cm.rainbow, linewidths=5)
ax.add_collection(lines)
fig.colorbar(lines)
# Manually adding artists doesn't rescale the plot, so we need to autoscale
ax.autoscale()
plt.show()
与重复调用相比,此方法有两个主要优点plot
。
Collections
渲染速度比许多类似的艺术家快得多。本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句