Matplotlib绘制不同颜色的带箭头的线

Matplotlib绘制不同颜色的箭头线

  周五的时候计算出来一条线路,但是计算出来的只是类似与

0->10->19->2->..0

这样的线路只有写代码的人才能看的懂无法直观的表达出来,让其它同事看的不清晰,所以考虑怎样直观的把线路图画出来。
&esp; 当然是考虑用matplotlib了,
导入相关的库

import matplotlib.pyplot as plt
import numpy
import matplotlib.colors as colors
import matplotlib.cm as cmx

后面两个主要是用于处理颜色的。
准备数据

 _locations = [
        (4, 4),  # depot
        (4, 4),  # unload depot_prime
        (4, 4),  # unload depot_second
        (4, 4),  # unload depot_fourth
        (4, 4),  # unload depot_fourth
        (4, 4),  # unload depot_fifth
        (2, 0),
        (8, 0),  # locations to visit
        (0, 1),
        (1, 1),
        (5, 2),
        (7, 2),
        (3, 3),
        (6, 3),
        (5, 5),
        (8, 5),
        (1, 6),
        (2, 6),
        (3, 7),
        (6, 7),
        (0, 8),
        (7, 8)
    ]

画图

plt.figure(figsize=(10, 10))
p1 = [l[0] for l in _locations]
p2 = [l[1] for l in _locations]
plt.plot(p1[:6], p2[:6], 'g*', ms=20, label='depot')
plt.plot(p1[6:], p2[6:], 'ro', ms=15, label='customer')
plt.grid(True)
plt.legend(loc='lower left')

way = [[0, 12, 18, 17, 16, 4, 14, 10, 11, 13, 5], [0, 6, 9, 8, 20, 3], [0, 19, 21, 15, 7, 2]]   # 

cmap = plt.cm.jet
cNorm  = colors.Normalize(vmin=0, vmax=len(way))
scalarMap = cmx.ScalarMappable(norm=cNorm,cmap=cmap)

for k in range(0, len(way)):
    way0 = way[k]
    colorVal = scalarMap.to_rgba(k)
    for i in range(0, len(way0)-1):
        start = _locations[way0[i]]
        end = _locations[way0[i+1]]
#         plt.arrow(start[0], start[1], end[0]-start[0], end[1]-start[1], length_includes_head=True,
#                  head_width=0.2, head_length=0.3, fc='k', ec='k', lw=2, ls=lineStyle[k], color='red')
        plt.arrow(start[0], start[1], end[0]-start[0], end[1]-start[1], 
                  length_includes_head=True, head_width=0.2, lw=2,
                  color=colorVal)
plt.show()
cmap = plt.cm.jet
cNorm  = colors.Normalize(vmin=0, vmax=len(way))
scalarMap = cmx.ScalarMappable(norm=cNorm,cmap=cmap)

cmap可以理解为颜色库,cNorm设置颜色的范围,有几条线路就设置几种颜色,scalarMap颜色生成完毕。最后在绘图的时候,根据索引获得相应的颜色就可以了。

结果如下:
Matplotlib绘制不同颜色的带箭头的线_第1张图片

reference:
https://stackoverflow.com/questions/18748328/plotting-arrows-with-different-color-in-matplotlib

你可能感兴趣的:(python,小常识)