[英]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 將為您處理着色
這是管理數據的一種明智的方式,因為現在您可以獨立索引每條路線,而不必擔心所有路線的長度相同。 例如,如果一條路線有 4 個停靠點,並且您需要獲得該組停靠點,則您必須索引 x 和 y arrays 知道這條路線的位置。 相反,我可以只索引 x 和 y 的第一條路線:
x[1]
>> [0, 5, 3]
y[1]
>> [0, 1, 5]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.