python, matplotlib, svg and hyperlinks in text lab

2019-06-17 04:31发布

In matplotlib, it is possible to create SVG figures with hyperlinks.

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

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?


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

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

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

2条回答
一纸荒年 Trace。
2楼-- · 2019-06-17 05:10

This change in matplotlib git enables rendering Text object's URL fields as links in the rendered SVG.

Including the code by @travc this could look like:

url = "https://matplotlib.org/"
txt = plt.text(x, y, url, url=url, bbox = dict(color='w', alpha=0.01, url=url)
查看更多
SAY GOODBYE
3楼-- · 2019-06-17 05:18

The following solution seems to work fine.

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

    ax.text(x, y, label, gid='foo')
    
  • Create the SVG file as usual; there are no hyperlinks yet.

  • 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.

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

查看更多
登录 后发表回答