python - Matplotlib 图例中的字幕

标签 python matplotlib plot legend cartopy

我正在使用 matplotlib 进行绘图,我有一个图例可以告诉查看器这些点是用哪些传感器记录的。有多种类型的多个传感器,我想在图例中加上字幕来告诉观众每组是什么类型的传感器。我有一个可行的解决方案,但有点乱,如下所示:

enter image description here

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

最佳答案

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

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 中的示例.

关于python - Matplotlib 图例中的字幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38463369/

相关文章:

python - 在 urllib2.urlopen 中使用 mimetools.Message

python - 使用 matplotlib 创建自己的颜色图并绘制颜色比例

python - 如何将离散值映射到 seaborn 中的热图?

matlab - 在 MATLAB 中使用位于圆柱体上的点的密度为圆柱体着色

r - R中同一时间序列图有多种颜色,可能吗?

python - 脚本无法通过 Selenium 和 Python 使用 xpath 或 id 或其他任何内容找到按钮

python - selenium.common.exceptions.WebDriverException : Message: invalid session id using Selenium with ChromeDriver and Chrome through Python

python - 使用 Python 更正 matplotlib 中的 x 值

python-2.7 - 导入错误 : 'No module named plotly.plotly' in LinuxMint17. 3

python - 我如何针对 python HTTPConnection 进行 read()/write() 操作?