Bra*_*aux 30 python patch matplotlib
我知道拥有一个传奇的标题似乎相当多余,但是有可能使用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()
Run Code Online (Sandbox Code Playgroud)
Alp*_*aya 40
将title参数添加到此行:
legend = plt.legend(handles=[one, two, three], title="title", loc=4, fontsize='small', fancybox=True)
Run Code Online (Sandbox Code Playgroud)
另请参阅构造函数的官方文档legend.
Ern*_*ler 19
只是为了添加到已接受的答案中,这也适用于 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')
Run Code Online (Sandbox Code Playgroud)
iba*_*ond 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.
Run Code Online (Sandbox Code Playgroud)
对于基于轴的第二个答案:
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")
Run Code Online (Sandbox Code Playgroud)