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

标签 python matplotlib plot

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

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/

相关文章:

python - pandas 中的分组和转换

python - 这个实体定义模型是否太冗长了?

python - 将 pandas 数据框中的多行合并为一行?

python - 在 map 上绘制点,但错误代码为 "ValueError: ' box_aspect' 且 'fig_aspect' 必须为正值"

python - Matplotlib:使最终图形尺寸与 savefig() 和 bbox_extra_artists 匹配 figsize

R - 绘制六边形镶嵌

使用 Julia 绘制相关矩阵的热图

python - 依赖单元测试

python - 省略 matplotlib 图中的连接线,例如y = tan(x)

r - 如何让ggplot线跑到边缘?