【问题标题】:Why isn't the legend in matplotlib correctly displaying the colors?为什么 matplotlib 中的图例不能正确显示颜色?
【发布时间】:2019-12-06 09:18:39
【问题描述】:

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

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

【问题讨论】:

  • 您好,请查看this,在此之前我也在努力解决您的问题。

标签: python matplotlib legend line-plot


【解决方案1】:

已解决:

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 链接,这将有助于答案解释。

【讨论】:

    【解决方案2】:

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

    相反,正如 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()
    

    【讨论】:

    • 我回答了玩具示例,因为它只是被提及(不是实际的)。不过很高兴您找到了解决方案!
    • @Rex5 奇怪的是为什么您的解决方案不适用于我的实际数据。
    • 您在字典中添加了第四对 key:value 并在 for 循环中添加了 _nolegend_ 子句?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-05
    • 2023-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多