これは、なにをしたくて書いたもの?
Pythonのグラブ描画ライブラリーといえば、Matplotlibが代表的なもののひとつだというイメージがあります。
今まで可視化まわりをちゃんと扱ってきていなかったので、少しちゃんと学んでみようかなと思いまして。
まずはQuick start guideをやってみようと思います。書いていたら長くなったので、前編と後編で分けることにしました。
後半はこちらです。
Pythonのグラフ描画ライブラリー、MatplotlibのQuick start guideをやってみる(後編) - CLOVER🍀
Matplotlib
MatplotlibのWebサイトはこちら。
Matplotlib documentation — Matplotlib 3.10.7 documentation
静的、アニメーション、インタラクティブな可視化ができる包括的なライブラリーであるとされています。
他にはPlotlyというライブラリーも人気がありそうです。
Plotly Python Graphing Library
現在のバージョンは3.10.7です。
Matplotlib documentation — Matplotlib 3.10.7 documentation
まずはQuick start quideに沿ってやっていってみましょう。
Quick start guide — Matplotlib 3.10.7 documentation
環境
今回の環境はこちら。
$ python3 --version Python 3.12.3 $ uv --version uv 0.9.8
準備
まずはuvプロジェクトを作成してMatplotlibをインストールします。
$ uv init --vcs none $ rm main.py
Matplotlibをインストール。
$ uv add matplotlib
あとRuffも入れておきます。
$ uv add --dev ruff
pyproject.toml
[project] name = "getting-started-guide" version = "0.1.0" description = "Add your description here" readme = "README.md" requires-python = ">=3.12" dependencies = [ "matplotlib>=3.10.7", ] [dependency-groups] dev = [ "ruff>=0.14.4", ]
インストールされたライブラリーの一覧。
$ uv pip list Package Version --------------- ----------- contourpy 1.3.3 cycler 0.12.1 fonttools 4.60.1 kiwisolver 1.4.9 matplotlib 3.10.7 numpy 2.3.4 packaging 25.0 pillow 12.0.0 pyparsing 3.2.5 python-dateutil 2.9.0.post0 ruff 0.14.4 six 1.17.0
ちなみに、uvを使う時はバージョンに注意する必要がありそうです。
uv usually installs its own versions of Python from the python-build-standalone project, and only recent versions of those Python builds (August 2025) work properly with the tkagg backend for displaying plots in a window. Please make sure you are using uv 0.8.7 or newer (update with e.g. uv self update) and that your bundled Python installs are up to date (with uv python upgrade --reinstall). Alternatively, you can use one of the other supported GUI frameworks, e.g.
ひとまず準備は完了です。
MatplotlibのQuick start guideをやってみる
それでは、こちらに沿って進めてみます。
Quick start guide — Matplotlib 3.10.7 documentation
どのコードを実行するにも、以下のimport文が必要なようです。
import matplotlib.pyplot as plt import numpy as np
A simple example
まずはこちらから。
Quick start guide / A simple example
例をそのままコードにしてみます。
simple_example.py
import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() ax.plot([1, 2, 3, 4], [1, 4, 2, 3]) plt.show()
とりあえず実行してみると、以下のようになり図が表示されません。
$ uv run simple_example.py /path/to/simple_example.py:6: UserWarning: FigureCanvasAgg is non-interactive, and thus cannot be shown plt.show()
調べてみると、Matplotlibでは図を表示するためのバックエンドというものが必要だそうです。デフォルトはOSのパッケージとしてpython-tk
というものが入っていれば、それを選ぶようです。
By default, Matplotlib should automatically select a default backend which allows both interactive work and plotting from scripts, with output to the screen and/or to a file, so at least initially, you will not need to worry about the backend. The most common exception is if your Python distribution comes without tkinter and you have no other GUI toolkit installed. This happens with certain Linux distributions, where you need to install a Linux package named python-tk (or similar).
Backends / The builtin backends
こちらが使えるようになるみたいですね。
tkinter --- Tcl/Tk の Python インターフェース — Python 3.12.12 ドキュメント
Ubuntu Linux 24.04 LTSでは、python3-tkというパッケージ名でした。
$ apt show python3-tk Package: python3-tk Version: 3.12.3-0ubuntu1 Priority: optional Section: python Source: python3-stdlib-extensions Origin: Ubuntu Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com> Original-Maintainer: Matthias Klose <doko@debian.org> Bugs: https://bugs.launchpad.net/ubuntu/+filebug Installed-Size: 474 kB Provides: python3.12-tk Depends: python3 (>= 3.12.2-0~), python3 (<< 3.13), blt (>= 2.4z-9), libc6 (>= 2.4), libtcl8.6 (>= 8.6.0), libtk8.6 (>= 8.6.0), tk8.6-blt2.5 (>= 2.5.3) Suggests: tix, python3-tk-dbg Breaks: libpython3.6-stdlib (<< 3.6.4~rc1-2), libpython3.7-stdlib (<< 3.7.0~a3-2) Replaces: libpython3.6-stdlib (<< 3.6.4~rc1-2), libpython3.7-stdlib (<< 3.7.0~a3-2) Task: ubuntustudio-photography, ubuntustudio-publishing, edubuntu-desktop-gnome, edubuntu-desktop-gnome-raspi Download-Size: 102 kB APT-Sources: http://jp.archive.ubuntu.com/ubuntu noble/main amd64 Packages Description: Tkinter - Writing Tk applications with Python 3.x A module for writing portable GUI applications with Python 3.x using Tk. Also known as Tkinter.
インストール。
$ sudo apt install python3-tk
再度実行すると
$ uv run simple_example.py
今度は描画されました。

これで初めてのMatplotlibによるグラフ描画ができました、と。
コードに戻ります。
fig, ax = plt.subplots() ax.plot([1, 2, 3, 4], [1, 4, 2, 3]) plt.show()
Matplotlibではfig(Figure)のデータを可視化します。
matplotlib.figure.Figure — Matplotlib 3.10.7 documentation
各グラフには、ひとつ以上のax(Axes)が含まれます。
matplotlib.axes.Axes — Matplotlib 3.10.7 documentation
Axesは点をxy座標(または極座標ではθ-r、3D座標ではx-y-z)で指定できる領域です。
Axesを持つFigureを作成する最も簡単な方法がpyplot.subplotsを使うことです。
matplotlib.pyplot.subplots — Matplotlib 3.10.7 documentation
その後、Axes.plotでデータを描画し、pyplot.showでFigureを表示します。
ちなみに、Jupyter Notebookのようなコードセルで作成されたすべての図を自動的に表示する環境ではpyplot.showを省略できます。
Figureの構成要素
ここで、Figureの構成要素を見ていきます。
Quick start guide / Parts of a Figure
こちらですね。

ここで、Figure、Axes、Axis、Artistの4つの言葉が出てきます。
Figure全体について。Figureはすべての子となるAxes、特別なArtistのグループ(タイトル、図の凡例、カラーバーなど)、そしてネストした
サブfigureを含みます。
Figureの作成方法は、通常以下のいずれかになるようです。
fig = plt.figure() # Axesがない空のFigure fig, ax = plt.subplots() # ひとつのAxesを持つFigure fig, axs = plt.subplots(2, 2) # 2 × 2のグリッドとなるAxesを持つFigure # ひだりにひとつ、そして右に2つのAxesを持つFigure fig, axs = plt.subplot_mosaic([['left', 'right_top'], ['left', 'right_bottom']])
Axesはデータをプロットするために、FigureにアタッチされたArtistです。通常は2つ(3Dの場合は3つ)のオブジェクトが含まれます。これらの
オブジェクトは、Axes内のデータのスケールを提供するための目盛りと目盛りラベルを提供します。また、Axesのset_title、set_xlabel、
set_ylabelで設定できるタイトル、xラベル、yラベルがあります。
Axesはプロットのほとんどの部分(データの追加、軸のスケールや上限、ラベルの追加など)を設定するための主要なインターフェースです。
Axisはスケールと目盛りを設定し、目盛り(Axis上のマーク)と目盛りラベル(目盛りにラベルをつける文字列)を生成します。目盛りの位置は
Locatorオブジェクトにより決まり、目盛りラベルの文字列はFormatterでフォーマットされます。
AxesとAxisが混同しやすそうで注意ですね。
ArtistはFigureに表示されるものすべてを指します。Figure、Axes、AxisもArtistの一種です。Text、Line2D、collections、Patchオブジェクトなどが
含まれます。Figureがレンダリングされると、すべてのArtistがキャンバスに描画されます。ほとんどのArtistはAxesに結び付けられていて、
複数のAxesで共有したり、Axes間で移動することはできません。
プロット関数への入力の種類
プロット関数は入力としてnumpy.arrayまたはnumpy.ma.masked_array、numpy.asarrayを期待しています。
Quick start guide / Types of inputs to plotting functions
Pandasのデータオブジェクトやnumpy.matrixのような配列に似たクラスは、意図通りに動作しない可能性があります。よくある慣習としては、
プロットする前にこれらのオブジェクトをnumpy.arrayに変換します。
以下はnumpy.matrixを変換する例です。
b = np.matrix([[1, 2], [3, 4]]) b_asarray = np.asarray(b)
ほとんどのメソッドは辞書、numpyのStructured arrays、PandasのDataFrameのような文字列インデックスアクセス可能なオブジェクトも
解析します。
サンプル。
inputs_to_plot_functions.py
import matplotlib.pyplot as plt import numpy as np np.random.seed(19680801) data = {"a": np.arange(50), "c": np.random.randint(0, 50, 50), "d": np.random.randn(50)} data["b"] = data["a"] + 10 * np.random.randn(50) data["d"] = np.abs(data["d"]) * 100 print(data) fig, ax = plt.subplots(figsize=(5, 2.7), layout="constrained") ax.scatter("a", "b", c="c", s="d", data=data) ax.set_xlabel("entry a") ax.set_ylabel("entry b") plt.show()
実行。
$ uv run inputs_to_plot_functions.py
dataを出力している箇所はこんな感じです。
{'a': array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]), 'c': array([20, 44, 20, 45, 6, 34, 34, 23, 3, 49, 36, 42, 18, 11, 8, 37, 11,
3, 5, 48, 9, 3, 33, 32, 31, 0, 26, 37, 0, 17, 23, 25, 24, 6,
23, 19, 34, 10, 42, 11, 47, 9, 39, 3, 24, 38, 42, 10, 35, 47]), 'd': array([131.08605149, 51.74420745, 1.66581368, 46.91722512,
77.67780947, 188.46976928, 12.75873335, 51.9317436 ,
73.51432203, 134.68513218, 55.02550534, 22.90511577,
66.12316262, 53.63684671, 48.19443761, 31.27235627,
312.18385278, 135.84770113, 14.26382069, 21.69969255,
3.28680039, 183.21446831, 35.23598407, 23.66451326,
147.85480652, 155.43065697, 111.06089767, 82.37885628,
66.52746882, 71.47663897, 123.0787053 , 209.54021272,
60.32194818, 161.35530599, 25.39840502, 151.58787722,
11.72265226, 49.54283589, 70.25908475, 39.50695356,
112.32790207, 171.55547852, 27.11051464, 8.62407388,
109.04711851, 11.25430131, 95.36444665, 5.02231944,
48.31606025, 133.39032998]), 'b': array([ 4.8018808 , -6.4972666 , -11.2077656 , 6.322316 ,
1.33391659, 11.36202025, -5.18315173, 9.64545151,
8.93059413, -2.9619809 , 1.010722 , 10.5460328 ,
6.02832418, 13.15619153, 7.92816087, 22.2140083 ,
20.64277678, 25.26559419, 18.93012033, -3.62283088,
29.90723646, 8.2618424 , 8.1226306 , 24.55220778,
24.73672481, 35.29148044, 19.39618445, 20.81129384,
26.1046295 , 23.53964929, 46.2580496 , 29.97454235,
17.69996036, 41.7538301 , 32.48260765, 31.30030868,
36.13983623, 36.18332016, 48.92477345, 44.27782523,
57.41677485, 35.53675523, 58.57367953, 49.73629965,
43.15151999, 28.47595654, 52.43563731, 37.8567097 ,
51.49878342, 49.98087623])}
描画されたグラフ。

で、結果は出たのですがこのあたりをもう少し見た方がよさそうですね。
fig, ax = plt.subplots(figsize=(5, 2.7), layout="constrained") ax.scatter("a", "b", c="c", s="d", data=data)
まずpyplot.subplotsから。
figsizeはpyplot.figureにそのまま渡される値で、pyplot.figureでは幅、高さの指定を指しています。
matplotlib.pyplot.subplots — Matplotlib 3.10.7 documentation
matplotlib.pyplot.figure — Matplotlib 3.10.7 documentation
layoutmもpyplot.figureにそのまま渡される値ですね。文字通りレイアウトを指定する引数で、constrained、compressed、tight、none、
そしてLayoutEngineのインスタンスのいずれかを渡せます。デフォルトはnoneでレイアウトエンジンを使いません。
今回は軸の装飾の重なりを避け、軸のサイズを調整するconstrainedレイアウトを使っています。
Constrained layout guide — Matplotlib 3.10.7 documentation
次にAxes.scatter。散布図を描画します。こちらではマーカーや色の調整を行います。
matplotlib.axes.Axes.scatter — Matplotlib 3.10.7 documentation
本来のシグニチャーはこうです。
xes.scatter(x, y, s=None, c=None, *, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, edgecolors=None, colorizer=None, plotnonfinite=False, data=None, **kwargs)
dataを指定した場合、x、y、c、sで指定した値はdataの文字列インデックスを指すことになります。
データはxとyで、マーカーのサイズを調整するのがs、マーカーの色を調整するのがcのようです。
コーディングスタイル
コーディングスタイル。Matplotlibを使う時には、FigureやAxesを明示的に作成してそれらのメソッドを呼び出すオブジェクト指向(OO)スタイルと
pyplotを使ってFigureとAxesを暗黙的に作成・管理してプロットにはpyplot関数を使うスタイルの2つがあります。
Quick start guide / Coding styles
オブジェクト指向スタイル。
oo_style.py
import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 2, 100) fig, ax = plt.subplots(figsize=(5, 2.7), layout="constrained") ax.plot(x, x, label="linear") ax.plot(x, x**2, label="quadratic") ax.plot(x, x**3, label="cubic") ax.set_xlabel("x label") ax.set_ylabel("y label") ax.set_title("Simple Plot") ax.legend() plt.show()
3つのデータを重ね合わせたグラフを作っています。Axes.legendは凡例の表示ですね。
実行。
$ uv run oo_style.py

次はpyplotスタイル。
pyplot_style.py
import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 2, 100) plt.figure(figsize=(5, 2.7), layout="constrained") plt.plot(x, x, label="linear") plt.plot(x, x**2, label="quadatic") plt.plot(x, x**3, label="cubic") plt.xlabel("x label") plt.ylabel("y label") plt.title("Simple Plot") plt.legend() plt.show()
このスタイルには、他のPythonコードや書籍で見かけた覚えがあります。
実行。
$ uv run pyplot_style.py
結果。

Matplotlibのドキュメントでは、オブジェクト指向スタイルとpyplotスタイルの両方を使っています。複雑なプロットや大きなプロジェクトの
一部として再利用することを目的とした関数・スクリプトの場合はオブジェクト指向スタイルを推奨しているようです。
インタラクティブな作業の場合はpyplotスタイルが便利としています。
またMatplotlibをGUIアプリケーションに埋め込む際に、pyplotを完全に削除する3つ目のアプローチもあるようです。
長くなってきたので、このあたりで1度区切ります。
おわりに
Pythonのグラフ描画ライブラリー、MatplotlibのQuick start guideをやってみました。
まだ半分くらいなのですが、なんとなく雰囲気がわかってきた気がします。このまま後半もやってみましょう。
Pythonのグラフ描画ライブラリー、MatplotlibのQuick start guideをやってみる(後編) - CLOVER🍀