手动添加图例项 Python matplotlib

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39500265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:20:41  来源:igfitidea点击:

Manually add legend Items Python matplotlib

pythonmatplotlib

提问by Brady forcier

I am using matlibplot and I would like to manually add items to the legend that are a color and a label. I am adding data to to the plot to specifying there would lead to a lot of duplicates.

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

My thought was to do:

我的想法是这样做:

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

Where self.labels is the number of items I want legend lables for that takes a subset of the large color list. However this yields nothing when I run it.

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

Am I missing anything?

我错过了什么吗?

Thanks

谢谢

回答by gabra

Have you checked the Legend Guide?

你看过传奇指南吗?

For practicality, I quote the example from the 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

在此处输入图片说明

Edit

编辑

To add two patches you can do this:

要添加两个补丁,您可以执行以下操作:

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

在此处输入图片说明

回答by R2-D2

Here's a solution which let's you control the width and style of your legend lines (among 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

上面代码的输出

For even more options, take a look at this matplotlib gallery sample.

有关更多选项,请查看此matplotlib 库示例

回答by birac

I'm adding some code to build on the answer from https://stackoverflow.com/users/2029132/gabraand the comment from https://stackoverflow.com/users/5946578/brady-forcier. Here, I manually add elements to a legend viaa 'for' loop.

我添加一些代码来构建从答案https://stackoverflow.com/users/2029132/gabra和评论https://stackoverflow.com/users/5946578/brady-forcier。在这里,我通过“for”循环手动将元素添加到图例中。

First I create a dictionary with my legend names and desired colours. I actually do this as I load in my data, but here I'm just explicitly defining:

首先,我用我的图例名称和所需的颜色创建一个字典。我实际上是在加载数据时这样做的,但在这里我只是明确定义:

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

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

Then I loop through the dictionary and for each entry define a patch and append to a list, 'patchList'. I then use this list to create my legend.

然后我遍历字典并为每个条目定义一个补丁并附加到一个列表“patchList”。然后我使用这个列表来创建我的图例。

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

Here's my output: legend example

这是我的输出: 图例示例

I'm not bothered about the legend entries being in a particular order, but you could probably achieve this with

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

plt.legend(handles=sorted(patchList))

This is my first answer, so apologies in advance for any errors/faux pas.

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

回答by CreekGeek

For those wanting to add manual legend items into a single/common legend with automatically generated items:

对于那些想要将手动图例项目添加到具有自动生成项目的单个/通用图例中的人:

# where some data has already been plotted to ax
handles, labels = ax.get_legend_handles_labels()

# manually define a new patch 
patch = mpatches.Patch(color='grey', label='Manual Label')

# handles is a list, so append manual patch
handles.append(patch) 

# plot the legend
plt.legend(handles=handles, loc='upper center')

Example of common legend with manual and auto-generated items:
example of common legend with manual and auto-generated items

带有手动和自动生成项目的常见图例示例:
带有手动和自动生成项目的常见图例示例

回答by tlanigan

I ended up writing this out:

我最终写了这个:

def plot_bargraph_with_groupings(df, groupby, colourby, title, xlabel, ylabel):
    """
    Plots a dataframe showing the frequency of datapoints grouped by one column and coloured by another.
    df : dataframe
    groupby: the column to groupby
    colourby: the column to color by
    title: the graph title
    xlabel: the x label,
    ylabel: the y label
    """

    import matplotlib.patches as mpatches

    # Makes a mapping from the unique colourby column items to a random color.
    ind_col_map = {x:y for x, y in zip(df[colourby].unique(),
                               [plt.cm.Paired(np.arange(len(df[colourby].unique())))][0])}


    # Find when the indicies of the soon to be bar graphs colors.
    unique_comb = df[[groupby, colourby]].drop_duplicates()
    name_ind_map = {x:y for x, y in zip(unique_comb[groupby], unique_comb[colourby])}
    c = df[groupby].value_counts().index.map(lambda x: ind_col_map[name_ind_map[x]])

    # Makes the bargraph.
    ax = df[groupby].value_counts().plot(kind='bar',
                                         figsize=FIG_SIZE,
                                         title=title,
                                         color=[c.values])
    # Makes a legend using the ind_col_map
    legend_list = []
    for key in ind_col_map.keys():
        legend_list.append(mpatches.Patch(color=ind_col_map[key], label=key))

    # display the graph.
    plt.legend(handles=legend_list)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)