loo*_*oom 4 python fonts matplotlib
我正在尝试将 matplotlib 图的字体设置为 Times New Roman。我努力了:
import matplotlib.pyplot as plt
plt.rcParams['font.family'] = 'Times New Roman'
Run Code Online (Sandbox Code Playgroud)
我相信这是设置字体的正确方法,但我不断收到此错误,提示找不到找到的字体:
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/matplotlib/font_manager.py:1238: UserWarning: findfont: Font family ['Times New Roman'] not found. Falling back to DejaVu Sans.
Run Code Online (Sandbox Code Playgroud)
经过一番搜索,我确认我已经下载了该字体。我尝试打开 python shell 并亲自检查 rcParams 的内容。在一堆其他字体参数中,我好奇地得到了一个font.serif
包含 Times New Roman 的字体列表。
'font.serif': ['DejaVu Serif', '比特流维拉衬线', “计算机现代罗马”, 《新世纪教科书》, 《世纪教科书L》, “乌托邦”, “ITC 布克曼”, ‘书人’, 'Nimbus Roman No9 L', '英语字体格式一种', 《时代》, '帕拉蒂诺', '宪章', '衬线'],
但是,font.family
仅包含一项:sans-serif
,而matplotlib 文档指出内应有五个值font.family
。以前有人遇到过这个错误吗?你怎么修好它的?
然而,font.family 只包含一项:sans-serif,而 matplotlib 文档指出 font.family 中应该有五个值
不,font.family
应该包含这五个值之一,即您要使用的字体系列。
您必须确保字体系列设置为衬线字体,并且Times New Roman字体位于衬线字体列表的顶部。它的工作原理如下:
plt.rcParams['font.family'] = 'serif'
plt.rcParams['font.serif'] = ['Times New Roman'] + plt.rcParams['font.serif']
Run Code Online (Sandbox Code Playgroud)
从技术上讲,您不需要附加列表的其余部分(最后一部分)。如果 Times New Roman 实际上不可用,它只是为 matplotlib 提供后备。
另请参阅文档中的示例。