在 matplotlib 中绘制不同的颜色 - python
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 始终具有 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) 时颜色会改变。
谢谢
有几种方法可以做到这一点,但我建议使用多维列表:
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 会为您处理着色
这是一种管理数据的明智方法,因为现在您可以独立地为每条路线编制索引,而不必担心所有路线的长度都相同。例如,如果一条路线有 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()
我正在做一个关于车辆路径问题的小项目,其中一组车辆从仓库向一组客户运送货物。
解决方案类似于:
Sub-route 1: Depot Customer4 Customer7
Sub-route 2: Depot Customer1 Customer5 Customer3
Sub-route 3: Depot Customer2 Customer6
其中 depot 始终具有 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) 时颜色会改变。 谢谢
有几种方法可以做到这一点,但我建议使用多维列表:
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 会为您处理着色
这是一种管理数据的明智方法,因为现在您可以独立地为每条路线编制索引,而不必担心所有路线的长度都相同。例如,如果一条路线有 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()