gpt4 book ai didi

python - Matplotlib - 向图例行添加标题

转载 作者:太空狗 更新时间:2023-10-30 02:26:43 26 4
gpt4 key购买 nike

我创建了一个包含两行的图例,如下所示:

enter image description here

是否可以为每一行添加标签/标题,当我显示图例时,图例显示为:

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

enter image description here

这里的主要缺点是行标题句柄所在的位置有很多空白。

设置 markerfirst=False 会使这不太明显:

enter image description here

如果所有这些都不是一个选项,则需要更深入地研究这个传说。图例由 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)

这现在几乎应该给出所需的行标题

enter image description here


列标题 的等价物可以通过像这样交换 [: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)

matplotlib legend column titles

关于python - Matplotlib - 向图例行添加标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44071525/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com