Home > database >  Matplotlib: Custom fonts in cloud functions using Python 3.9
Matplotlib: Custom fonts in cloud functions using Python 3.9

Time:10-14

I'm trying to graph using google cloud functions using matplotlib, but I need to use the font Balthazar.

Here is the simple example I'm working with https://matplotlib.org/stable/gallery/shapes_and_collections/scatter.html

And here is the font. https://www.1001freefonts.com/balthazar.font

I can do it on my desktop using:

hfont = {'fontname': 'Balthazar'}
plt.text(6, 0.5, 'Test', **hfont, fontsize=20)

because the font is installed. How do I use this font in cloud functions?

CodePudding user response:

You can use custom fonts in matplotlib from Cloud Function without installing the font. When you deploy a Cloud Function, it will upload the contents of your function's directory. You can use this method to change your font without installing it. Here are the steps:

  1. Download your custom font file(unzip the file).
  2. Place your font file in your function root directory, ex:
function/Balthazar-Regular.ttf

or create another folder for font files

function/font_folder/Balthazar-Regular.ttf
  1. Sample code:
# font file directory
font_dir = ['/font_folder']

# Add every font at the specified location
font_files = font_manager.findSystemFonts(fontpaths=font_dir)
for font_file in font_files:
   font_manager.fontManager.addfont(font_file)

# Set font family globally
plt.rcParams['font.family'] = 'Balthazar'

# The details below is the sample code in matplotlib
np.random.seed(19680801)


N = 50
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
area = (30 * np.random.rand(N))**2  # 0 to 15 point radii

plt.scatter(x, y, s=area, c=colors, alpha=0.5)
plt.show()
  1. Deploy your Cloud Function.
  • Related