Search code examples
pythonmatplotliblegendline-plot

Why isn't the legend in matplotlib correctly displaying the colors?


I have a plot where I am displaying 3 different lineplots. I am thus specifying the legend explicitly to display 3 colors, one for each of the plots. Below is a toy example:

import matplotlib.pyplot as plt

for i in range(1,20):
    if i%3==0 and i%9!=0:
        plt.plot(range(1,20),[i+3 for i in range(1,20)], c='b')
    elif i%9==0:
        plt.plot(range(1,20),[i+9 for i in range(1,20)], c='r')
    else:
        plt.plot(range(1,20),range(1,20), c='g')
plt.legend(['Multiples of 3 only', 'Multiples of 9', 'All the rest'])
plt.show()

enter image description here

But the legend does not display the colors correctly. Why is that and how to fix it?


Solution

  • I tried Rex5's answer; it works in this toy example, but in my actual plot (below) it was still producing wrong legends for some reason.

    enter image description here

    Instead, as suggested in the link provided by Rex5, the following solution works (both in the toy example and in my actual plot), and is simpler too:

    for i in range(1,20):
        if i%3==0 and i%9!=0:
            a, = plt.plot(range(1,20),[i+3 for i in range(1,20)], c='b')
        elif i%9==0:
            b, = plt.plot(range(1,20),[i+9 for i in range(1,20)], c='r')
        else:
            c, = plt.plot(range(1,20),[j for j in range(1,20)],c='g')
    plt.legend([a, b, c], ["Multiples of 3", "Multiples of 9", "All of the rest"])
    plt.show()