Search code examples
stringmatplotlibfontsaxis-labels

Changing font inside curly brackets in matplotlib


I´m trying to change the font in my plot to Times New Roman but for some reason, the font of the exponent in my x-axis label doesn´t change.

I have set the global parameters as follows:

plt.rcParams["font.family"] = "Times New Roman"

Which works fine except for the part inside the curly brackets.

plt.xlabel("Stromdichte A cm$^{-2 test}$", fontsize=40)

the x-axis label


Solution

  • plt.rcParams["font.family"] = "Times New Roman" will not apply for your text inside mathtext formatting (i.e., r"$...$"). Instead it should be modified using plt.rcParams["mathtext.fontset"] = "custom" while simultaneously redefining how you want to customize the font which is changing to Times New Roman in this case:

    plt.rcParams["mathtext.fontset"] = "custom"
    plt.rcParams["mathtext.rm"] = "Times New Roman"  
    plt.rcParams["mathtext.it"] = "Times New Roman"  # italic
    plt.rcParams["mathtext.bf"] = "Times New Roman"  # bold