繁体   English   中英

在 matplotlib - python 中绘制不同的 colors

[英]Plotting different colors in matplotlib - python

我正在研究一个关于车辆路线问题的小项目,其中一组车辆从仓库向一组客户运送货物。

解决方案类似于:

Sub-route 1:  Depot Customer4  Customer7
Sub-route 2:  Depot Customer1  Customer5  Customer3  
Sub-route 3:  Depot Customer2  Customer6

其中 depot 始终具有 xy 坐标 (0,0),因此 x_all 和 y_all 类似于

x_all = [0,x4,x7,0,x1,x5,x3,0,...]
y_all = [0,y4,y7,0,y1,y5,y3,0,...]
plt.plot(x_all, y_all)

我怎么能 plot 一个图表对于不同的路线有不同的 colors? 换句话说,当 (x,y) = (0,0) 时,colors 会发生变化。 谢谢

你可以这样做:

# Find indices where routes get back to the depot
depot_stops = [i for i in range(len(x_all)) if x_all[i] == y_all[i] == 0]
# Split route into sub-routes
sub_routes = [(x_all[i:j+1], y_all[i:j+1]) for i, j in zip(depot_stops[:-1], depot_stops[1:])]

for xs, ys in sub_routes:
    plt.plot(xs, ys)
    # (Consecutive calls will automatically use different colours)

plt.show()

有几种方法可以做到这一点,但我建议使用多维列表:

x = [[0, 4, 7],
     [0, 5, 3],
     [0, 2, 1]]

y = [[0, 4, 7],
     [0, 1, 5],
     [0, 2, 1]]

for i in range(len(x)):
    plt.plot(x[i], y[i])

plt.show()

matplotlib 将为您处理着色

多色 matplotlib 图

这是管理数据的一种明智的方式,因为现在您可以独立索引每条路线,而不必担心所有路线的长度相同。 例如,如果一条路线有 4 个停靠点,并且您需要获得该组停靠点,则您必须索引 x 和 y arrays 知道这条路线的位置。 相反,我可以只索引 x 和 y 的第一条路线:

x[1]
>> [0, 5, 3]
y[1]
>> [0, 1, 5]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM