手动添加图例项Python matplotlib

2024-09-30 16:22:03 发布

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

我正在使用matlibplot,我想手动向图例添加颜色和标签项。我将数据添加到绘图中以指定会导致大量重复。

我的想法是:

    ax2.legend(self.labels,colorList[:len(self.labels)])
    plt.legend()

其中self.labels是我想要的图例标签的项目数,它采用大颜色列表的子集。不过,当我运行它时,这不会产生任何结果。

我有什么遗漏吗?

谢谢


Tags: 数据self绘图labelslen颜色plt标签
3条回答

这里有一个解决方案,让您控制图例线的宽度和样式(在a lot of other things之间)。

import matplotlib.pyplot as plt
from matplotlib.lines import Line2D

colors = ['black', 'red', 'green']
lines = [Line2D([0], [0], color=c, linewidth=3, linestyle='--') for c in colors]
labels = ['black data', 'red data', 'green data']
plt.legend(lines, labels)
plt.show()

output of the code above

更多选项,请看这个matplotlib gallery sample

你检查过Legend Guide了吗?

为了实用,我引用了guide中的示例。

Not all handles can be turned into legend entries automatically, so it is often necessary to create an artist which can. Legend handles don’t have to exists on the Figure or Axes in order to be used.

Suppose we wanted to create a legend which has an entry for some data which is represented by a red color:

import matplotlib.patches as mpatches
import matplotlib.pyplot as plt

red_patch = mpatches.Patch(color='red', label='The red data')
plt.legend(handles=[red_patch])

plt.show()

enter image description here

编辑

要添加两个修补程序,可以执行以下操作:

import matplotlib.patches as mpatches
import matplotlib.pyplot as plt

red_patch = mpatches.Patch(color='red', label='The red data')
blue_patch = mpatches.Patch(color='blue', label='The blue data')

plt.legend(handles=[red_patch, blue_patch])

enter image description here

我添加了一些代码来构建来自https://stackoverflow.com/users/2029132/gabra的答案和来自https://stackoverflow.com/users/5946578/brady-forcier的注释。在这里,我通过a'for'循环手动向图例添加元素。

首先,我创建了一本字典,里面有我的传奇名字和想要的颜色。我实际上是在加载数据时这样做的,但这里我只是明确定义:

import matplotlib.patches as mpatches
import matplotlib.pyplot as plt    

legend_dict = { 'data1' : 'green', 'data2' : 'red', 'data3' : 'blue' }

然后我循环遍历字典,并为每个条目定义一个补丁并附加到一个列表“patch list”。然后我用这个列表来创建我的传奇。

patchList = []
for key in legend_dict:
        data_key = mpatches.Patch(color=legend_dict[key], label=key)
        patchList.append(data_key)

plt.legend(handles=patchList)
plt.savefig('legend.png', bbox_inches='tight')

这是我的输出: legend example

我不担心图例条目是按特定顺序排列的,但是您可以通过

plt.legend(handles=sorted(patchList))

这是我的第一个回答,因此,对于任何错误/失礼,请提前道歉。

相关问题 更多 >