matplotlib图例的标题

时间:2017-06-18 22:09:36

标签: 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='#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以上的图例标题。作为参考,这是输出: Showing legend

3 个答案:

答案 0 :(得分:29)

title参数添加到此行:

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

另请参阅official docs for the legend constructor

答案 1 :(得分:13)

只需将其也与Axes对象一起使用添加到接受的答案即可。

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

答案 2 :(得分:1)

如果您已经创建了图例,您可以使用 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")