图表显示中文
使用 matplotlib 绘制图表时只能显示英文,如果直接输入中文将会出现乱码,这篇教学将会介绍如何加载外部字体,让图表可以正确的显示中文。
快速导览
本篇使用的 Python 版本为 3.7.12,所有范例可使用 Google Colab 实作,不用安装任何软件 ( 参考:使用 Google Colab )
使用 matplotlib.font_manager
由于 matplotlib 绘制图表时只能显示英文,因此必须使用 matplotlib.font_manager 进行字体的管理和设定,下方的例子将中文字型放在 Google 云端硬盘,再使用 Colab 连接对应的路径,接着设定 fontproperties 参数,就能显示中文。
from matplotlib import pyplot as plt
from matplotlib.font_manager import FontProperties as font
# 設定字型的路徑
font1 = font(fname="/content/drive/MyDrive/Colab Notebooks/font/NotoSansTC-Regular.otf")
x = [1,2,3,4,5]
fig = plt.figure()
plt.plot(x)
# 設定 fontproperties 參數,指定字型
plt.title('這是圖表', fontproperties=font1, fontsize=20)
plt.show()
一张图表,多种中文字型
使用同样的方法,可以指定多种中文字型,下方的例子,title 使用 font1 的中文字型,xlabel 和 ylabel 则使用 font2 的中文字型。
from matplotlib import pyplot as plt
from matplotlib.font_manager import FontProperties as font
font1 = font(fname="/content/drive/MyDrive/Colab Notebooks/font/NotoSansTC-Regular.otf")
font2 = font(fname="/content/drive/MyDrive/Colab Notebooks/font/wlcmaru2004emojip.ttf")
x = [1,2,3,4,5]
fig = plt.figure()
plt.plot(x)
plt.title('這是圖表', fontproperties=font1, fontsize=20)
plt.xlabel('X 軸', fontproperties=font2, fontsize=20)
plt.ylabel('Y 軸', fontproperties=font2, fontsize=20)
plt.show()
下载 Google Font 免费字型
Google Font 是 Google 提供的免费字型,目前 Google Font 提供两种繁体中文字型,可透过下面的网址进行下载。
微信扫码关注
抖音扫码关注