在matplotlib中更改字体

4

我尝试了几乎所有在stackoverflow(和任何其他谷歌搜索结果)上找到的方法,但我就是无法更改这该死的字体!

以下是我迄今为止尝试过的非详尽列表:

按照此问题中的建议尝试:

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()

给我这个错误日志:

>>> (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]))

>>> 

这个答案 对我也没太大帮助:

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()

没有显示错误,但这不是Times字体...

Still not Times

对我来说,第一次尝试会出现那个错误日志有点奇怪,因为按照 this answer 所示,Times New Roman 确实是我应该能够使用的字体:

>>> 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'}

那么...我还能尝试什么?


你尝试过其他字体吗?无论如何,你最后的代码片段似乎表明,也许你应该使用 'Times' 而不是 'Times New Roman' 作为字体名称。 - jdehesa
我尝试了两个,甚至是“Times-Roman”,但仍然不起作用.. - A.Aussage
4个回答

9
为了查看可用的字体,你应该使用 这个方法
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)

然后看看是否有"Times New Roman"。

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

如果它不是,你就不能使用它。如果它是,以下内容将按预期工作。
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()

请注意,您可以指定多种字体。实际可用的第一个字体将被选择。在列表中最后添加"serif"至少可以确保如果其他字体都不存在,则回退到衬线字体。
plt.rcParams["font.family"] = "Gulasch", "Times", "Times New Roman", "serif"

看起来 'Times new Roman' 不在那里;我需要像这个问题中建议的那样强制添加它,还是有更简单的方法? - A.Aussage
你链接的问题很好。你需要检查是否实际上存在一个 Times New Roman 字体文件,如果没有,请将其添加到目录中,并清空字体缓存。这可能有效。 - ImportanceOfBeingErnest
1
看起来有一种名叫 STIX 的字体非常类似于 times;我想最安全的做法就是使用已经包含的字体! - A.Aussage
get_fontconfig_fonts函数在Matplotlib 3.5中已弃用,并将在后两个小版本中删除。请改用matplotlib.font_manager.findSystemFonts() - MERose

3

我在使用Python 3.9,Anaconda运行Pop!_OS 20.04 Linux时遇到了同样的问题。

所有专有的MS字体都已经通过sudo apt install ttf-mscorefonts-installer命令安装,但是没有任何帮助。

安装包含MS字体的CONDA包也没有帮助matplotlib! :(

fontmanager还抱怨说没有重建文件!

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

解决方法:

我将MS字体从/home/dracid/anaconda3/fonts复制到Matplotlib自己的字体文件夹中。对于我的系统来说是:

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

这样做后,需要删除matplotlib字体/home/dracid/.cache/matplotlib/fontlist-v330.json,然后在下一次启动Python会话时,它将重建缓存。

接着,让我们庆祝吧,我的IEEE论文图表终于工作了! :) 现在我可以继续进行我的LINUX学术工作 <3


这似乎是处理此问题的最新方法:anaconda/miniconda上的matplotlib显然需要在miniconda3/envs/<ENV_NAME>/lib/python3.9/site-packages/matplotlib/mpl-data/fonts/ttf文件夹中拥有.ttf字体文件。将.ttf字体文件复制到该文件夹并重新启动内核,这对我有效!我使用的是Ubuntu 22.04和Python3.9。 - flinz

1

我遇到了同样的问题,出现了相同的警告:

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

我阅读了很多 Stack Overflow 的帖子,但都没有找到答案,直到我发现了this

现在我可以在 matplotlib 中使用 "Times New Roman" 字体了。

在我的情况下,我必须使用 sudo,因为我没有使用虚拟环境,所以我不得不这样做:

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

我需要查找帖子中的最后一个建议,即:

注意:如果字体未渲染,可能是因为 matplotlib 需要刷新其字体缓存(请参见 Kevin 的评论):

import matplotlib

matplotlib.font_manager._rebuild()

但它对我不起作用。而我使用了:

import matplotlib.font_manager as fm

fm._rebuild()

很遗憾,该链接已失效:https://www.andresabino.com/2015/08/18/fonts-and-matplotlib/ - MERose

1
我使用了这段Python代码来确保Georgia已经安装在虚拟环境中。显然,这对于matplotlib.font_manager来说还不够。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接