在matplotlib python中绘制不同颜色

2024-05-14 01:06:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个关于车辆路径问题的小项目,在这个项目中,一组车辆从仓库向一组客户运送货物

解决方案如下:

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

其中,仓库始终具有x-y坐标(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)

如何绘制不同路线具有不同颜色的图形?换句话说,当(x,y)=(0,0)时,颜色会改变。 谢谢


Tags: 项目路径客户颜色all解决方案route仓库
2条回答

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

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将为您处理着色

multicolor matplotlib plot

这是一种管理数据的明智方法,因为现在您可以独立地为每个路由编制索引,而不用担心所有路由的长度都相同。例如,如果一条路由有4个站点,而您需要获取该组站点,那么您必须为您的x和y数组编制索引,以了解该路由的位置。相反,我可以只索引x和y的第一条路线:

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

你可以这样做:

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

相关问题 更多 >