Matplotlib-向图例行添加标题 [英] Matplotlib - add titles to the legend rows

查看:69
本文介绍了Matplotlib-向图例行添加标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I created a legend which contains two rows, as below:

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

Is it possible to add a label/title to each row, that when I show the plot the legend appears as:

Title1: One One One
Title2: Two Two Two

非常感谢您的任何建议!

Many thanks for any suggestions!

推荐答案

没有内置选项可在图例中设置行标题.
作为一种解决方法,您可以为图例预先设置第一列,该列没有句柄,只有标签.

There is no built-in option to set row titles in legends.
As a workaround you may preprend a first column to the legend, which has no handles, but only labels.

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

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

The main drawback here is that there is a lot of whitespace at the positions where the handles of the row titles would sit.

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

Setting markerfirst=False would make this less apparent:

如果所有这些都不是一个选择,则需要深入了解图例.图例由 Packer 对象组成.然后可以从第一列中识别出占据空间并将其宽度设置为零的那两个封隔器

If all of those are not an option one needs to dive a little deeper into the legend. The legend consists of Packer objects. It is then possible to identify those two packers from the first column that take up the space and set their width to zero

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)

这现在应该可以提供所需的行标题了

This should now pretty much give the desired row titles

列标题的等价物可以通过像这样交换[:1]来实现:

The equivalent thing for column titles can be achieved by swapping the [:1] like this:

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-向图例行添加标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆