import matplotlib
 
 
def setup_dpi(plt_obj, dpi=75, width=8, height=6):
    plt_obj.rcParams.update({"figure.dpi": dpi, "figure.figsize": [width, height]})
 
 
def setup_latex(update=None):
    matplotlib.use("pgf")
    pgf_config = {
        "font.family": "serif",
        "font.size": 24,
        "pgf.rcfonts": False,
        "text.usetex": True,
        # "hatch.linewidth": 5.0,
        "font.serif": "Times New Roman",
        "pgf.preamble": r"""\usepackage{fontspec} \setmainfont{Times New Roman}""",
    }
    if update:
        pgf_config.update(update)
    print(pgf_config)
    matplotlib.rcParams.update(pgf_config)
 
 
def sty(*fns):
    def f(t):
        _t = t
        for fn in fns:
            _t = fn(_t)
        return _t
 
    return f
 
 
def tt(t):
    return rf"\texttt{{{t}}}"
 
 
def bf(t):
    return rf"\textbf{{{t}}}"
 
 
def mathbf(t):
    return rf"\mathbf{{{t}}}"
 
 
def it(t):
    return rf"\textit{{{t}}}"
 
 
def bfit(t):
    return sty(bf, it)(t)
 
 
def font(size="normalsize"):
    def f(t):
        return rf"{{\{size} {t}}}"
 
    return f
 
 
def resizebox(width):
    def f(t):
        return rf"\resizebox{{{width}}}{{!}}{{{t}}}"
 
    return f
 
 
def family(face="rm"):
    def f(t):
        return rf"\text{face}{{{t}}}"
 
    return f

Use Case

from utils import *
from matplotlib import pyplot as plt
import numpy as np
 
if __name__ == "__main__":
    setup_dpi(plt, 120, 10, 8)
    setup_latex({"font.size": 16})
 
    fig, ax = plt.subplots()
 
    x = np.linspace(-5, 5, 500)
    y_sin = np.sin(x)
    y_cos = np.cos(x)
 
    ax.plot(x, y_sin, label=sty(bf, it)("Plot: $f(x) = \sin(x)$"))
    ax.plot(x, y_cos, label=family("tt")("Plot: $f(x) = \cos(x)$"))
    ax.plot(x, -x, label=family("sf")("Plot: $f(x) = -x$"))
 
    ax.set_xlabel("$x$")
    ax.set_ylabel("$y$")
    ax.legend(loc="upper right")
 
    plt.title(r"Testing: \LaTeX{} " + family("tt")("matplotlib") + " binding.")
    plt.savefig("test.png", transparent=False, facecolor="#EEEEEE")
 

test.png