Setting colours to multiple lines in matplotlib (python)


I have a graph computed from matplotlib, containing six plotted lines, and I want to know what I’m doing wrong for assigning each of my lines a unique colour.

I’ve got a list for the colours using hex codes, and each listx in "lists" contains the y axis data for each line:

colours = ["#ffa500", "#008000", "#ff0000", "#800080", "#7f6000", "#ffa7b6"]
lists = [list1, list2, list3, list4, list5, list6]

and I’m trying to assign each colour for each line:

for c in range(len(colours)):
    for l in lists:
        plt.plot(x, l, colours[c])

What I’m getting currently is every line being assigned pink (the last entry in the colours list), rather than each colour corresponding to each list (e.g. list2 needs color #008000).

I’m relatively new to programming, so if someone can explain what’s wrong and how I can fix this that would be much appreciated, thanks!

Asked By: canderous



I think what is probably happening in your code is because you are looping through your colours list index and then for each index in your colours you are looping through lists.

So what will happen is you will get to the end of your colours list indexes (pink) and then loop through lists plotting each using that colour.

To fix this (if your colours and lists lists will always be the same length) do something like:

for x in range(len(colours)):
    plt.plot(x, lists[x], colours[x])

I hope this works for you.

Answered By: MDavidson
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.