Skip to content

Instantly share code, notes, and snippets.

@iktakahiro
Last active August 8, 2017 15:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iktakahiro/28d6e7c2620893e26e489a7b12e99c84 to your computer and use it in GitHub Desktop.
Save iktakahiro/28d6e7c2620893e26e489a7b12e99c84 to your computer and use it in GitHub Desktop.
グラフ描画に日本語フォントを指定
import os
import numpy as np
from matplotlib import pyplot as plt, font_manager, get_cachedir
# フォントキャッシュを再構築します
font_manager._rebuild()
if os.name == 'nt':
# OS が Windows の場合、win32FontDirectory() が利用出来ます。
font_dir = font_manager.win32FontDirectory()
else:
# OS が macOS の場合はディレクトリを指定してください。
# パスに含まれるユーザ名は環境に合わせて変更してください
font_dir = '/Users/pydata/Library/Fonts/'
font_path = os.path.join(font_dir, 'SourceHanCodeJP-Regular.otf')
font = font_manager.FontProperties(fname=font_path, size=14)
# グラフを描画します
np.random.seed(0)
x = range(5)
y = 10 + 5 * np.random.randn(5)
fig = plt.figure()
ax = fig.add_subplot(111)
# ここでfontpropertiesを指定します。
ax.set_title('日本語を指定したタイトル', fontproperties=font)
ax.bar(x, y)
plt.show()
@drillan
Copy link

drillan commented Aug 5, 2017

これでどうですか?

if os.name == 'nt':
    font_dir = font_manager.win32FontDirectory()
else:
    font_dir = '/Users/pydata/Library/Fonts/'

@iktakahiro
Copy link
Author

@iktakahiro
Copy link
Author

プラクティスとしてはほぼどこにも書かれていないけど以下の関数で当該のキャッシュファイルが再生成される模様

from matplotlib import font_manager

font_manager._rebuild()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment