为什么 matplotlib 中的图例不能正确显示颜色?

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

我有一个图,其中显示了 3 个不同的线图。因此,我明确指定图例以显示 3 种颜色,每个图一种。下面是一个玩具示例:

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

但是图例没有正确显示颜色。为什么会这样以及如何解决?

已解决:

import matplotlib.pyplot as plt

my_labels = {"x1" : "Multiples of 3", "x2" : "Multiples of 9","x3":'All of the rest'}

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', label = my_labels["x1"])
        my_labels["x1"] = "_nolegend_"
    elif i%9==0:
        plt.plot(range(1,20),[i+9 for i in range(1,20)], c='r', label = my_labels["x2"])
        my_labels["x2"] = "_nolegend_"
    else:
        plt.plot(range(1,20),[j for j in range(1,20)],c='g', label = my_labels["x3"])
        my_labels["x3"] = "_nolegend_"
plt.legend(loc="best") #
plt.show()

请参阅this link中提供的doc link,这将有助于解释答案。

我试过Rex5的答案;它在这个玩具示例中有效,但在我的实际情节中(下图)由于某种原因它仍然产生错误的图例。

相反,正如 Rex5 提供的 中所建议的,以下解决方案有效(在玩具示例和我的实际情节中),并且也更简单:

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