0
0

matplotlibを用いたグラフ描写にてTimes New Romanのフォントを利用する方法

Last updated at Posted at 2024-08-12

はじめに

OS、実行環境は以下の通りです。

Ubuntu 22.04
virtualenv + python 3.9

タイトルにあるように、matplotlibにてグラフを描写する際、グラフ内で用いる凡例や軸名にTimes New Romanを用いる方法を説明します。以下、自身の環境におけるデフォルトのフォントです。

>>>import matplotlib as plt
>>>plt.rcParams["font.family"]
['sans-serif']

Times New Romanフォントのインストール

まず、システムにTimes New Romanフォントがインストールされていることを確認します。以下のコマンドを使用して、Microsoftのコアフォントをインストールします。

sudo apt update
sudo apt install ttf-mscorefonts-installer

フォントファイルを仮想環境に設定

Times New Romanフォントファイル(Times_New_Roman.ttf)を仮想環境内のMatplotlibフォントディレクトリにコピー。なお、カレントディレクトリ内のenvに仮想環境があリます。pythonX.Xは仮想環境内のpythonバージョンを指定。

cp /usr/share/fonts/truetype/msttcorefonts/Times_New_Roman.ttf ./env/lib/pythonX.X/site-packages/matplotlib/mpl-data/fonts/ttf/

Matplotlibのフォントキャッシュをクリアします。

rm -rf ~/.cache/matplotlib

次に、Pythonコード内でフォントを設定。/home/muzzumuzu/src/envは仮想環境のパス。
pythonX.Xは仮想環境内のpythonバージョンを指定。

import matplotlib.pyplot as plt
from matplotlib import font_manager as fm
font_path = "/home/muzzumuzu/src/env/lib/pythonX.X/site-packages/matplotlib/mpl-data/fonts/ttf/Times_New_Roman.ttf"
font_prop = fm.FontProperties(fname=font_path)

# フォントプロパティをMatplotlibに設定
plt.rcParams["font.family"] = "sans-serif"
plt.rcParams["font.sans-serif"] = [font_prop.get_name()]

これでTimes New Romanのフォントが利用できます(多分)。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0