Use a custom font like Montserrat in bold and italics bold using matplotlib

Viewed 142

I need to use the Montserrat font and display text in bold and italics bold. It's suppose to look like this

text example I am doing this using the matplotlib package 3.5.2 version. I downloaded the Mostserrat tff file.

from matplotlib.pyplot import *
import matplotlib as mpl
import matplotlib.font_manager as fm

fe = fm.FontEntry(
       fname='./Montserrat-Regular.ttf',
       name='Montserrat')
fm.fontManager.ttflist.insert(0, fe) # or append is fine
mpl.rcParams['font.family'] = fe.name
rcParams['mathtext.fontset'] = 'custom'
rcParams['mathtext.it'] = fe.name + ':italic'
rcParams['mathtext.bf'] = fe.name + ':italic:bold'


fig, ay = subplots()
ay.text(0.5,0.5,r"$\mathbf{My}$" + r"$\mathit{Text^{1}}$",fontsize=20)

show()

But it is displaying the text in the following manner

actual image

I tried the same code with STIX font and its working as expected.

rcParams['mathtext.fontset'] = 'custom'
rcParams['mathtext.it'] = 'STIXGeneral:italic'
rcParams['mathtext.bf'] = 'STIXGeneral:italic:bold'

text with STIX font

Edited

I tried another method.

from pathlib import Path
from matplotlib.font_manager import FontProperties
import matplotlib.font_manager as fm
import matplotlib.pyplot as plt

fe = fm.FontEntry(
    fname='./Montserrat-Regular (2).ttf',
    name='Montserrat')

alignment = {'horizontalalignment': 'center', 'verticalalignment': 
'baseline'}
fig, ax = plt.subplots()

font0 = FontProperties()
font = font0.copy()
font.set_style('italic')
font.set_weight('bold')
font.set_size('medium')
t = ax.text(0.3, 0.2, 'My', fontproperties=font, 
**alignment,fontsize=20,color='#004878',font=Path(fe.fname))

font0 = FontProperties()
font = font0.copy()
font.set_style('italic')
font.set_size('medium')
t = ax.text(0.475, 0.2, 'Text', fontproperties=font, 
**alignment,fontsize=20,color='#004878',font=Path(fe.fname))

font0 = FontProperties()
font = font0.copy()
font.set_weight('bold')
font.set_size('medium')
t = ax.text(0.61, 0.2, '$\mathregular{^{1}}$', fontproperties=font, 
**alignment,fontsize=20,color='#004878',font=Path(fe.fname))

plt.show()

When the Montserrat font is applied, the set_weight and set_style does not work as expected.

0 Answers
Related