Search code examples
matplotliblatexjupyter-labeps

Saving Matplotlib graphs with LaTeX fonts as eps


I am trying to make publication-quality in Jupyter-lab using matplotlib and LaTeX fonts. I have created a simple document following instructions found here: https://matplotlib.org/stable/tutorials/text/usetex.html

The graph was created with beautiful fonts; however, saved eps file was blank. The same graph could be successfully saved as png, but it looked blurry when import to LaTeX even using dpi=2400 option. Eps files WITHOUT LaTeX fonts were sharp as a razor when imported into LaTeX file.

Suggestions? Workarounds?

Thanks, Radovan

PS. One workaround I found was using gnuplot and cairolatex terminal ... resulting *.tex file could be compiled with Pdflatex with excellent results. But that a different story :-).


Solution

  • I gave this another try. At the end, it did work! Here is the code:

    import numpy as np
    import matplotlib.pyplot as plt
    
    ## reset defaults
    plt.rcdefaults()
    
    ## Set up LaTeX fonts
    plt.rcParams.update({
        "text.usetex": True,
        "font.family": "serif",
        "font.serif": ["Computer Modern Roman"],
        "font.size": 14,
        })
    
    ## Data for plotting
    t = np.arange(0.0, 2.0, 0.01)
    s = 1 + np.sin(2 * np.pi * t)
    
    fig, ax = plt.subplots(figsize=(4.5,3))
    
    ax.plot(t, s, linewidth=3)
    
    ax.set(xlabel=r'time $\tau_p$ [$\mu$s]', ylabel=r'voltage (mV)')
    ax.set(title=r'$ E = m c^2 $')
    
    fig.savefig("test600.png", format="png", dpi=600, bbox_inches="tight")
    fig.savefig("test1200t.eps", format="eps", dpi=1200, bbox_inches="tight", transparent=True)
    fig.savefig("test1200t.pdf", format="pdf", dpi=1200, bbox_inches="tight", transparent=True)
    
    plt.show()
    

    I am not sure what was wrong before. I did different font declaration this time around.

    Cheers, Radovan