在Python matplotlib中手动添加图例项
我正在使用matlibplot,我想手动向图例中添加颜色和标签项。我正在向绘图中添加数据,以说明这将导致大量重复 我的想法是:在Python matplotlib中手动添加图例项,python,matplotlib,Python,Matplotlib,我正在使用matlibplot,我想手动向图例中添加颜色和标签项。我正在向绘图中添加数据,以说明这将导致大量重复 我的想法是: ax2.legend(self.labels,colorList[:len(self.labels)]) plt.legend() 其中self.labels是我想要图例标签的项目数,它是大颜色列表的子集。然而,当我运行它时,这不会产生任何结果 我遗漏了什么吗 谢谢您查看了吗 为了实用起见,我引用了 并非所有句柄都可以自动转换为图例条目,因此 通常是必
ax2.legend(self.labels,colorList[:len(self.labels)])
plt.legend()
其中self.labels是我想要图例标签的项目数,它是大颜色列表的子集。然而,当我运行它时,这不会产生任何结果
我遗漏了什么吗
谢谢您查看了吗
为了实用起见,我引用了
并非所有句柄都可以自动转换为图例条目,因此
通常是必要的,以创造一个艺术家,可以。图例句柄不会
必须存在于图形或轴上才能使用
假设我们想要创建一个图例,其中包含一些数据的条目
由红色表示:
编辑
要添加两个修补程序,可以执行以下操作:
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])
我最后写了以下内容:
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)
我正在添加一些代码,以构建来自的答案和来自的注释。在这里,我通过“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))
这是我的第一个答案,因此,对于任何错误/失礼,请提前道歉。这里有一个解决方案,让您可以控制图例线的宽度和样式(其中)
有关更多选项,请查看此项。对于那些希望将手动图例项目添加到具有自动生成项目的单个/通用图例中的人:
#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 使用手动线路和补丁完成示例
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import matplotlib.patches as mpatches
plt.plot([1,2,3,4],[10,20,30,40],label='My Data',color='red')
handles, labels = plt.gca().get_legend_handles_labels()
patch = mpatches.Patch(color='grey', label='manual patch')
line = Line2D([0], [0], label = 'manual line',color='k')
handles.extend([patch,line])
plt.legend(handles=handles)
plt.show()
添加多个文件时,该文件可能会重复吗?我可以列一个补丁列表,然后精确地执行plt.legend(handles=patchList)@Bradyforcier。我尝试像这样添加我的自定义补丁,我在图例中看到两个黑点和补丁。我试着在上面加上红色的补丁,我得到了同样的结果。补丁被添加为plt.legend(mpatches.Patch(color='red',label='The red data'))。原来我一直使用的版本是超旧的0.99。不知道如何找到这个旧APIworks@Bradyforcier我添加了一个带有两个补丁的示例。我不确定它是否能在v0.99上工作。是否也可以手动将一种颜色指定给一个特定值?我是否可以使用圆形面片而不是矩形面片?对于任何使用标准matplotlib.pyplot作为plt的人,我必须这样做:
plt.legend()
handles,labels=plt.gca()。获取\u legend\u handles\u labels()
更好的答案,因为它显示附加到生成的标签,而不是手动添加所有内容。如果我希望标签看起来像一条黑线而不是一个黑色块呢??我试着改变线宽
,但它只改变了块周围的边框。@Shaun Han…见我答案后面的块
#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')
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import matplotlib.patches as mpatches
plt.plot([1,2,3,4],[10,20,30,40],label='My Data',color='red')
handles, labels = plt.gca().get_legend_handles_labels()
patch = mpatches.Patch(color='grey', label='manual patch')
line = Line2D([0], [0], label = 'manual line',color='k')
handles.extend([patch,line])
plt.legend(handles=handles)
plt.show()