Python matplotlib图例的标题

Python matplotlib图例的标题,python,matplotlib,patch,Python,Matplotlib,Patch,我知道为一个传奇写一个标题似乎是多余的,但有可能使用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='#f

我知道为一个传奇写一个标题似乎是多余的,但有可能使用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()
我想要标签1上方的图例标题。作为参考,以下是输出:

标题
参数添加到此行:

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

另请参见。

,以便在已接受的答案中添加以下内容:这也适用于Axis对象

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

如果您已经创建了图例,可以使用
set\u title()
修改其标题。关于第一个答案:

legend=plt.legend(句柄=[1,2,3],loc=4,fontsize='small',fancybox=True)
图例。设置标题(“标题”)
#plt.gca().get_legend().set_title()如果未存储
#对象中的图例或正在加载保存的地物。
对于基于轴的第二个答案:

fig,ax=plt.subplot()
绘图([0,1,2],[0,1,4],label='some_label')或创建轴的方式。
ax.图例()
ax.get_legend().设置标题(“标题”)

示例1有一个标题是出于兴趣,你能告诉我是什么原因让你问这个问题,你花了很多精力去写它,甚至在里面放了一张图片,而不是仅仅用谷歌之类的东西或查看文档吗?@ImportanceOfBeingErnest因为他们这么做了,这是谷歌的新答案,我对此表示感谢,因为我是最难找到API的。我喜欢第一句话“我知道为一个图例设置一个标题似乎是多余的”-想法不错。你也可以通过
title\u fontsize
参数控制标题的大小