python,matplotlib,svg和文本标签中的超链接 [英] python, matplotlib, svg and hyperlinks in text labels

查看:800
本文介绍了python,matplotlib,svg和文本标签中的超链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

matplotlib 中,可以创建带有超链接的SVG数字

例如,我可以使用 scatter 绘制标记的方法,以便每个标记都是超链接。

For example, I can use the scatter method to draw markers so that each individual marker is a hyperlink.

但是,我的一些标记有文字标签,我使用 text 方法创建。我可以以某种方式将文本标签转换为超链接吗?

However, some of my markers have text labels that I have created with the text method. Can I somehow turn the text labels into hyperlinks as well?

到目前为止,我已经能够实现以下目标。首先,创建带有边界框的文本标签,以便 bbox 字典具有 url 参数:

So far I have been able to achieve the following. First, create a text label with a bounding box so that the bbox dictionary has a url parameter:

ax.text(x, y, label, bbox=dict(boxstyle=..., url=url))

然后补丁 matplotlib / backends / backend_svg.py (版本1.1。 1)稍微,替换

Then patch matplotlib/backends/backend_svg.py (version 1.1.1) slightly, replacing

self.writer.end('</a>')

with

self.writer.end('a')

现在它几乎有效。我可以点击环绕文本的区域,但不能点击文本本身(否则,如果我在白色背景上有黑色文字,我可以点击白色部分的任何地方,但不能点击黑色部分)。

Now it almost works. I can click on the area that surrounds the text, but not the text itself (put otherwise, if I have black text on white background, I can click anywhere in the white parts, but not in the black parts).

将整个文本标签转换为超链接(文本及其边界)的最简单方法是什么?盒子)?

What is the easiest way to turn the entire text label into a hyperlink (both the text and its bounding box)?

理想情况下,我更喜欢一种不需要修补matplotlib库的解决方案。

Ideally, I would prefer a solution that does not require that I patch the matplotlib library.

推荐答案

以下解决方案似乎工作正常。

The following solution seems to work fine.


  • 设置 gid 文本元素属性为唯一字符串:

  • Set the gid attribute of the text element to a unique string:

ax.text(x, y, label, gid='foo')


  • 像往常一样创建SVG文件;还没有超链接。

  • Create the SVG file as usual; there are no hyperlinks yet.

    使用例如 lxml 来解析SVG文件。找到属性 id =foo的唯一< g> 元素。修改XML树:将< g> ...< / g> 替换为< a ...>< g> ...< / g取代;< / A> 。保存结果。

    Use, e.g., lxml to parse the SVG file. Find the unique <g> element with the attribute id="foo". Modify the XML tree: replace <g>...</g> with <a ...><g>...</g></a>. Save the result.

    同样的方法似乎一般都有效;许多元素接受 gid 参数。

    The same approach seems to work in general; many elements accept a gid parameter.

    这篇关于python,matplotlib,svg和文本标签中的超链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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