如何手动创建图例

2025-01-22 08:45:00
admin
原创
86
摘要:问题描述:我正在使用 matplotlib,我想手动将颜色和标签添加到图例中。我正在将数据添加到图中以指定会导致大量重复。我的想法是: ax2.legend(self.labels,colorList[:len(self.labels)]) plt.legend() 其中 self.labels...

问题描述:

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

我的想法是:

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

其中 self.labels 是我想要的图例标签的项目数,它取自大型颜色列表的子集。然而,当我运行它时,它什么也没产生。


解决方案 1:

您查看过图例指南吗?

为了实用性,我引用了指南中的示例。

并非所有手柄都可以自动转换为图例条目,因此通常需要创建一个可以这样做的艺术家。图例手柄不必存在于图形或轴上即可使用。

假设我们想要创建一个图例,其中包含一些用红色表示的数据:

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

在此处输入图片描述

编辑

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

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

在此处输入图片描述

解决方案 2:

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

#Imports
import matplotlib.patches as mpatches

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

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

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

添加于 2021-05-23(修订于 2023-04-21,包含要点)

带有手动线、面和点的完整示例

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

# from data
plt.plot([1,2,3,4], [10,20,30,40], label='My Data (line)', color='red')
plt.scatter([2.5], [15], label='My Data (scatter point)', color='b') # plotting single point via scatter
plt.plot([3.5], [20], label= ' My Data (plot point)', marker='o', markersize=10, 
         markeredgecolor='k', markerfacecolor='g', linestyle='') # plotting single point via plot with null linestyle

# access legend objects automatically created from data
handles, labels = plt.gca().get_legend_handles_labels()

# create manual symbols for legend
patch = mpatches.Patch(color='grey', label='manual patch')   
line = Line2D([0], [0], label='manual line', color='k')
point = Line2D([0], [0], label='manual point', marker='s', markersize=10, 
         markeredgecolor='r', markerfacecolor='k', linestyle='')

# add manual symbols to auto legend
handles.extend([patch, line, point])

plt.legend(handles=handles)
plt.show()

在此处输入图片描述

解决方案 3:

这里有一个解决方案,可以让您控制图例线的宽度和样式(以及许多其他东西)。

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

上述代码的输出

如需更多选项,请查看此matplotlib 图库示例。

解决方案 4:

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

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

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

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

然后我循环遍历字典,为每个条目定义一个补丁并附加到列表“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')

这是我的输出:
图例示例

我并不关心图例条目是否按特定顺序排列,但你可以通过以下方式实现这一点

plt.legend(handles=sorted(patchList))

这是我的第一个回答,因此对于任何错误/失礼之处,我深表歉意。

解决方案 5:

我最终写了以下内容:

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)
相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   1565  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1354  
  信创国产芯片作为信息技术创新的核心领域,对于推动国家自主可控生态建设具有至关重要的意义。在全球科技竞争日益激烈的背景下,实现信息技术的自主可控,摆脱对国外技术的依赖,已成为保障国家信息安全和产业可持续发展的关键。国产芯片作为信创产业的基石,其发展水平直接影响着整个信创生态的构建与完善。通过不断提升国产芯片的技术实力、产...
国产信创系统   21  
  信创生态建设旨在实现信息技术领域的自主创新和安全可控,涵盖了从硬件到软件的全产业链。随着数字化转型的加速,信创生态建设的重要性日益凸显,它不仅关乎国家的信息安全,更是推动产业升级和经济高质量发展的关键力量。然而,在推进信创生态建设的过程中,面临着诸多复杂且严峻的挑战,需要深入剖析并寻找切实可行的解决方案。技术创新难题技...
信创操作系统   27  
  信创产业作为国家信息技术创新发展的重要领域,对于保障国家信息安全、推动产业升级具有关键意义。而国产芯片作为信创产业的核心基石,其研发进展备受关注。在信创国产芯片的研发征程中,面临着诸多复杂且艰巨的难点,这些难点犹如一道道关卡,阻碍着国产芯片的快速发展。然而,科研人员和相关企业并未退缩,积极探索并提出了一系列切实可行的解...
国产化替代产品目录   28  
热门文章
项目管理软件有哪些?
云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用