如何手动创建图例
- 2025-01-22 08:45:00
- admin 原创
- 86
问题描述:
我正在使用 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)
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD