How to make a plot with legend entries that are hyperlinks

Published

March 29, 2023

This is a demo on what the title says, also see this matplotlib issue. The trick works with SVG and PDF. Try to click on “BBC” in the legend.

from matplotlib import pyplot as plt
import numpy as np

# generate SVG images instead of PNG
%config InlineBackend.figure_formats = ['svg']

# required for SVG to accept a click on the text area and not just on the text path
plt.rcParams["svg.fonttype"] = "none"

plt.figure()
plt.scatter([1, 2], [4, 6], label="BBC")
plt.scatter([1, 2, 3], [6, 5, 4], label="Google")

urls = {"BBC": 'https://www.bbc.com/news'}

leg = plt.legend()
for ta in leg.texts:
    t = ta.get_text()
    try:
        url = urls[t]
        ta.set_url(url)
    except KeyError:
        pass

# plt.savefig('scatter.svg')
# plt.savefig('scatter.pdf')