简体   繁体   中英

Changing fonts in matplotlib

So I've tried pretty much everything I could find on stackoverflow (and anywhere else google would lead me) ; and I just can't change the god damn font !

Here comes the non-exhaustive list of what I've tried so far :

Trying as suggested in this question :

import matplotlib.pyplot as plt
csfont = {'fontname':'Times New Roman'}
x = [1,2,3]
y = x

plt.plot(x,y)

plt.title('Please be Times >__<',**csfont)

plt.show()

gives me this error log :

>>> (executing file "<tmp 1>")
Note on using QApplication.exec_():
The GUI event loop is already running in the pyzo kernel, and exec_()
does not block. In most cases your app should run fine without the need
for modifications. For clarity, this is what the pyzo kernel does:
- Prevent deletion of objects in the local scope of functions leading to exec_()
- Prevent system exit right after the exec_() call
/home/antoine/miniconda3/lib/python3.6/site-packages/matplotlib/font_manager.py:1297: UserWarning: findfont: Font family ['Times New Roman'] not found. Falling back to DejaVu Sans
  (prop.get_family(), self.defaultFamily[fontext]))

>>> 

This answer didn't quite help me either :

import matplotlib.pyplot as plt
plt.rcParams["font.family"] = "Times New Roman"
x = [1,2,3]
y = x

plt.plot(x,y)

plt.title('Please be Times >__<',**csfont)

plt.show()

There is no error shown ; but this is not Times ...

仍然不是时代

It's also a bit wierd to me that the first attempt gives that error log, as doing what this answer suggests shows that Times New Roman is indeed a font I should be able to use :

>>> set([f.name for f in matplotlib.font_manager.fontManager.afmlist])
{'Courier', 'Times', 'URW Bookman L', 'Nimbus Mono L', 'ITC Bookman', 'ZapfDingbats', 'Century Schoolbook L', 'New Century Schoolbook', 'Helvetica', 'Standard Symbols L', 'Utopia', 'Palatino', 'URW Gothic L', 'Courier 10 Pitch', 'Symbol', 'Computer Modern', 'Bitstream Charter', 'ITC Avant Garde Gothic', 'Nimbus Roman No9 L', 'ITC Zapf Chancery', 'ITC Zapf Dingbats', 'URW Chancery L', 'Nimbus Sans L', 'Dingbats', 'URW Palladio L'}

So ... What else can I try ?

In order to see which fonts are available, you should use this method :

import  matplotlib.font_manager
flist = matplotlib.font_manager.get_fontconfig_fonts()
names = [matplotlib.font_manager.FontProperties(fname=fname).get_name() for fname in flist]
print names

Then see if "Times New Roman" is there or not.

if "Times New Roman" in names:
    print "Yes"
else:
    print "font not available"

If it isn't, you can't use it. If it is, the following will work as expected.

import matplotlib.pyplot as plt
plt.rcParams["font.family"] = "Times New Roman"

plt.plot([1,2,3])

plt.title('Please be Times New Roman')

plt.show()

Note that you may specify several fonts. The first that actually is available will be chosen. Adding "serif" last in the list at least makes sure to fall back to a serif font if none of the others is present.

plt.rcParams["font.family"] = "Gulasch", "Times", "Times New Roman", "serif"

I'd the same problem with the same warning:

UserWarning: findfont: Font family ['Times New Roman'] not found. Falling back to DejaVu Sans

I read lots of Stack Overflow posts to no avail until I found this.

Now I can use Times New Roman in matplotlib

In my case I had to use sudo and since Im not using a virtual environment I'd to do this instead:

sudo cp /usr/share/fonts/truetype/msttcorefonts/Times_New_Roman* /usr/local/lib/python2.7/dist-packages/matplotlib/mpl-data/fonts/ttf

Another thing that I'd to look up was the last suggestion of the post, ie,

Note: If the font is not rendered, it may be because matplotlib needs to refresh its font cache (see Kevin's comment):

import matplotlib

matplotlib.font_manager._rebuild()

It didn't work for me. Instead I used:

import matplotlib.font_manager as fm

fm._rebuild()

I used this i python code to make sure Georgia was installed in a virtualenv. Apparently it is not enough for the matplotlib.font_manager to find it.

import os.path
import matplotlib
import matplotlib.font_manager

destination = os.path.join(os.path.dirname(matplotlib.__file__), 'mpl-data/fonts/ttf')
for font_filename in matplotlib.font_manager.get_fontconfig_fonts():
    try:
        if matplotlib.font_manager.FontProperties(fname=fname).get_name() == 'Georgia':
            !cp '{font_filename}' '{destination}'
            matplotlib.font_manager.rebuild()
            print('Installed ' font_filename)
            break
    except:
        pass

I've had the same problem on Python 3.9, Anaconda on Pop!_OS 20.04 Linux.

All proprietary MS fonts were installed using sudo apt install ttf-mscorefonts-installer , but didn't help at all.

Installing a package for CONDA that has MS fonts didn't help matplotlib either! :(

Also, my fontmanager complains that there is no such thing as rebuild!

AttributeError: module 'matplotlib.font_manager' has no attribute '__rebuild'

SOLUTION:

I've copied MS fonts from /home/dracid/anaconda3/fonts to the Matplotlib's OWN folder of fonts. On my system it's:

/home/dracid/anaconda3/lib/python3.9/site-packages/matplotlib/mpl-data/fonts/ttf

After this, one needs to remove matplotlib font /home/dracid/.cache/matplotlib/fontlist-v330.json , then on the next launch of Python session, it will rebuild cache.

Then, VIOLA my IEEE paper plot is working finally :) Now I can proceed with my academic work on LINUX <3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM