Arcturus B
Arcturus B

Reputation: 5621

How to add hyperlink to PDF using Matplotlib

I’m generating figures with Matplotlib’s PDF backend:

import matplotlib.pyplot as plt
plt.title('Foo')
plt.savefig('bar.pdf', format='pdf')

What are my options to render the title (or any other label) a clickable hyperlink?

Upvotes: 3

Views: 2162

Answers (1)

Michael Goerz
Michael Goerz

Reputation: 4460

Using the PGF backend, you gain the full flexibility of LaTeX, including the possibility to define hyperlinks (or internal references):

import numpy as np
import matplotlib
matplotlib.use('pgf')
import matplotlib.pyplot as plt

# Example data
t = np.arange(0.0, 1.0 + 0.01, 0.01)
s = np.cos(4 * np.pi * t) + 2

plt.rc('text', usetex=True)
plt.rc('font', family='serif')
matplotlib.rcParams['pgf.preamble'] = [r'\usepackage{hyperref}', ]

plt.plot(t, s)

plt.xlabel(r'\textbf{time} (s)')
plt.ylabel(r'\textit{voltage} (mV)')
plt.title(r"\href{http://www.google.com}{This title links to google}", color='gray')

plt.savefig('tex_demo.pdf')

Unfortunately, I haven't been able to get this to work with other backends (setting text.latex.preamble instead of pgf.preamble). It appears that while other backends also process the strings through latex, they strip out the hyperlink.

Upvotes: 4

Related Questions