Matplotlib - 为图例行添加标题
·
问题:Matplotlib - 为图例行添加标题
我创建了一个包含两行的图例,如下所示:

是否可以为每一行添加标签/标题,当我显示图例时,图例显示为:
Title1: One One One
Title2: Two Two Two
非常感谢您的任何建议!
解答
没有用于在图例中设置行标题的内置选项。
作为一种解决方法,您可以在图例中预先设置第一列,该列没有句柄,只有标签。
import matplotlib.pyplot as plt
import numpy as np
y = np.exp(-np.arange(5))
markers=["s", "o", ""]
labels =["one", "two"]
fig, ax = plt.subplots()
for i in range(6):
ax.plot(y*i+i/2., marker=markers[i//2], label=labels[i%2])
h, l = ax.get_legend_handles_labels()
ph = [plt.plot([],marker="", ls="")[0]]*2
handles = ph + h
labels = ["Title 1:", "Title 2:"] + l
plt.legend(handles, labels, ncol=4)
plt.show()

这里的主要缺点是行标题的句柄所在的位置有很多空白。
设置markerfirst=False会使这不太明显:

如果所有这些都不是一种选择,则需要更深入地了解传说。图例由Packer个对象组成。然后可以从第一列中识别占用空间并将它们的宽度设置为零的那两个打包器
leg = plt.legend(handles, labels, ncol=4)
for vpack in leg._legend_handle_box.get_children()[:1]:
for hpack in vpack.get_children():
hpack.get_children()[0].set_width(0)
这现在应该几乎给出了所需的行标题

列标题的等价物可以通过像这样交换[:1]来实现:
handles = ph[:1] + h[::2] + ph[1:] + h[1::2]
labels = ["Title 1:"] + l[::2] + ["Title 2:"] + l[1::2]
leg = plt.legend(handles, labels, ncol=2)
for vpack in leg._legend_handle_box.get_children():
for hpack in vpack.get_children()[:1]:
hpack.get_children()[0].set_width(0)

更多推荐

所有评论(0)