pythonmatplotlibfontslatextext-formatting

Matplotlib LaTeX text not respecting font family


I am trying to display a LaTeX-style equation in a Matplotlib plot using a custom font (Algerian). I want both the equation and the surrounding text to use the same upright (non-italic) font. Using the LaTeX package is acceptable, so XeLaTeX or LuaLaTeX can be used.

Here's a minimal example:

import matplotlib.pyplot as plt

plt.rcParams['font.family'] = 'Algerian'
plt.rcParams['font.weight'] = 'bold'
plt.rcParams['font.size'] = 10


plt.figure()
plt.text(0.1, 0.5, r"$a*ln(x)*x^2+2$", fontfamily='Algerian')
plt.show()

The problem is that while normal text respects the font settings, the math text does not inherit the Algerian font and also defaults to italic.

I understand that Matplotlib math text always uses the math font (Computer Modern by default). In my real application, the expressions are much more complex, which makes switching everything to plain text or using Unicode very tricky.

Is there a way to have both the custom upright font and proper LaTeX formatting in Matplotlib?


Solution

  • To first answer your question you need to understand the difference between a font-family and a actual font: A font family is a collection of related fonts, like sans-serif, and a font is a specific member of that family, such as Helvetica, Arial, Calibri and the font you are trying to use, Algerian. The font family is the overall design, while the font is the specific variation in weight, style, and size within that design.

    Furthermore I spotted this errors in your code:

    With this corrections I was able to correct the code to get what I hope is the inted output (didn't understand perfectly the LaTeX issue):

    import matplotlib.pyplot as plt
    
    plt.rcParams['font.sans-serif'] = ['Algerian']
    plt.rcParams['font.weight'] = 'bold'
    plt.rcParams['font.size'] = 10
    
    
    plt.figure()
    plt.text(0.1, 0.5, r"$a*ln(x)*x^2+2$", math_fontfamily='custom')
    plt.show()
    

    I found that it needs to be told to use a custom family font to enable a esternal font to be used, the other accepted values are:

    'dejavusans', 'dejavuserif', 'cm', 'stix', 'stixsans', 'custom'
    

    this gives in output:https://i.sstatic.net/L76gmQdr.png

    which I understand is the one you need.

    Some notes:

    To further understand how to customise matplotlib refer to the text, label and annotation docs.