Python matplotlib 图例的标题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44620013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Title for matplotlib legend
提问by Brandon Molyneaux
I know it seems fairly redundant to have a title for a legend, but is it possible using matplotlib?
我知道为图例设置标题似乎相当多余,但是是否可以使用 matplotlib?
Here's a snippet of the code I have:
这是我拥有的代码片段:
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()
I would want the title of the legend above label1. For reference, this is the output:
回答by Alper F?rat Kaya
Add the title
parameter to the this line:
将title
参数添加到此行:
legend = plt.legend(handles=[one, two, three], title="title",
loc=4, fontsize='small', fancybox=True)
See also the official docs for the legend
constructor.
另请参阅构造函数的官方文档legend
。
回答by ErnestScribbler
Just to add to the accepted answer that this also works with an Axes object.
只是为了添加到已接受的答案中,这也适用于 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')