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.
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:
The following solution seems to work fine.
Set the
gid
attribute of the text element to a unique string: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 attributeid="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.