Matplotlib:使用Python 3.9在云函数中自定义字体



我正在尝试使用matplotlib使用谷歌云函数绘制图形,但我需要使用字体Balthazar。

下面是我正在使用https://matplotlib.org/stable/gallery/shapes_and_collections/scatter.html

的简单示例这是字体。https://www.1001freefonts.com/balthazar.font

我可以在桌面上使用:

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

,因为字体已安装。如何在云功能中使用这种字体?

您可以在matplotlib中使用Cloud Function中的自定义字体,而不需要安装字体。部署云函数时,它将上传函数目录的内容。您可以使用此方法更改字体,而无需安装字体。步骤如下:

  1. 下载您的自定义字体文件(解压文件)。
  2. 将字体文件放在函数根目录下,例如:
function/Balthazar-Regular.ttf

或为字体文件创建另一个文件夹

function/font_folder/Balthazar-Regular.ttf
  1. 示例代码:
# 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. 部署您的云功能