Matplotlib cannot find basic fonts
Asked Answered
H

19

102

I am using matplotlib version 2.0.0 on Python 3 in a miniconda virtual environment. I am working on a unix scientific computing cluster where I don't have root privileges. I am generally executing python code through an ipython notebook. If I do a basic command such as:

import matplotlib.pyplot as plt
plt.scatter([1,5], [1,5])

I get an error message:

path_to_miniconda/miniconda3/envs/conda34/lib/python3.4/site-
packages/matplotlib/font_manager.py:1297: UserWarning: findfont: Font family
['sans-serif'] not found. Falling back to DejaVu Sans
(prop.get_family(), self.defaultFamily[fontext]))

I would like to be able to use a Times New Roman font but even after deleting the Font cache file (fontList.py3k.cache) which I find from here:

import matplotlib as mpl
fm = mpl.font_manager
fm.get_cachedir()

The commands:

mpl.rcParams['font.family'] = ['serif']
mpl.rcParams['font.serif'] = ['Times New Roman']

have no effect, I get the same error as above. The true type fonts directory:

path_to_miniconda/miniconda3/envs/conda34/lib/python3.4/site-packages/matplotlib/mpl-data/fonts/ttf/

only has 40 fonts in it of the type: DejaVuSerif,DejaVuSans,STIX,cmb, cmt, cmy

Any idea what could be going on and how I can add additional fonts? Thanks!

Horal answered 7/2, 2017 at 18:16 Comment(3)
I had the same problem. Thank you for your tip fm.get_cachedir(), I was erasing the wrong cache and now it works! Thank you :)Gilbertina
I have the same error, but my figures end up in serif (using latex).Arlindaarline
Try reinstall, matplotlib released version 3 in 2018Parricide
I
127

To get it to work, I had to combine the two current top answers. Here's what worked for me:

$ sudo apt install msttcorefonts -qq
$ rm ~/.cache/matplotlib -rf
Ilonailonka answered 17/4, 2018 at 17:21 Comment(6)
can confirm, this also worked for me on Ubuntu 16.04.Placebo
Confirmed on Debian Bookworm, matplotlib 3.3.4Sukhum
Confirmed on WSL, Ubuntu 20.04. Thanks!Indemnify
Works on 18.04 and 22.04 too. Thanks!Grof
It doesn't work in my case (Mac user). I get The operation couldn’t be completed. Unable to locate a Java Runtime that supports apt. Please visit http://www.java.com for information on installing Java. I install what it but nothing changes. Any suggestion? Thanks.Rumen
You may need to restart your IDE.Posting
C
41

I had this exact same problem on a Vagrant VM running Ubuntu Xenial 64-bit. No matter how many fonts I had already installed, matplotlib was having a problem with the "system" font name "sans-serif". I fixed it by:

  • Stopping Jupyter
  • Installing font-manager: sudo apt install font-manager
  • Cleaning the matplotlib cache directory: rm ~/.cache/matplotlib -fr
  • Restarting Jupyter.

No more error messages about sans-serif.

Convivial answered 21/3, 2017 at 19:39 Comment(3)
Note that you can get the cache directory (which varies by OS) with: matplotlib.font_manager.get_cachedir()Balinese
fontmanager.get_cachedir() didn't exist for me (on OSX), but fontmanager._fmcache did, and deleting the json file it points to, solved the issue.Ovum
I could use matplotlib.get_cachedir() on Windows. Deleting the fontlist-v330.json file and restarting the kernel solved the issue for me!Humperdinck
C
25

This work for me::

$ sudo apt-get install msttcorefonts -qq
Chaisson answered 16/3, 2017 at 17:56 Comment(4)
Docker users will need to accept the license agreement automatically: RUN echo ttf-mscorefonts-installer msttcorefonts/accepted-mscorefonts-eula select true | debconf-set-selections RUN apt-get install -y ttf-mscorefonts-installerErikerika
This worked after I deleted the matplotlib font cache file described in the question.Heartthrob
You need to clear the cache: rm ~/.cache/matplotlib -frWilliamsen
E: Package 'ttf-mscorefonts-installer' has no installation candidateTaxicab
A
19

I had this problem with anaconda env (it could be useful in other related situations as well). For example, for base env, I have checked the following directory: /home/***/anaconda3/pkgs/matplotlib-base-3.1.3-py37hef1b27d_0/lib/python3.7/site-packages/matplotlib/mpl-data/fonts/ttf/

and noticed that I have DejaVuSerif.ttf intalled there, so instead of using plt.rcParams['font.family'] = 'Serif' I used plt.rcParams['font.family'] = 'DeJavu Serif' ( there is a space between "DeJavu and serif" ). i worked for me.

import matplotlib.pyplot as plt
plt.rcParams['font.family'] = 'DeJavu Serif'
plt.rcParams['font.serif'] = ['Times New Roman']
Audacious answered 3/3, 2021 at 18:0 Comment(1)
After many many hours this is the only solution that worked for me. Thank you!Arak
K
18

A solution for Windows users, when confronted with the warning:

UserWarning: findfont: Font family ['serif'] not found. Falling back to DejaVu Sans
(prop.get_family(), self.defaultFamily[fontext]))
  1. Delete the fonts located in matplotlib's cache.
    Cache's location: import matplotlib as mpl; print(mpl.font_manager.get_cachedir())

  2. Find matplotlib's font directory. The path might be similar to
    C:\Miniconda3\pkgs\matplotlib-2.2.2-py36_1\Lib\site-packages\matplotlib\mpl-data\fonts\ttf

  3. Copy necessary fonts like Computer Modern to this directory.

The warning may persist, but your plots' font should change appropriately.

Kimberlite answered 3/4, 2018 at 16:27 Comment(4)
Worked exactly as you described for me on windows (inc. persisting warning)Overly
The solution did not work for me (module 'matplotlib' has no attribute 'font_manager'), but instead I found that print(matplotlib.font_manager.findfont('the font i want')) shows me where the font (or the default font if the font I want is not found) is located.Pauperize
Just in case someone gets this error: 'module' object has no attribute 'font_manager'. I solved it by first importing the font_manager like this: import matplotlib.font_manager as fm and then: print(fm.get_cachedir())Ammieammine
The command that works for me is import matplotlib and matplotlib.get_cachedir() directly without the font_managerDorey
B
11

There is a conda package for it[1]. So, you don't really need sudo to fix this!

conda install -c conda-forge -y mscorefonts

UPDATE: the below functionality is broken in recent matplotlib (no longer works on v3.4.3)

Also, if you dont want to restart jupyter, you can force rebuild matplotlib font cache

import matplotlib
matplotlib.font_manager._rebuild()

[1] - https://anaconda.org/conda-forge/mscorefonts

Boogeyman answered 30/6, 2020 at 5:54 Comment(5)
This is clean and worked first time for my Windows installation. Thanks :-)Disario
Also did not have to restart jupyter with rm ~/.cache/matplotlib -rf :)Pteropod
+1. Thanks a lot! I did not remove any cache or anything else. Just import matplotlib matplotlib.font_manager._rebuild() solved my problem.Edrick
Not sure what version this is for, but for Python 3.8.10 with matplotlib 3.5.0, AttributeError: module 'matplotlib.font_manager' has no attribute '_rebuild'Shabbir
module 'matplotlib.font_manager' has no attribute '_rebuild'Merchant
T
8

I actually solved by

import matplotlib.font_manager

Towboat answered 2/2, 2020 at 17:2 Comment(1)
AttributeError: module 'matplotlib.font_manager' has no attribute '_rebuildMerchant
J
5

It took me many hours to finally figure out that I needed to update matplotlib.

My original version of 3.0.3 (which came with my jupyter-datascience docker image) would give me this error, but updating to 3.1.1 fixed it.

In the end, my docker script:

RUN pip install matplotlib==3.1.1
COPY fonts /usr/share/fonts/truetype/
RUN fc-cache -fv
RUN rm /home/jovyan/.cache/matplotlib -rf

is what did it for me.

Jowett answered 10/10, 2019 at 14:32 Comment(1)
It works! You save me an hour! My original version is 3.0.2, after update to 3.1.1, it no longer pop Font family ... not found error message.Bedizen
F
3

Just removing the matplotlib cache and restarting the jupyter instance solved the issue for me:

Removing cache using: rm ~/.cache/matplotlib -rf

Featureless answered 3/11, 2022 at 13:58 Comment(0)
C
1

I was facing a similar issue in a Cloud Datalab docker image running on a gcloud VM. Executing the following fixed the issue for me:

$ sudo apt install msttcorefonts -qq
$ rm ~/.cache/matplotlib -rf

Here is instructions on how to get to the docker image running on the gcloud VM containing the Datalab instance just in case.

Calicut answered 8/10, 2018 at 19:7 Comment(0)
P
1

try all the methods above, not work for me.

my way to solve this is a little dirrent cause I'm using conda on ubuntu server running jupyter

locate -b '\mpl-data'

find a folder

/usr/share/matplotlib/mpl-data

then I add the simhei fonts into the font folder in mpl-data . then remove matplotlib fonts cache

rm -rf ~/.cache/matplotlib

restart jupyter notebook, and it works.

Pneuma answered 6/12, 2018 at 5:52 Comment(0)
B
1

I am in macOS with jupyter notebook, I solved with the following, first close your jupyter notebook. Then find out the font path by doing the following in Python

import matplotlib
print(matplotlib.matplotlib_fname())

it prints /Users/zyy/anaconda2/lib/python2.7/site-packages/matplotlib/mpl-data/matplotlibrc for me, notice matplotlibrc is a file, not a directory.

Then download font SimHei, and copy it to the directory fonts/ttf under the mpl-data/ directory above.

Delete directory ~/.cache/matplotlib and restart your jupyter notebook, everything should be good.

Barstow answered 6/10, 2019 at 1:39 Comment(0)
P
1

None of the above worked for me. I had to combine the provided solutions.

I run Jupyter from PyCharm in Windows 10. Here is my workaround. Before doing these steps, import the font manager via import matplotlib.font_manager:

  1. Find font directory => matplotlib.font_manager.findSystemFonts(fontpaths=None, fontext='ttf')
  2. Put your font file (ttf. file) to that directory.
  3. Find font config file: matplotlib.matplotlib_fname()
  4. Edit to set font type: pdf.fonttype: 42 # Output Type 3 (Type3) or Type 42 (TrueType)
  5. Run PyCharm.
  6. After you start kernel, cache files will be generated. Clean \matplotlib\__pycache__ folder.
  7. Set the font you want to use via:
plt.rcParams['font.family'] = 'serif'
plt.rcParams['font.serif'] = ['Lin Libertine']
  1. Run the code to generate plots.

If you restart your kernel, if will generate cache files, hence you need to remove them again.

Preconcerted answered 4/3, 2022 at 19:4 Comment(0)
O
0

For windows users

  1. Just go to the cache dir of matplotlib by using

import matplotlib as mpl

print(mpl.font_manager.get_cachedir())

  1. Clear the entire cache file

  2. Lastly again import matplotlib

Hopefully u will also find it helpful as it worked for me

P:S - If you wish you can restart your jupyter/ide (optional) after this

Oxidimetry answered 6/4, 2021 at 11:11 Comment(1)
Hi, First I found out the location using .getcachedir() function,after that I deleted everything from that file including the empty cache file and the fonts generated.After that I started my Jupiter notebook again and importer matplotlib and seaborn,you will find that once you import again the fonts are automatically regenerated. That would hopefully solve your problem as it solved mineOxidimetry
T
0

My situation is that I have JupyterHub running in Docker and I need to use matplotlib to plot and display some Chinese characters as titles.

Here's how I install new fonts and get new fonts worked( No need to restart the Jupyter container ):

Docker Image version:

  • Ubuntu 18.04.3 LTS
  • Python 3.7.6
  • matplotlib.__version__ : 3.1.2

All operations are executed inside the container.

  1. download the fonts to /.../python3.7/site-packages/matplotlib/mpl-data/fonts/ttf

  2. rebuild the font cache in a notebook. ~/.cache/matplotlib/ (AttributeError: module 'matplotlib' has no attribute 'font_manager').

import matplotlib.font_manager
matplotlib.font_manager._rebuild()

the font cache is per-user base(/home/{username}/.cache/matplotlib/), so other people might need to rebuild the cache too.

  1. use the new font. e.g.
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = ['SimSun']

You might need to restart the notebook/kernel in step 2 and 3.

Notes:

  • I tried sudo apt install msttcorefonts -qq but I don't think that works. Neither do I know what has been installed by that package. apt-file list msttcorefonts returns nothing.
    Why apt-file list msttcorefonts returns nothing?

  • There is a configuration file /.../python3.7/site-packages/matplotlib/mpl-data/matplotlibrc on which one can add font.sans-serif fonts. But without modifying it, the new fonts also work.

Tenterhook answered 13/9, 2022 at 11:41 Comment(1)
AttributeError: module 'matplotlib.font_manager' has no attribute '_rebuildMerchant
T
0

For me, using Pycharm on Windows 10, none of the above completely solve my problem.

I have placed Roboto font at folder (replace with your Python package folder): C:\Python\Python310\Lib\site-packages\matplotlib\mpl-data\fonts\ttf\

The last thing I tried that made me successful is to remove the file fontlist-v330.json at folder (replace C:\Users\User\ with you own folder): C:\Users\User\.matplotlib\
In fact, i tried the above because I can't find a cache folder C:\Users\User.cache.matplotlib\ as mentioned in this thread.

Interestingly, if you find the following json within the file "fontlist-v330.json" that means you can start using the font (in my case Roboto). There is also tricky part here that I don't know how to resolve yet. I tried to place both Arial and Arial Narrow font into the folder, but both of them appeared to use "Arial" as their name in this json file. So I have remove the font files for "Arial" and keep those "Arial Narrow" files, so I can use "Arial Narrow" font.

 {
      "fname": "fonts\\ttf\\Roboto-Regular.ttf",
      "name": "Roboto",
      "style": "normal",
      "variant": "normal",
      "weight": 400,
      "stretch": "normal",
      "size": "scalable",
      "__class__": "FontEntry"
    },

Then restart Pycharm which calls the function to set rc parameter:

pyplot.rcParams['font.family'] = 'serif'
pyplot.rcParams['font.serif']=['Roboto']

Then it will not complain being not able to get font file.

Tame answered 8/10, 2022 at 3:7 Comment(0)
N
0

Neither one of the solutions worked for me. I had to combine the solutions as well!

Just adding the following failed during Docker build.

RUN apt install -y msttcorefonts -qq:

Resulting in the following error message:

> #22 11.26 E: Failed to fetch http://archive.ubuntu.com/ubuntu/pool/main/u/ubuntu-advantage-tools/ubuntu-advantage-tools_27.13.6%7e22.04.1_amd64.deb 404  Not Found [IP: 91.189.91.38 80]
#22 11.26 E: Unable to fetch some archives, maybe run apt-get update or try with --fix-missing?
#22 11.26 0 upgraded, 36 newly installed, 0 to remove and 17 not upgraded.
#22 11.26 Need to get 8167 kB of archives.
#22 11.26 After this operation, 37.6 MB of additional disk space will be used.

But making sure to update and fix missing and broken packages, combined with @Matt Kleinsmith's comment for Docker users:

RUN apt update --fix-missing
RUN echo ttf-mscorefonts-installer msttcorefonts/accepted-mscorefonts-eula select true | debconf-set-selections
RUN apt-get install -y ttf-mscorefonts-installer

With the lines above, I was able to get it working in the container!

Nonobjective answered 28/4, 2023 at 11:48 Comment(1)
This didn't work for me on WSL on windowsBallade
L
0

For a Debian based Dockerfile, I needed to do :

RUN apt-get install -y  cabextract xfonts-utils
RUN apt --fix-broken install
RUN wget http://ftp.us.debian.org/debian/pool/contrib/m/msttcorefonts/ttf-mscorefonts-installer_3.8.1_all.deb
RUN dpkg -i ttf-mscorefonts-installer_3.8.1_all.deb
Loisloise answered 29/12, 2023 at 6:22 Comment(0)
M
-1

If you just want to get rid of matplotlib.font_manager warnings easily you can do:

    # Get rid of findfont: Font family 'Arial' not found.
    # when running a remote notebook on Jupyter Server on Ubuntu Linux server
    import logging
    logging.getLogger("matplotlib.font_manager").setLevel(logging.ERROR)
Manuelmanuela answered 29/4, 2023 at 13:34 Comment(1)
Unfortunately this goes against a symptom, not against the issueFrap

© 2022 - 2024 — McMap. All rights reserved.