Skip to content

[Bug]: Font fallback bugs #32063

In review
In review

Description

@dragoneptech

Bug summary

If the global font size is set with plt.rcParams["font.size"] and the size value >12, the Chinese charaters will show, else the Chinese characteres will disappear.

Code for reproduction

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["font.family"] = ["Times New Roman", "SimSun"]
plt.rcParams["font.serif"] = ["Times New Roman", "SimSun"]
plt.rcParams["font.sans-serif"] = ["Times New Roman", "SimSun", "Arial", "SimHei"]

plt.rcParams["mathtext.fontset"] = "custom"
plt.rcParams["axes.unicode_minus"] = False
plt.rcParams["font.size"] = 13  # If font size <= 12, the Chinese characters will not show.

x = np.array([1, 2, 3, 4, 5])
y = np.array([1, 4, 9, 16, 25])

plt.plot(x, y)
plt.xlabel('X-axis / X 轴')
plt.ylabel('Y-axis / Y 轴')
plt.title('Font Style Example / 字体样式示例')
plt.show()

Actual outcome

"# plt.rcParams["font.size"] = 13"

Image

"plt.rcParams["font.size"] = 13"
Image

Expected outcome

Font fallback can work correctly. The text containing Chinese characters and Non-Chinese characters can be diplayed with SimSun font and Time New Roman font, respectively.

Additional information

Font fallback is incompatible for SimSun and Times New Roman fonts.

Operating system

Windows

Matplotlib Version

3.11.0

Matplotlib Backend

tkagg

Python version

3.14.6

Jupyter version

No response

Installation

uv

Activity

  1. mohit-sharma-001 commented on Jul 19, 2026

    @mohit-sharma-001

    Hi @dragoneptech , thank you for reporting this issue. I am interested in investigating this font fallback behavior. I will attempt to reproduce it locally to understand why the Chinese characters disappear when the font size is 12 or smaller. I’ll keep you updated on my findings.

  2. mohit-sharma-001 commented on Jul 19, 2026

    @mohit-sharma-001

    Hi @dragoneptech , thank you for reporting this issue. I am interested in investigating this font fallback behavior. I will attempt to reproduce it locally to understand why the Chinese characters disappear when the font size is 12 or smaller. I’ll keep you updated on my findings.

    I have successfully reproduced this bug locally.

    I enabled debug logging for matplotlib.font_manager and observed that both Times New Roman and SimSun are successfully matched with a perfect score (0.05). This indicates the font manager is working correctly.

    Hypothesis: The issue seems to be in the FreeType rendering phase. SimSun contains embedded bitmap strikes for smaller sizes (<= 12). It appears that the font fallback mechanism in Matplotlib fails when trying to render a mix of vector glyphs (Times New Roman) and embedded bitmap glyphs (SimSun at small sizes), causing the fallback text to disappear completely. When size >12, SimSun uses vector outlines, and the fallback works fine.

    I am now looking into how ft2font and the backend handle this mixed rendering.

  3. mohit-sharma-001 commented on Jul 19, 2026

    @mohit-sharma-001

    Hii @dragoneptech
    I have submitted a fix for this issue in PR #32072. The fix involves forcing the FT_LOAD_NO_BITMAP flag in FT2Font::load_glyph to ensure vector outlines are used for small font sizes. Looking forward to your feedback!

  4. sahil-11116 commented on Jul 23, 2026

    @sahil-11116

    Hi I'm a new contributor to Matplotlib and would like to take this documentation issue. I'd appreciate any guidance or suggestions on where to begin.

  5. QuLogic commented on Jul 23, 2026

    @QuLogic
    Member

    @sahil-11116 There is an existing PR (linked above) by @mohit-sharma-001 and we tend to focus on the first one, unless it goes stale and orphaned.

  6. mohit-sharma-001 commented on Jul 24, 2026

    @mohit-sharma-001

    @QuLogic Thanks for your observation
    If there needs to be an change please feel free to contact me

  7. scottshambaugh commented on Jul 25, 2026

    @scottshambaugh
    Contributor

    I looked into this and found the underlying issue.

    Relevant code:

    for font, size, glyph_index, slant, extend, dx, dy in glyphs: # dy is upwards.
    font.set_size(size, self.dpi)
    font._set_transform(
    (0x10000 * np.array([[cos, -sin], [sin, cos]])
    @ [[extend, extend * slant], [0, 1]]).round().astype(int),
    [round(0x40 * (x + dx * cos - dy * sin)),
    # FreeType's y is upwards.
    round(0x40 * (self.height - y + dx * sin + dy * cos))]
    )
    bitmap = font._render_glyph(
    glyph_index, load_flags,
    RenderMode.NORMAL if gc.get_antialiased() else RenderMode.MONO)
    buffer = bitmap.buffer
    if not gc.get_antialiased():
    buffer *= 0xff
    # draw_text_image's y is downwards & the bitmap bottom side.
    self._renderer.draw_text_image(
    buffer,
    bitmap.left, int(self.height) - bitmap.top + buffer.shape[0],
    0, gc)

    There are actually two bugs here:

    1. FreeType returns embedded bitmap glyphs as 0 or 1 per pixel, but Agg needs an alpha of 0 to 255. RendererAgg._draw_text_glyphs_and_boxes incorrectly only scales when antialiasing is off, so with antialiasing on we draw these glyphs at a near-invisible alpha of 1 instead of 255.

    2. FT_Load_Glyph only applies its transform to outlines, and the offset and rotation set by _set_transform are silently dropped for a bitmap, so bitmaps render at the origin (wrong location).

    Suggested fix for both: Add an attribute to _PositionedBitmap that says whether the glyph came from an embedded bitmap. Based on that, _draw_text_glyphs_and_boxes can scale the alpha value and add in the offset it already computed, since FreeType only applies that to outlines right now.

    However! This still does not allow for rotating or slanting the bitmaps, and resampling those would be quite a bit more scope. So FT_LOAD_NO_BITMAP should still be set true (as in #32072) so that we prefer outlines - per the freetype source this flag is ignored for bitmap-only fonts.

    For tests this may require defining a custom bitmap-only font as a test fixture, since I can't find any of the packaged fonts that are bitmap only (it's uncommon, which is why this went unnoticed so long). SimSun is windows only and so can't be relied on for testing.

    Demo plot that claude threw together:

    Image
  8. spalato commented on Nov 18, 2026

    @spalato

    This isn't limited to font fallback or CJK fonts. Any font with embedded bitmap strikes renders blank text at those pixel sizes when it's the primary font. Calibri (default on Windows) is a common example: its strikes are at 12, 13, 15, 16, 17 and 19 ppem, and every one of those sizes renders blank in Agg.

    In practice, 9 pt text at dpi=150 (18.75 → 19 px) disappears entirely: tick labels, axis labels and the legend. Mathtext still renders. Saving at dpi=300 hides the problem, so the inline/Jupyter view is broken while the exported figure looks fine.

    import io
    import numpy as np
    import matplotlib
    matplotlib.use("agg")
    import matplotlib.pyplot as plt
    
    plt.rcParams["font.family"] = "Calibri"
    
    blank = []
    for px in range(8, 30):
        fig = plt.figure(figsize=(1, 0.3), dpi=72)
        fig.text(0.05, 0.3, "0.2 exp", fontsize=px)  # at dpi=72, 1 pt = 1 px
        buf = io.BytesIO()
        fig.savefig(buf, format="rgba", dpi=72)
        plt.close(fig)
        img = np.frombuffer(buf.getvalue(), np.uint8).reshape(-1, 4)
        if (img[:, :3].mean(axis=1) < 128).sum() == 0:
            blank.append(px)
    print(matplotlib.__version__, "blank at ppem:", blank)

    output:

    3.10.9 blank at ppem: []
    3.11.1 blank at ppem: [12, 13, 15, 16, 17, 19]
    3.11.2 blank at ppem: [12, 13, 15, 16, 17, 19]
    

    Windows 11, Python 3.14, FreeType 2.14.3 (bundled), Agg backend. Changing text.hinting makes no difference. This regressed in 3.11.0, and the analysis above (bitmap glyphs drawn at alpha 1, plus FT_LOAD_NO_BITMAP as the fix) fits this case.

    Workarounds: downgrade to matplotlib<3.11, use different resolutions (ex: 144 instead of 150).

  9. added this to the v3.11.3 milestone on Nov 21, 2026
  10. added 3 commits that reference this issue on Dec 4, 2026
    d9f15c0
    f48750d
    cc0e539
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

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions