Python matlplotlib add hyperlink to text

This example shows how to set hyperlinks if you're outputting an SVG. Note that this only makes sense for SVG. If the plot is just an image, it's just an image, and images can't have hyperlinks in them.

If you want to be able to click on the object in the interactive plotting window and have that act like a hyperlink, you could create an event handler to handle the "pick" event, and have that open a browser or whatever. See this example for how to do pick events. Matplotlib plots aren't web pages or even really documents, they're just windows with graphics displayed in them, so they don't support hyperlinks as such; using a pick event you can emulate a hyperlink by opening a web browser when an object is clicked.

Edit: You are right, it doesn't work. It seems that the URL property is only read and used for certain types of objects. Googling, I see some old matplotlib mailing list discussion of it, where it seems the idea was to gradually add URL support to different artist types, but I guess they never got around to it. I would suggest you raise a bug about this on the matplotlib bug tracker.

In the meantime, there is a way to do it, but it is somewhat roundabout. The URL is drawn for PathCollection objects, so you could make a Path out of your text, then make a PathCollection out of that path, and then add that PathCollection to your plot. Here's an example:

pyplot.scatter([1, 2, 3], [4, 5, 6])
t = mpl.text.TextPath((2, 4), 'This is text', size=0.1)
pc = mpl.collections.PathCollection([t])
pc.set_urls(['http://www.google.com'])
ax = pyplot.gca()
ax.add_collection(pc)
pyplot.draw()
f = pyplot.gcf()
f.canvas.print_figure('fig.svg')

Note that you must use set_urls and not set_url. This method produces an SVG with clickable text, but it has some drawbacks. Most notably, it seems you have to set the text size manually in data coordinates, so it may take some fiddling to find a text size that isn't too ridiculously huge or tiny relative to the magnitude of your plotted data.


Adding a hyperlink makes sense when e.g. using an SVG file.

The url property works in newer matplotlib versions:

text = plt.annotate("Link", xy=(2,5), xytext=(2.2,5.5),
                    url='http://matplotlib.org', 
                    bbox=dict(color='w', alpha=1e-6, url='http://matplotlib.org'))

For example, in a Jupyter notebook, which runs in a browser anyways, one could display an SVG with hyperlinks like this:

import matplotlib.pyplot as plt
from IPython.display import set_matplotlib_formats
set_matplotlib_formats("svg")

fig, ax = plt.subplots()
ax.scatter([1, 2, 3], [4, 5, 6])
text = ax.annotate("Link", xy=(2,5), xytext=(2.2,5.5),
                    url='http://matplotlib.org', 
                    bbox=dict(color='w', alpha=1e-6, url='http://matplotlib.org'))

In the figure produced this way you may click on the link and be directed to matplotlib.org.