简体   繁体   中英

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)

在此处输入图片说明

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):

在此处输入图片说明

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:

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM