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

2024-09-22 14:26:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个绘图,其中显示了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()

enter image description here

但是图例没有正确显示颜色。为什么会这样?怎么解决?你知道吗


Tags: ofinimport绘图forplotmatplotlibrange
2条回答

我尝试了Rex5的答案;它在这个玩具示例中起作用,但在我的实际情节(下面)中,由于某种原因,它仍然产生了错误的传说。你知道吗

enter image description here

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

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

已解决:

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链接中提供的doc链接,这将有助于解释答案。你知道吗

相关问题 更多 >