Coolcrab
Coolcrab

Reputation: 2723

pyplot plt.text custom font

I am trying to make a picture in python in a custom font for some nametags. So the end goal is to have a loop that saves an image with text how I want it.

Afaik this should work, as I changed the rc. But the font of plt.text is still the default. Does anyone know how to make this work?

import matplotlib.pyplot as plt
from matplotlib import font_manager, rc

f_name = font_manager.FontProperties(fname='/Users/me/Library/Fonts/customfont.ttf').get_name()
rc('font', family=f_name)

plt.text(0, 0.6, r"$%s$" % 'test', fontsize = 50)

Here is an example of what I get. The ticks change, so rc is set correctly. But the text does not. enter image description here

Upvotes: 2

Views: 1863

Answers (1)

Alexandre B.
Alexandre B.

Reputation: 5502

The problem seems to come from the $ ... $ notation that should override the font properties.

Try:

import matplotlib.pyplot as plt
from matplotlib import font_manager

# Path
path = '/path/to/custom/font.ttf'

# Create FontProperty object
font_prop = font_manager.FontProperties(fname=path)

# Apply font_prop to the text
plt.text(0, 0.6, 'Custom font !', font_properties=font_prop, fontsize = 50)


plt.show()

Output: enter image description here

Upvotes: 4

Related Questions