shjnlee
shjnlee

Reputation: 243

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 x-y coordinate (0,0), so x_all and y_all would be something like

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? In other words, the colors would change when (x,y) = (0,0). Thanks

Upvotes: 0

Views: 143

Answers (2)

Seb
Seb

Reputation: 4586

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

Upvotes: 1

ufoxDan
ufoxDan

Reputation: 609

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

multicolor matplotlib plot

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. Instead, I could just index the 1st route of x and y:

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

Upvotes: 0

Related Questions