【问题标题】:Matplotlib: Custom fonts in cloud functions using Python 3.9Matplotlib:使用 Python 3.9 在云函数中自定义字体
【发布时间】:2021-10-12 23:35:27
【问题描述】:

我正在尝试使用 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)

因为字体已安装。如何在云函数中使用此字体?

【问题讨论】:

    标签: python matplotlib google-cloud-functions


    【解决方案1】:

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

    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. 部署您的云函数。

    【讨论】:

    • 我还没有测试代码,因为我还在试图弄清楚如何执行第 2 步。
    猜你喜欢
    • 2016-06-10
    • 1970-01-01
    • 1970-01-01
    • 2020-06-30
    • 2017-11-27
    • 1970-01-01
    • 1970-01-01
    • 2022-08-05
    • 1970-01-01
    相关资源
    最近更新 更多