简体   繁体   English

在 matplotlib - python 中绘制不同的 colors

[英]Plotting different colors in matplotlib - python

I'm working on a small project on the vehicle routing problem, where a set of vehicles delivering goods to a set of customers from depot.我正在研究一个关于车辆路线问题的小项目,其中一组车辆从仓库向一组客户运送货物。

The solution would be something like:解决方案类似于:

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

where depot always have xy coordinate (0,0), so x_all and y_all would be something like其中 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)

How could I plot a graph that has different colors for different routes?我怎么能 plot 一个图表对于不同的路线有不同的 colors? In other words, the colors would change when (x,y) = (0,0).换句话说,当 (x,y) = (0,0) 时,colors 会发生变化。 Thanks谢谢

You could do something like this:你可以这样做:

# 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()

There are a few ways you could do this, but I would suggest using a multidimensional list:有几种方法可以做到这一点,但我建议使用多维列表:

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()

And matplotlib will take care of the coloring for you matplotlib 将为您处理着色

多色 matplotlib 图

This is an advisable way of managing your data as now you can index each route independently without worrying about all the routes being of the same length.这是管理数据的一种明智的方式,因为现在您可以独立索引每条路线,而不必担心所有路线的长度相同。 For example if one route had 4 stops and you needed to get that set of stops, you'd have to index your x and y arrays knowing where this route is.例如,如果一条路线有 4 个停靠点,并且您需要获得该组停靠点,则您必须索引 x 和 y arrays 知道这条路线的位置。 Instead, I could just index the 1st route of x and y:相反,我可以只索引 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