oliversm
oliversm

Reputation: 1967

Matplotlib font common font with LaTeX

I can't seem to set the same font for both regular text and mathematical numbers

I am trying to set a font using Matplotlib for a draft article, and the font I need to use is Libertine. Ideally I would just let LaTeX do all the formatting, but it seems set on formatting the maths font with computer modern:

import matplotlib as mpl

rc_fonts = {
    "font.family": "serif",
    "font.size": 20,
    'figure.figsize': (5, 3),
    "text.usetex": True,
    'text.latex.preview': True,
    'text.latex.preamble': [
        r"""
        \usepackage[libertine]{newtxmath}
        \usepackage{libertine}
        """],
}
mpl.rcParams.update(rc_fonts)
import matplotlib.pylab as plt

with the trivial plot

plt.ion()
plt.clf()
plt.plot(range(10))
plt.title("something 0,2,4,6,8 $e=mc^2$")

produces (compare the "2"s)

enter image description here

If instead I use

rc_fonts = {
    "font.family": "serif",
    'font.serif': 'Linux Libertine O',
    "font.size": 20,
    'figure.figsize': (5, 3),
}

then the numbers now match but the maths is not using LaTeX (unsurprisingly):

enter image description here

To get the libertine fonts I downloaded them from https://ctan.org/tex-archive/install/fonts and installed them using the description from https://dallascard.github.io/changing-the-font-in-matplotlib.html (http://andresabino.com/2015/08/18/fonts-and-matplotlib/ seems related). The following questions seem to touch upon the issue, but I can't get a solution to work from them yet:

Upvotes: 4

Views: 4039

Answers (1)

oliversm
oliversm

Reputation: 1967

Based on the comment pointed out by @gboffi, it seems this is not an issue with Matplotlib at all, but can be replicated by LaTeX using the preamble. Switching the order of the packages, which is the order as seen in answers to this question: https://tex.stackexchange.com/questions/544474/libertine-and-math-numbers then the issue is resolved:

rc_fonts = {
    "font.family": "serif",
    "font.size": 20,
    'figure.figsize': (5, 3),
    "text.usetex": True,
    'text.latex.preview': True,
    'text.latex.preamble': [
        r"""
        \usepackage{libertine}
        \usepackage[libertine]{newtxmath}
        """],
}

gives

enter image description here

Upvotes: 3

Related Questions