Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 839
Arcturus B Avatar asked Feb 23 '26 19:02

Arcturus B


1 Answers

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.

like image 95
Michael Goerz Avatar answered Feb 25 '26 08:02

Michael Goerz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!