Matplotlib传奇中的字幕

时间:2016-07-19 15:57:22

标签: python matplotlib plot legend cartopy

我正在用matplotlib做一些绘图,我有一个传说告诉观众哪些传感器记录了点。有多种类型的多个传感器,我希望在图例中有字幕,告诉观众每个组的传感器类型。我有一个有效的解决方案,但它有点像黑客,如下所示:

enter image description here

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

1 个答案:

答案 0 :(得分:5)

我能想到的最好的方法是为字符串创建一个自定义处理程序。

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

output

我的基础是http://matplotlib.org/users/legend_guide.html中的示例。