问题
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.
回答1:
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)
回答2:
The following solution seems to work fine.
Set the
gidattribute 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.,
lxmlto 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.
来源:https://stackoverflow.com/questions/12387585/python-matplotlib-svg-and-hyperlinks-in-text-labels