【问题标题】:Lato Fonts in Matplotlib PlotsMatplotlib 绘图中的 Lato 字体
【发布时间】:2021-06-07 05:24:28
【问题描述】:

以前有人问过这个问题,但我还没有找到任何可行的解决方案。我一直在试图弄清楚如何将 Matplotlib 图中的 默认字体 更改为 Lato

那里有几个帖子/线程,例如123。通过这些帖子,我尝试按以下方式进行构建。首先,将我电脑中的所有字体添加到字体管理器中,如示例 2 中建议的那样。

from matplotlib import font_manager

font_dirs = [r"C:\Windows\Fonts"]
font_files = font_manager.findSystemFonts(fontpaths=font_dirs)

for font_file in font_files:
    font_manager.fontManager.addfont(font_file)
    
result = font_manager.findfont("Lato")
print(result)

print 的输出是 --> C:\Windows\Fonts\Lato-Regular.ttf 因此,字体管理器检测到 Lato。在下一步中,我尝试了

import matplotlib as mpl
mpl.rcParams['font.family'] = 'Lato-Regular'
mpl.rcParams['font.sans-serif'] = 'Lato-Regular'
import matplotlib.pyplot as plt
plt.plot(range(0,50,10))
plt.title('Font test', size=32)
plt.show()
plt.savefig('f1.png')

现在代码可以完美运行,没有任何“DeJaVou”错误。但字体仍然是默认字体,而不是Lato

我做错了什么?任何帮助表示赞赏!谢谢。

【问题讨论】:

  • 你想改变当前情节的字体吗?
  • @David:是的,主要是。在此之后,可能会将相同的方法应用于所有子图。

标签: python matplotlib fonts


【解决方案1】:

使用该字体,最好是install 全家人(或至少是主要样式)。请记住,Lato 是一种 sans-serif 字体,并且由于您想将其用作所有绘图的默认字体(仅用于一个脚本),因此它应该在 sans-serif 系列选项中.

import matplotlib as mpl
import numpy as np
import matplotlib.pyplot as plt

print(mpl.rcParams['font.sans-serif'])

# Just write the name of the font
mpl.rcParams['font.sans-serif'] = 'Lato'
print(mpl.rcParams['font.sans-serif'])

plt.figure()
plt.plot(range(0,50,10))
plt.title('Font test', size=32)


plt.figure()
x = np.linspace(0, 6.5)
y = np.sin(x)
plt.plot(x, y)
plt.title(r'Just a plot of the function $f(x) = \sin(x)$', size=18)

plt.show()

你可以看到标题的变化,记号,如果你放一些图例,你会在那里看到字体。

【讨论】:

  • 感谢您的回答。我重新安装了所有样式的 Lato 字体。但是,我仍然得到第一个数字和第二个数字:findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans.。我尝试在 Jupyter notebook 和 Spyder 文件中运行此代码,仍然得到相同的结果。
  • 您的独立代码不起作用,但是,它在我的第一部分代码行中为我提供了所需的输出。感谢您的努力。
猜你喜欢
  • 2015-09-18
  • 2014-10-15
  • 1970-01-01
  • 2020-04-08
  • 1970-01-01
  • 1970-01-01
  • 2014-08-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多