1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

オブジェクト指向で整理する Matplotlib ― 基本設定編

1
Last updated at Posted at 2025-12-12

はじめに

Matplotlib の plt.rcParams を直接書き散らすと、設定が至るところに分散したり他のファイルから再利用しづらかったりという問題が起きがちです。

今回、私は Matplotlib の設定を オブジェクト指向でカプセル化し、再利用可能で、保守しやすい構成にまとめました。

本記事のゴール

  • Matplotlib の設定を 1ヶ所に集約して管理したい
  • フォント設定を再利用する
  • 日本語フォントで表示できるようにする

🎨 実装コード(完全版)

from matplotlib import font_manager
from matplotlib import pyplot as plt



class PlotConfigurator:
    def __init__(self, fig: Figure, ax: Axes):
        self.fig = fig
        self.ax = ax
        self.font_prop = FontLoader().font_prop

    def apply(self):
        # font設定
        self.fig.text(0.01, 0.01, "", fontproperties=self.font_prop)
        # tick設定
        self.ax.tick_params(
            axis="x", direction="in", labelsize=11, top=True, which="both"
        )
        self.ax.tick_params(
            axis="y", direction="in", labelsize=11, right=True, which="both"
        )
        # グリッド(局所設定)
        self.ax.grid(linestyle="--", color="gray", alpha=0.7, linewidth=0.7)


class FontLoader:
    #フォントファイルのパスに設定してください
    FONT_PATH = "/your/path/NotoSansJP-Regular.ttf"

    def __init__(self):
        font_manager.fontManager.addfont(FONT_PATH)
        self.font_prop = font_manager.FontProperties(fname=FONT_PATH)  # type: ignore (OSによって型が異なるため)

日本語フォントはNotoSansJP-Regular.ttfをローカルにダウンロードして利用しています。
またパス等は各自設定して調整してください。

📥ダウンロードはこちらから

呼び出し方法

プロット前に以下を 1 行書くだけで設定が適用されます。

self.fig, self.ax = plt.subplots(figsize=self.FIG_SIZE)
PlotConfigurator(self.fig, self.ax).apply()

これで、以降の全てのプロットに共通設定が反映されます。

さいごに

本記事ではオブジェクト指向でフォント設定をする方法を紹介しました。
今回はフォントの設定だけでしたが、他の設定もカプセル化することでコードを綺麗に書けます。
次回は軸設定のカプセル化の方法を紹介したいと思います。
もし分からないことがあったら気軽に質問してください!

1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?