Ian
Ian

Reputation: 1716

Antialiased text rendering in matplotlib pgf backend

I have a question regarding the text rendering in the matplotlib pgf backend. I am using matplotlib to export .pdf files of my plots. In the section with the rcParameters I define that I want to use sans-serif and I want to use Helvetica as font. Therefore I disabled the option text.usetex. Here's a MWE:

import matplotlib as mpl
import os

mpl.use('pgf')

pgf_with_latex = {                     
    "pgf.texsystem": "pdflatex",       
    "text.usetex": False,                
    "font.family": "sans-serif",
    "font.sans-serif": "Helvetica",
    "pgf.preamble": [
        r"\usepackage[utf8x]{inputenc}",    
        r"\usepackage[T1]{fontenc}",       
        r"\usepackage{textcomp}",
        r"\usepackage{sfmath}",
    ]
    }
mpl.rcParams.update(pgf_with_latex)

import matplotlib.pyplot as plt


def newfig():
    plt.clf()
    fig = plt.figure()
    ax = fig.add_subplot(111)
    return fig, ax

fig, ax = newfig()
ax.set_xlabel("Some x-label text")
ax.text(0.3, 0.5, r"This text is not antialiased! 0123456789", transform=ax.transAxes, fontsize=8)
plt.savefig(os.getcwd() + "/test.pdf")

The result is, that the tick labels and the text are rendered in Computer Modern (-> LaTeX) instead of Helvetica and they are not rendered as vector graphic and look pixelated. Now, when I enable text.usetex the tick labels become vector graphics (I can zoom in without seeing pixels), but the text doesn't!

What do I have to do to get everything (tick labels, axis labels, legend, text etc.) to be vectorized Helvetica? Is that even possible? If not, how do I get text, legend, etc. to be vectorized in Computer Modern like the tick labels?

Edit: Python 3.4.4, matplotlib 1.5.2

here are the smooth tick labels vs. the ragged xlabel Zoom

Another edit: If I save my file as .eps instead of .pdf and enable usextex I get wonderfully vectorized fonts, but the tick labels are in serif font :<

Upvotes: 1

Views: 841

Answers (1)

Ian
Ian

Reputation: 1716

I think I finally found my answer after many attempts. I found it in this SO post.

I merely added this to the preamble:

r'\usepackage{helvet}',    # set the normal font here
r'\usepackage{sansmath}',  # load up the sansmath so that math -> helvet
r'\sansmath'               # <- tricky! -- gotta actually tell tex to use!

and set "text.usetex": False". Now it finally uses Helvetica everywhere and it is vectorized everywhere.. well, except for axes with logarithmic scaling. There I have to manually set axis labels by using ax.set_yticklabels([1, 2, 3, 4]).

Upvotes: 0

Related Questions