0

This has been asked before but I havent found any working solution for me. I have been trying to figure out how to change default font in Matplotlib plot to Lato.

There are several posts/threads out there, e.g. 1, 2, 3. With these posts, I tried building up as following. Firstly, all fonts from my computer are added to font manager, like suggested in example 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)

Output of print is --> C:\Windows\Fonts\Lato-Regular.ttf Thus, Lato is detected by Font Manager. In the next step, I tried

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

Now code runs flawlessly, without any "DeJaVou" error. But font is still the default font and not Lato.

What am I doing wrong? Any help is appreciated ! Thanks.

1 Answers1

2

With that font, it is better to install all of the family (or at least the main styles). Keep in mind that Lato is a sans-serif font and since you want to use it as the default font for all the plot (for just one script), it should be in the sans-serif family option.

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

As you can see the change in the title, ticks, and if you put some legends, you will see the font there.

David
  • 435
  • 3
  • 12
  • Thanks for the answer. I reinstalled all styles of Lato font. However, I am still getting for 1st figure and 2nd Figure: ```findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans.```. I tried running this code both in Jupyter notebook and in Spyder file, still getting the same result. – pukumarathe Jun 07 '21 at 12:18
  • your code standalone did not work, however, it gave me desired output with my first part of code lines. Thanks for the effort. – pukumarathe Jun 09 '21 at 13:13