google colab上让 python 视觉化套件 matplotlib 显示中文

 如何在 Colab 上让 python 视觉化套件 matplotlib 显示中文 

  1. 下载开源字体,目前是使用 Google 的 Noto Sans 系列
  2. 讲开源字体下载后自动导入字符型文件夹
  3. 在 matplotlib 设定字符参数
    # 从 Google API 上下载暂存字体放到咱村文件夹下
    !wget 'https://noto-website-2.storage.googleapis.com/pkgs/NotoSansCJKtc-hinted.zip'
    !mkdir /tmp/fonts
    !unzip -o NotoSansCJKtc-hinted.zip -d /tmp/fonts/
    !mv /tmp/fonts/NotoSansMonoCJKtc-Regular.otf /usr/share/fonts/truetype/NotoSansMonoCJKtc-Regular.otf -f
    !rm -rf /tmp/fonts
    !rm NotoSansCJKtc-hinted.zip
    --2022-06-26 08:47:46--  https://noto-website-2.storage.googleapis.com/pkgs/NotoSansCJKtc-hinted.zip
    Resolving noto-website-2.storage.googleapis.com (noto-website-2.storage.googleapis.com)... 173.194.213.128, 2607:f8b0:400c:c0a::80
    Connecting to noto-website-2.storage.googleapis.com (noto-website-2.storage.googleapis.com)|173.194.213.128|:443... connected.
    HTTP request sent, awaiting response... 200 OK
    Length: 121247366 (116M) [application/zip]
    Saving to: ‘NotoSansCJKtc-hinted.zip’
    
    NotoSansCJKtc-hinte 100%[===================>] 115.63M  39.4MB/s    in 2.9s    
    
    2022-06-26 08:47:49 (39.4 MB/s) - ‘NotoSansCJKtc-hinted.zip’ saved [121247366/121247366]
    
    Archive:  NotoSansCJKtc-hinted.zip
      inflating: /tmp/fonts/LICENSE_OFL.txt  
      inflating: /tmp/fonts/NotoSansCJKtc-Black.otf  
      inflating: /tmp/fonts/NotoSansCJKtc-Bold.otf  
      inflating: /tmp/fonts/NotoSansCJKtc-DemiLight.otf  
      inflating: /tmp/fonts/NotoSansCJKtc-Light.otf  
      inflating: /tmp/fonts/NotoSansCJKtc-Medium.otf  
      inflating: /tmp/fonts/NotoSansCJKtc-Regular.otf  
      inflating: /tmp/fonts/NotoSansCJKtc-Thin.otf  
      inflating: /tmp/fonts/NotoSansMonoCJKtc-Bold.otf  
      inflating: /tmp/fonts/NotoSansMonoCJKtc-Regular.otf  
      inflating: /tmp/fonts/README       
    # 指定字体
    import matplotlib.font_manager as font_manager
    import matplotlib.pyplot as plt
    
    font_dirs = ['/usr/share/fonts/truetype/']
    font_files = font_manager.findSystemFonts(fontpaths=font_dirs)
    
    for font_file in font_files:
      font_manager.fontManager.addfont(font_file)
    
    plt.rcParams['font.family'] = "Noto Sans Mono CJK TC"
    #测试
    import numpy as np
    import matplotlib.pyplot as plt
    
    
    plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
    
    x = np.arange(1, 12)
    y = x ** 2 + 4
    plt.title("Matplotlib demo")
    plt.xlabel("时间(分钟)")
    plt.ylabel("金额($)")
    plt.plot(x,y)
    plt.show()

    google colab上让 python 视觉化套件 matplotlib 显示中文_第1张图片

  4. 显示成功 

你可能感兴趣的:(python,开发语言)