FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

[Bug]: Numbers in words not italic · Issue #29253 · matplotlib/matplotlib · GitHub

Repository navigation

[Bug]: Numbers in words not italic #29253

Closed

Description

Bug summary

Y labels in plots cannot be displayed in italic if the label contains numbers. While the letters will be italic, the numbers will stay in normal font.

Code for reproduction

mpl.rcParams['font.family'] = 'Arial'

bars = sns.barplot(
    x='Sample Name',
    y='delta',
    data=renamed,
    palette=custom_palette,
    alpha=1,
    edgecolor='grey',
    errorbar='se',
    errcolor='black',
    capsize=0.05,
    errwidth=1
)


sns.stripplot(
    x='Sample Name',
    y='delta',
    data=renamed,
    palette=custom_palette,
    edgecolor='white',
    linewidth=1,
    alpha=1,
    size=8,
    legend=False,
    dodge=False,
    jitter=0.17
)

bars.spines['top'].set_visible(False)
bars.spines['right'].set_visible(False)
plt.xticks(rotation=45, ha='right')
plt.ylabel("${CYP11B2}$ mRNA (%)")
plt.xlabel("")
plt.suptitle("")

plt.show()

Actual outcome

Expected outcome

Additional information

No response

Operating system

Mac OS Apple M1 Ventura 13.4.1

Matplotlib Version

3.9.2

Matplotlib Backend

module://matplotlib_inline.backend_inline

Python version

3.11.3

Jupyter version

6.5.4

Installation

pip

Activity

  1. oscargus commented on Dec 7, 2024

    Member

    $ is not for using italic, it is for render text as equations. There characters are italic and numbers not.

  2. oscargus commented on Dec 7, 2024

    Member

    The seemingly correct way to do that is to instead write

    plt.ylabel(r"$\mathit{CYP11B2}$ mRNA (%)")
    

    However, if this works or not will depend on if the font you are using, determined by rcParams['mathtext.it'], has italic numbers or not.

    It may be that there is a bug here, but I have not really figured out if it depends on the font or if, for some reasons, digits are not rendered using the italic font, as the default font is not rendered correctly.

  3. john-zhang-uoft commented on Dec 7, 2024

    Hello, can I work on this if this really is a bug?

  4. Sanas-m commented on Dec 7, 2024

    Author

    plt.ylabel(r"$\mathit{CYP11B2}$ mRNA (%)")

    I already tried this $\mathit{CYP11B2}$, it doesn't work. I'm currently using Arial and can't change the font type, since it is required by the journal. CYP11B2 needs to be fully italic, this is the biological nomenclature for gene names.

  5. jklymak commented on Dec 7, 2024

    Member

    Why are you using mathtext?

  6. oscargus commented on Dec 8, 2024

    Member

    Why are you using mathtext?

    Is it possible to mix italic and upright fonts in a single label otherwise?

  7. Sanas-m commented on Dec 8, 2024

    Author
  8. rcomer commented on Dec 8, 2024

    Member

    It does seem like we aren't consistent with Latex here. If I do

    ax.set_ylabel(r'$\it{abc123}$', usetex=False)

    only the letters are in italics, whereas if I do

    ax.set_ylabel(r'$\it{abc123}$', usetex=True)

    both letters and numbers are in italics.

    @Sanas-m the first example above uses Matplotlib's mathtex whereas the second example (usetex=True) uses my locally installed Latex. This may be a workaround for you and you can set an rcParam to turn it on for all your text:
    https://matplotlib.org/stable/users/explain/text/usetex.html

  9. jklymak commented on Dec 8, 2024

    Member

    Why are you using mathtext?

    Is it possible to mix italic and upright fonts in a single label otherwise?

    Sorry, agree you need something tex-like if you want to mix italic and non-italics.

  10. anntzer commented on Dec 9, 2024

    Contributor

    This looks like a bug to me (matching tex's behavior seems reasonable). The code that forces numbers to be in roman is under UnicodeFonts._get_glyph (commenting out the section starting at if fontname == 'it' and uniindex < 0x10000 revert them to italics), but doing that would turn all digits to italics in math mode (whereas we want r"1\mathit{1}" to only have the second one in italics). I suspect(?) the issue is that at the parsing stage all the characters are forced to italics (more precisely, to rcParams["mathtext.default"] by Parser.non_math), but really that should not affect digits (and greek capital letters); then this info can be threaded all the way down rather than doing the switch in UnicodeFonts._get_glyph.

  11. Sanas-m commented on Dec 10, 2024

    Author

    It does seem like we aren't consistent with Latex here. If I do

    ax.set_ylabel(r'$\it{abc123}$', usetex=False)

    only the letters are in italics, whereas if I do

    ax.set_ylabel(r'$\it{abc123}$', usetex=True)

    both letters and numbers are in italics.

    @Sanas-m the first example above uses Matplotlib's mathtex whereas the second example (usetex=True) uses my locally installed Latex. This may be a workaround for you and you can set an rcParam to turn it on for all your text: https://matplotlib.org/stable/users/explain/text/usetex.html

    I tried this but then the fonts are mixed again

  12. NaotoKubota commented on Apr 15, 2025

    Same problem here. I would be grateful if someone could fix this.

  13. cmatKhan commented on Apr 28, 2025

    bump -- found this after struggling to correctly format gene symbols.

    Edit -- this ended up working for me (with a good deal of help from chatGPT):

    On ubuntu 22.04, I installed the following

    sudo apt install texlive-latex-recommended texlive-fonts-recommended texlive-latex-extra cm-super dvipng

    and then the following matplotlib settings:

    import matplotlib as mpl
    
    mpl.rcParams.update({
        "text.usetex": True,
        "font.family": "sans-serif", 
        "font.sans-serif": ["cmbright"],
        "text.color": "black",
        "axes.labelcolor": "black",
        "xtick.color": "black",
        "ytick.color": "black", 
    })

    that made this work:

    ax.set_ylabel(f"\\textit{{{pTF}}} perturbation response", fontsize=label_fontsize, usetex=True)

  14. llohse commented on Feb 7, 2026

    Contributor

    This appears to be a logic bug in _mathtext.py.

    The Parser class sets fontname to 'it' as soon as a math environment is entered.

    def non_math(self, toks: ParseResults) -> T.Any:
    s = toks[0].replace(r'\$', '$')
    symbols = [Char(c, self.get_state()) for c in s]
    hlist = Hlist(symbols)
    # We're going into math now, so set font to 'it'
    self.push_state()
    self.get_state().font = mpl.rcParams['mathtext.default']
    return [hlist]

    Later, when the actual glyph is requested for rendering, it will only italize actual non-greek letters:

    if fontname == 'it' and uniindex < 0x10000:
    char = chr(uniindex)
    if (unicodedata.category(char)[0] != "L"
    or unicodedata.name(char).startswith("GREEK CAPITAL")):
    new_fontname = 'rm'

    One way to fix this would be to

    • not italize math mode within the parser but track math/regular
    • italize within the Fonts class depending on math/regular mode
  15. llohse commented on Feb 10, 2026

    Contributor

    I have opened a PR #31121 to fix this, which is waiting for a review.

    The fix has two parts:

    1. Introduce normal as the default font in a math environment (can also be explicitly set by \mathnormal{...}) and reserve it for explicit italic (\mathit or \it). This replicates the behaviour of LaTeX.
    2. In the Font classes, set digits in italics or upright when the font is set to 'it' or 'normal', respectively. For cm (Computer Modern), add the text italic (cmti) font and use that for 'it' instead of math italic, same as LaTeX does.

    Note that LaTeX further distinguishes between the default and normal math environment, where normal uses oldstyle digits. Modern LaTeX with unicode-math breaks with this behaviour and treats them both the same. For that reason I do not think it is worth the extra complexity.

  16. added this to the v3.11.0 milestone on Mar 2, 2026
  17. moved this from Waiting for other PR to In Progress in Font and text overhaulon Mar 2, 2026
  18. QuLogic commented on Apr 10, 2026

    Member

    The text-overhaul branch is now merged to main.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions


    Back | FazBrowse Home | New Git URL