Matplotlib图例中的字幕 [英] Subtitles within Matplotlib legend

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

问题描述

我正在用matplotlib进行一些绘图,并且有一个图例,它告诉查看者记录点的传感器.有多种类型的多个传感器,我想在图例中添加字幕,以告诉观众每个组是哪种传感器.我有一个可行的解决方案,但这有点hack,如下所示:

I am doing some plotting with matplotlib, and I have a legend which tells the viewer which sensors the points were recorded with. There are multiple sensors of multiple types, and I'd like to have subtitles within the legend to tell the viewer what kind of sensor each group is. I have a working solution, but it's a bit of a hack, shown here:

创建图例时,它接受两个重要的参数:图例标记列表和图例标签列表.我当前的解决方案是将字幕标记设置为带有白色轮廓的白框,并用两个换行符包围字幕.看起来不错,但是如果没有缩进字幕,它将显得更加专业.我尝试过的两种解决方法是将字幕的标记设置为无",还将字幕的标记设置为所需的字幕字符串,并将其标签设置为空字符串.都没有工作.有人对这个有经验么?非常感谢.

When the legend is created, it accepts two important arguments: a list of legend markers, and a list of legend labels. My current solution is to set the subtitle marker to be a white box with a white outline, and have the subtitle lable be surrounded by two newline characters. It looks alright, but it would look much more professional if the subtitles were not indented. Two workarounds I have tried have been setting the subtitle's marker to None, and also setting the subtitle's marker to the desired subtitle string and its label to an empty string. Neither have worked. Does anyone have any experience with this? Thanks so much.

推荐答案

我能想到的最好的办法是为字符串创建自定义处理程序.

The best I could come up with is to make a custom handler for a string.

import matplotlib.pyplot as plt
import matplotlib.text as mtext


class LegendTitle(object):
    def __init__(self, text_props=None):
        self.text_props = text_props or {}
        super(LegendTitle, self).__init__()

    def legend_artist(self, legend, orig_handle, fontsize, handlebox):
        x0, y0 = handlebox.xdescent, handlebox.ydescent
        title = mtext.Text(x0, y0, r'\underline{' + orig_handle + '}', usetex=True, **self.text_props)
        handlebox.add_artist(title)
        return title


[line1] = plt.plot(range(10))
[line2] = plt.plot(range(10, 0, -1), 'o', color='red')
plt.legend(['Title 1', line1, 'Title 2', line2], ['', 'Line 1', '', 'Line 2'],
           handler_map={basestring: LegendTitle({'fontsize': 18})})

plt.show()

我基于 http://matplotlib.org/users/legend_guide.html 中的示例a>.

这篇关于Matplotlib图例中的字幕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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