Reputation: 42459
I have a main list made of N
sub-lists (where this number will change for different runs), each one containing pairs of x,y
points. I need a way to plot the points in these sub-lists with different colors, taken from a list with (usually) fewer elements than sub-lists. To do this I need a way to cycle through this list of colors. This is an excerpt of what I'm after:
# Main list which holds all my N sub-lists.
list_a = [[x,y pairs], [..], [..], [..], ..., [..]]
# Plot sub-lists with colors taken from this list. I need the for block below
# to cycle through this list.
col = ['red', 'darkgreen', 'blue', 'maroon','red']
for i, sub_list in enumerate(list_a):
plt.scatter(sub_list[0], sub_list[1], marker='o', c=col[i])
If len(col) < len(list_a)
(which will happen most of the time) this will return an error. Since for a given run of my code the number of sub-lists will vary, I can't hard code a number of colors into the col
list, so I need a way to cycle through that list of colors. How could I do that?
Upvotes: 0
Views: 1931
Reputation: 239683
You can use modulo operator
numberOfColors = len(col)
for i, sub_list in enumerate(list_a):
plt.scatter(sub_list[0], sub_list[1], marker='o', c=col[i % numberOfColors])
Upvotes: 4
Reputation: 353569
IIUC, you can use itertools.cycle
, and then instead of c=col[i]
, use next
. For example:
>>> from itertools import cycle
>>> cols = cycle(["red", "green", "blue"])
>>> next(cols)
'red'
>>> next(cols)
'green'
>>> next(cols)
'blue'
>>> next(cols)
'red'
Upvotes: 7