Matplotlib 3.5.1 pyplot import is slow

I’m using Matplotlib 3.5.1 with Python 3.10.1 on Linux. I have lately observed that the import time is noticeably very slow (~3.6s).

$ time python -c 'import matplotlib'       
python -c 'import matplotlib'  1.14s user 0.09s system 99% cpu 1.233 total
$ time python -c 'import matplotlib.pyplot' 
python -c 'import matplotlib.pyplot'  3.50s user 0.10s system 99% cpu 3.608 total

I have search for similar problem on the internet, and found python - Extremely slow import of matplotlib afm - Stack Overflow and the GitHub issue, #3655 (I’m a new user in this Discourse, and so can only post 2 links). But clearing ~/.cache/matplotlib has no effect.

I also tried matplotlib.font_manager._rebuild(), but it error-ed out with module 'matplotlib' has no attribute 'font_manager' (probably because this is an outdated API?).

I wonder if it because of something else?
Here is my importtime log: matplotlib 3.5.1 on Python 3.10.1 on Linux importtime log · GitHub
pyparsing.helpers, matplotlib.collections, matplotlib.patches seem to be significant.

matplotlib.font_mangaer is a sub-module so you will have to import it to access the attribute (which ironically to your problem is to try and speed up import!).

Further defer backend selection by tacaswell · Pull Request #22005 · matplotlib/matplotlib · GitHub might help by deferring importing a GUI framework until you actually need it, but that is only moving the import cost around.

If you do not actually need a GUI window, you can do

import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt

That is an interesting log (not quite sure how to read it as it shows a six import in Matplotlib someplace).

The other thing that can be done is sort out how much of the time is spent on importing external packages and then defering those imports until actually needed.

There is also a proposal to top level imports (like scikit-image did), but we actually use a fair amount of stuff directly in pyplot so I’m not 100% that would actually get a big improvement.