简体   繁体   中英

Lato Fonts in Matplotlib Plots

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, eg 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM