Matplotlib:使用 Python 3.9 的云函数中的自定义字体
Matplotlib: Custom fonts in cloud functions using Python 3.9
我正在尝试使用 google 云函数和 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)
因为安装了字体。如何在云函数中使用此字体?
您可以在 Cloud Function 的 matplotlib 中使用自定义字体,而无需 安装字体。当您部署 Cloud Functions 时,它会上传您的函数目录的内容。您可以使用此方法更改字体而无需安装。以下是步骤:
- 下载您的自定义字体文件(解压缩文件)。
- 将字体文件放在函数根目录中,例如:
function/Balthazar-Regular.ttf
或为字体文件创建另一个文件夹
function/font_folder/Balthazar-Regular.ttf
- 示例代码:
# 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()
- 部署您的云功能。
我正在尝试使用 google 云函数和 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)
因为安装了字体。如何在云函数中使用此字体?
您可以在 Cloud Function 的 matplotlib 中使用自定义字体,而无需 安装字体。当您部署 Cloud Functions 时,它会上传您的函数目录的内容。您可以使用此方法更改字体而无需安装。以下是步骤:
- 下载您的自定义字体文件(解压缩文件)。
- 将字体文件放在函数根目录中,例如:
function/Balthazar-Regular.ttf
或为字体文件创建另一个文件夹
function/font_folder/Balthazar-Regular.ttf
- 示例代码:
# 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()
- 部署您的云功能。