0

I've searched for a while, trying to use Chinese font in my matplotlib histogram. Instead of installing the font locally, I tried to follow the post to use the raw TTF file from Github. However, I got In FT2Font: Can not load face. Unknown file format. message. Here is my code:

from tempfile import NamedTemporaryFile
import urllib3
import matplotlib.font_manager as fm
import matplotlib.pyplot as plt

https = urllib3.PoolManager()
github_url = 'https://github.com/google/fonts/tree/main/ofl/notosanssc/NotoSansSC[wght].ttf'

url = github_url + '?raw=true' # will trigger the download

response = https.request('GET', url)
# print(response.data) # to confirm the successful response with data
f = NamedTemporaryFile(delete=False, suffix='.ttf')
f.write(response.data)
f.close()
f.name # C:\\Users\\<username>\\AppData\\Local\\Temp\\tmp9i1czwm1.ttf'

fig, ax = plt.subplots()
ax.plot([1, 2, 3])

prop = fm.FontProperties(fname=f.name)
ax.set_title('this is a special font:\n%s' % github_url, fontproperties=prop)
ax.set_xlabel('This is the default font')

plt.show()

Reinstalling matplotlib and removing cache gave me no luck. What could be the issue? Thanks.

Woden
  • 1,054
  • 2
  • 13
  • 26

1 Answers1

0

I've figured it out using another way instead of Github Google font. There's also a post regarding using Chinese font with Mac. However, I am using Windows 10, which cannot replicate Mac's solution.

On Windows 10 (or 11), open Settings, Personalization, then fonts. Here you can confirm the installed fonts and available Chinese fonts. Next, go to matplotlib font cache, which could be C:\Users\<username>\.matplotlib. There's a file called fontlist-<version>.json, storing available fonts.

The format is:

{
  "_version": 330,
  "_FontManager__default_weight": "normal",
  "default_size": null,
  "defaultFamily": {
    "ttf": "DejaVu Sans",
    "afm": "Helvetica"
  },
  ttflist: [
    {
      "fname": "C:\\Windows\\Fonts\\FRABKIT.TTF",
      "name": "Franklin Gothic Book",
      "style": "italic",
      "variant": "normal",
      "weight": 400,
      "stretch": "normal",
      "size": "scalable",
      "__class__": "FontEntry"
    },
    "__class__": "FontManager"
  ]
}

Finally, you can set the font family with the name field. Below is the snippet:

fig, ax = plt.subplots()

fontP = matplotlib.font_manager.FontProperties()
fontP.set_family('DFKai-SB')

ax.set_title('職缺頻率計算', fontproperties=fontP)
plt.show()
Woden
  • 1,054
  • 2
  • 13
  • 26