Matplotlib图例的标题

113

我知道为传说添加标题似乎有些多余,但在matplotlib中是否可能实现?

这是我拥有的一小段代码:

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

one = mpatches.Patch(facecolor='#f3f300', label='label1', linewidth = 0.5, edgecolor = 'black')
two = mpatches.Patch(facecolor='#ff9700', label = 'label2', linewidth = 0.5, edgecolor = 'black')
three = mpatches.Patch(facecolor='#ff0000', label = 'label3', linewidth = 0.5, edgecolor = 'black')

legend = plt.legend(handles=[one, two, three], loc = 4, fontsize = 'small', fancybox = True)

frame = legend.get_frame() #sets up for color, edge, and transparency
frame.set_facecolor('#b4aeae') #color of legend
frame.set_edgecolor('black') #edge color of legend
frame.set_alpha(1) #deals with transparency
plt.show()
我会将图例标题置于label1上方。参考以下输出: 显示图例

1
示例1有一个标题 https://matplotlib.org/examples/pylab_examples/legend_demo3.html - Nick Becker
1
出于好奇,你能告诉我是什么原因促使你提出这个问题,付出了很多努力来写它,甚至放了一张图片,而不是像matplotlib图例标题那样只是谷歌一下或查看文档吗? - ImportanceOfBeingErnest
12
@ImportanceOfBeingErnest因为他们这样做了,这是新的Google答案,我很感激,因为我之前一直很难找到API。 Translated: @ImportanceOfBeingErnest因为他们这样做了,这是谷歌的新答案,我很感激,因为我之前一直很难找到这个API。 - Seanny123
3个回答

167

在这一行中添加title参数:

legend = plt.legend(handles=[one, two, three], title="title",
                    loc=4, fontsize='small', fancybox=True)

请参阅官方文档中的legend构造器


14
您可以通过title_fontsize参数控制标题的大小。 - dopexxx
如果补丁标签代表目标类别值,例如catdog,属于目标类animal,并且我已经将色调设置为该animal类/列,那么如何使这些标签自动继承该色调?即我不想手动设置标签颜色,我希望它们由animal的色调设置。 - Edison

39

只是为了补充被接受的答案,这也适用于一个坐标轴对象。

fig, ax = plt.subplots()
ax.plot([0, 1, 2], [0, 1, 4], label='some_label') # Or however the Axes was created.
ax.legend(title='This is My Legend Title')

17
如果您已经创建了图例,可以使用set_title()修改其标题。对于第一个答案:
legend = plt.legend(handles=[one, two, three], loc=4, fontsize='small', fancybox=True)
legend.set_title("title")   
# plt.gca().get_legend().set_title() if you didn't store the
# legend in an object or you're loading a saved figure. 

第二个基于Axes的答案:

fig, ax = plt.subplots()
ax.plot([0, 1, 2], [0, 1, 4], label='some_label') # Or however the Axes was created.
ax.legend()
ax.get_legend().set_title("title")

1
如果您有一个图例,可以使用fig.legends[0].set_title('title')来设置标题。请注意,如果有多个图例,则legends将返回所有图例。 - craymichael

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接