Skip to main content
 首页 » 编程设计

python之如何在 python shell 中检查 matplotlib 的默认字体

2024年10月24日17qq号

我尝试了下面的代码,但我只收到了所有 ttf 字体文件的列表。

import matplotlib.font_manager as fm  
for font in fm.findSystemFonts(): 
    print font 

我在想也许我需要使用 matplotlib 中的 findFont() 函数,但我不确定如何使用它。我的目标是能够询问 python 它用于 matplotlib 的默认字体是什么,理想情况下,如果它不是 Times New Roman,我想将默认设置更改为 Times New Roman。此外,如果 times new roman 不存在于 matplotlib 库中,那么我该如何将默认值更改为下一个最佳衬线字体。

请您参考如下方法:

您可以使用rcParams 动态修改字体。检查以下代码:

import matplotlib as mpl 
 
mpl.rcParams['font.family'] = ['serif'] # default is sans-serif 
mpl.rcParams['font.serif'] = [ 
           'Times New Roman', 
           'Times', 
           'Bitstream Vera Serif', 
           'DejaVu Serif', 
           'New Century Schoolbook', 
           'Century Schoolbook L', 
           'Utopia', 
           'ITC Bookman', 
           'Bookman', 
           'Nimbus Roman No9 L', 
           'Palatino', 
           'Charter', 
           'serif'] 

这样,如果 Times New Roman 在您的系统中可用,matplotlib 将在 session 期间使用它,否则,它将尝试使用定义的下一个字体类型。看看here for more info .

如果您想将参数重置为默认值,您可以使用:

mpl.rcdefaults() 

其他选项是 use a stylesheet使用您想要的设置,您可以将该样式应用于所有绘图,或者使用上下文管理器仅应用于其中的一些绘图。