在matplotlib中绘制不同的颜色-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,x1,x5,x3,...]
y_all = [0,y4,y7,y1,y5,y3,...]
plt.plot(x_all,y_all)

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

cs_chenzz 回答:在matplotlib中绘制不同的颜色-python

您可以执行以下操作:

# 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],2,1]]

y = [[0,1,5],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,3]
y[1]
>> [0,5]
本文链接:https://www.f2er.com/3127897.html

大家都在问