python - Trying to save mpl figure as pdf yields style flag error - Stack Overflow

admin2025-05-01  1

I am trying to generate and save PDFs of Matplotlib figures using the Inter font.

I installed Inter with:

brew install font-inter

An example:

import matplotlib.pyplot as plt
import matplotlib.font_manager as fm

available_fonts = [f.name for f in fm.fontManager.ttflist]
if 'Inter' in available_fonts:
    plt.rcParams['font.family'] = 'Inter'
else:
    print("Inter font is not available. Please ensure it is installed.")

plt.rcParams['pdf.fonttype'] = 42 # for compatibility

# generate the figure
fig, ax = plt.subplots()
ax.plot([0, 1], [0, 1])
ax.set_title("Example Plot with Inter Font")
plt.show()

# save the figure
fig.savefig("example_plot.pdf", format='pdf')

I have no issues with this except on macOS, where I get the following error about the font's style flags:

$ /Users/atom/hemanpro/HeMan/.venv/bin/python /Users/atom/hemanpro/HeMan/misc_tools/addfont.py                                                                                                                                                   [13:58:58]
2025-01-02 13:59:29.100 Python[59655:1610342] +[IMKClient subclass]: chose IMKClient_Modern
2025-01-02 13:59:29.100 Python[59655:1610342] +[IMKInputSession subclass]: chose IMKInputSession_Modern
Traceback (most recent call last):
  File "/Users/atom/hemanpro/HeMan/misc_tools/addfont.py", line 25, in <module>
    fig.savefig("example_plot.pdf", format='pdf')
    ~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/atom/hemanpro/HeMan/.venv/lib/python3.13/site-packages/matplotlib/figure.py", line 3490, in savefig
    self.canvas.print_figure(fname, **kwargs)
    ~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
  File "/Users/atom/hemanpro/HeMan/.venv/lib/python3.13/site-packages/matplotlib/backend_bases.py", line 2184, in print_figure
    result = print_method(
        filename,
    ...<3 lines>...
        bbox_inches_restore=_bbox_inches_restore,
        **kwargs)
  File "/Users/atom/hemanpro/HeMan/.venv/lib/python3.13/site-packages/matplotlib/backend_bases.py", line 2040, in <lambda>
    print_method = functools.wraps(meth)(lambda *args, **kwargs: meth(
                                                                 ~~~~^
        *args, **{k: v for k, v in kwargs.items() if k not in skip}))
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/atom/hemanpro/HeMan/.venv/lib/python3.13/site-packages/matplotlib/backends/backend_pdf.py", line 2789, in print_pdf
    file.finalize()
    ~~~~~~~~~~~~~^^
  File "/Users/atom/hemanpro/HeMan/.venv/lib/python3.13/site-packages/matplotlib/backends/backend_pdf.py", line 827, in finalize
    self.writeFonts()
    ~~~~~~~~~~~~~~~^^
  File "/Users/atom/hemanpro/HeMan/.venv/lib/python3.13/site-packages/matplotlib/backends/backend_pdf.py", line 973, in writeFonts
    fonts[Fx] = self.embedTTF(filename, chars)
                ~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
  File "/Users/atom/hemanpro/HeMan/.venv/lib/python3.13/site-packages/matplotlib/backends/backend_pdf.py", line 1416, in embedTTF
    sf = font.style_flags
         ^^^^^^^^^^^^^^^^
  File "/opt/homebrew/Cellar/[email protected]/3.13.1/Frameworks/Python.framework/Versions/3.13/lib/python3.13/enum.py", line 726, in __call__
    return cls.__new__(cls, value)
           ~~~~~~~~~~~^^^^^^^^^^^^
  File "/opt/homebrew/Cellar/[email protected]/3.13.1/Frameworks/Python.framework/Versions/3.13/lib/python3.13/enum.py", line 1207, in __new__
    raise exc
  File "/opt/homebrew/Cellar/[email protected]/3.13.1/Frameworks/Python.framework/Versions/3.13/lib/python3.13/enum.py", line 1184, in __new__
    result = cls._missing_(value)
  File "/opt/homebrew/Cellar/[email protected]/3.13.1/Frameworks/Python.framework/Versions/3.13/lib/python3.13/enum.py", line 1480, in _missing_
    raise ValueError(
    ...<2 lines>...
                ))
ValueError: <flag 'StyleFlags'> invalid value 589824
    given 0b0 10010000000000000000
  allowed 0b0 00000000000000000011
.venvFAIL

To be clear, the figure is displaying the font correctly:

I've tried switching backends before saving the figure to Cairo, but that still gives the same error:

matplotlib.use("macosx") (at the top)
...
plt.show()
plt.switch_backend("Cairo")
fig.savefig("example_plot.pdf", format='pdf')

I've also tried QtAgg via PySide6.

Any ideas on what's going wrong and how to resolve it? Thanks!

转载请注明原文地址:http://anycun.com/QandA/1746093710a91575.html