Infi
Infi

Reputation: 255

Change font type of some letters in a word in a Matplotlib plot

Say, for example, this is the plot I want to make with 'L' in 'LEGEND' in a different font.

import matplotlib.pyplot as plt
plt.plot([1,2,3],[4,5,6])
plt.legend(['LEGEND'])
plt.show()

enter image description here

Currently, I Latex out the text I want to be unaffected and change the font for the whole function. Like this.

import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
font_name = fm.FontProperties('Rage Italic').get_name()
plt.plot([1,2,3],[4,5,6])
plt.legend(['L$EGEND$'],prop={'family':font_name, 'size':14})
plt.show()

enter image description here

Is there any simpler way to do this, because, in my actual project, I had to do something like this $($l$/w)_{sub} = 1$ to change the font of l throughout a code which was pretty cumbersome.

Upvotes: 2

Views: 1700

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339120

Note that unless you use usetex=True, you will not be using latex, but rather matplotlib's mathtext. This allows you to use different kind of modifications to the font, the same known from latex, like \mathit for italic text etc.

You might hence opt for something like

ax.legend(['$\mathcal{L}\mathrm{EG}\mathit{END}$'], prop={'size':14})

enter image description here

Using true latex rendering may actually help you more here, because it would in prinpicle allow to use as many different fonts as you wish.

import matplotlib.pyplot as plt
plt.rcParams['text.usetex'] = True
plt.rcParams['text.latex.preamble'] = [
        r'\usepackage[T1]{fontenc}',
        r'\usepackage{cyklop}' ]


fig, ax=plt.subplots()
ax.plot([1,1,1,1,10])

tx = r'{\fontfamily{cyklop}\selectfont L}' + \
     r'{\fontfamily{bch}\selectfont E}' + \
     r'{\fontfamily{phv}\selectfont G}' + \
     r'{\fontfamily{lmtt}\selectfont END}'

ax.legend([tx], prop={'size':14})

plt.show()

enter image description here

Upvotes: 2

Related Questions