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

Posted

技术标签:

【中文标题】为啥 matplotlib 中的图例不能正确显示颜色?【英文标题】: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,在此之前我也在努力解决您的问题。 【参考方案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_ 子句?

以上是关于为啥 matplotlib 中的图例不能正确显示颜色?的主要内容,如果未能解决你的问题,请参考以下文章

Python+matplotlib可视化设置图例4个精选案例

Python+matplotlib可视化设置图例4个精选案例

Matplotlib 散点图图例

matplotlib中的legend()——用于显示图例

Pandas、matplotlib 和 plotly - 如何修复系列图例?

Matplotlib 轴图例在 barh 中仅显示一个标签