はじめに
インストールと最初のプロット
Matplotlib が Python プロットの基盤です。pyplot が状態ベースのインターフェースです(MATLAB のように)。スクリプトで図を描画するには必ず plt.show() を呼び、Jupyter ノートブックではセルが終わると自動で図が描画されます。
# install
pip install matplotlib
import matplotlib.pyplot as plt
import numpy as np
# a simple line plot
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.title("Sine Wave")
plt.xlabel("x")
plt.ylabel("sin(x)")
plt.show()pyplot の状態インターフェース
pyplot インターフェースが MATLAB を反映します:各呼び出しが、内部で追跡されている「現在の」figure/axes 上で動きます。素早いプロットには簡潔ですが、複数のサブプロットでは混乱し得ます。現在の figure/axes オブジェクトへのアクセスには plt.gcf()/plt.gca() を使いましょう。
import matplotlib.pyplot as plt
# pyplot tracks the "current" figure and axes
plt.figure() # create a new figure
plt.plot([1, 2, 3], [4, 5, 2])
plt.title("State-based") # applies to the current axes
plt.xlim(0, 4)
plt.ylim(0, 6)
plt.show()
# plt.gcf() -> current figure, plt.gca() -> current axes
print(plt.gca())Figure と Axes(OO インターフェース)
オブジェクト指向(OO)インターフェースが、単一のプロットを超えるすべてに推奨されるアプローチです。Figure(キャンバス全体)と 1 つ以上の Axes(個々のプロット)を作り、それらへメソッドを呼びます。サブプロット、二重軸、複雑なレイアウトへきれいにスケールします。
import matplotlib.pyplot as plt
import numpy as np
# object-oriented interface: explicit Figure and Axes objects
fig, ax = plt.subplots() # fig is the canvas, ax is a single Axes
x = np.linspace(0, 5, 50)
ax.plot(x, x**2, label="x^2")
ax.plot(x, x**3, label="x^3")
ax.set_title("OO Interface")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.legend()
plt.show()よくあるインポートと慣例
pyplot のほぼ普遍的な別名が plt で、NumPy は np です — ほとんどすべてのチュートリアルとライブラリがこれを期待します。rcParams がグローバルの設定辞書です:DPI、フォントサイズ、figure サイズ、その他多くのデフォルトを確定させるため、スクリプトの先頭で一度設定しましょう。
# the universal alias
import matplotlib.pyplot as plt
import numpy as np
# for the OO interface you often see
from matplotlib.figure import Figure
from matplotlib.axes import Axes
# set a global style once
plt.rcParams["figure.dpi"] = 100
plt.rcParams["font.size"] = 11
# inline backend in Jupyter (not needed in scripts)
# %matplotlib inlineバックエンドと plt.show()
figure を描画するのがバックエンドです:インタラクティブなバックエンド(TkAgg、Qt5Agg)がウィンドウを開き、非インタラクティブなもの(Agg)はファイルへ書くだけです。pyplot のインポートの前に matplotlib.use() を呼びましょう。plt.show() はスクリプトで、ウィンドウが閉じるまでブロックし、Jupyter では %matplotlib inline が図をノートブックに埋め込みます。
import matplotlib
# list available backends
print(matplotlib.rcsetup.all_backends)
# force a backend (do this BEFORE importing pyplot)
# matplotlib.use("Agg") # non-interactive, for saving files
# matplotlib.use("TkAgg") # interactive Tk window
import matplotlib.pyplot as plt
plt.plot([1, 2, 3])
# plt.show() blocks until the window is closed
plt.savefig("out.png") # saving works without any GUI backend折れ線グラフ(plot)
基本の折れ線グラフ
plt.plot(x, y) が、順番に (x, y) の点を結ぶ線を描きます。配列を 1 つ渡すと y として使われ、x は 0..N-1 がデフォルトです。グリッド線の切り替えが plt.grid(True) です。点は配列の順に結ばれるため、滑らかな曲線には先に x をソートしましょう。
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.5)
y = x * 2
plt.plot(x, y)
plt.title("y = 2x")
plt.xlabel("x")
plt.ylabel("y")
plt.grid(True)
plt.show()複数の折れ線
各 plt.plot() の呼び出しが現在の axes へ新しい線を加え、カラーのサイクルを自動的に進めます。plt.legend() が識別できるよう、それぞれに label= を渡しましょう。軸の範囲は Matplotlib が自動処理し、最大の範囲に合わせて拡張します。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2 * np.pi, 100)
plt.plot(x, np.sin(x), label="sin")
plt.plot(x, np.cos(x), label="cos")
plt.plot(x, np.sin(x) + np.cos(x), label="sin+cos")
plt.legend()
plt.title("Trig Functions")
plt.show()線のスタイルとマーカー
'色+マーカー+線種' の形式文字列(例:'ro--')はコンパクトですが暗号めいています。読みやすいコードのため、明示的な color=、marker=、linestyle= のキーワード引数を推奨します。よくある線種:'-' '--' ':' '-.'。よくあるマーカー:'o' 's' '^' 'D' 'v' '+' 'x'。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 5, 20)
# format string: [color][marker][linestyle]
plt.plot(x, x, "r-") # red solid line
plt.plot(x, x*2, "go--") # green circles, dashed
plt.plot(x, x*3, "bs:") # blue squares, dotted
plt.plot(x, x*4, "k^-.") # black triangles, dash-dot
# explicit kwargs (clearer, recommended)
plt.plot(x, x*5, color="purple", marker="D",
linestyle="-.", linewidth=2, markersize=6)色
Matplotlib が受け付ける色の形式は多くあります:名前('red')、hex 文字列('#FF8800')、RGB(A) タプル、Tableau の名前('tab:blue')、サイクルの参照('C0'..'C9')、グレースケール文字列('0.5')。'C0' が現在のスタイルの最初の色を選び、プロットがカラーサイクルと一致し続けます。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 1, 30)
plt.plot(x, x, color="red") # named color
plt.plot(x, x+0.2, color="#FF8800") # hex RGB
plt.plot(x, x+0.4, color=(0.1, 0.8, 0.2))# RGB tuple 0-1
plt.plot(x, x+0.6, color="C0") # cycle color 0
plt.plot(x, x+0.8, color="tab:purple") # Tableau palette
# gray shorthand: a string of float in [0,1]
plt.plot(x, x+1.0, color="0.5") # mid gray
plt.show()線の幅、Alpha、zorder
linewidth が線の太さを制御します(デフォルト 1.5)。透明度の設定が alpha で、曲線が重なる時に、下にあるものが見えるようにするのに不可欠です。重ね方の制御が zorder で — 値が高いほど後(上面)に描かれます。デフォルトの zorder は、線が 2、patches が 1 です。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
# alpha = transparency (0 invisible, 1 opaque)
# zorder = draw order; higher draws on top
plt.fill_between(x, np.sin(x), alpha=0.3, zorder=1)
plt.plot(x, np.sin(x), linewidth=2, zorder=2)
plt.plot(x, np.cos(x), linewidth=4, alpha=0.7, zorder=3)
plt.show()Step と Stairs プロット
plt.step() が、デジタル信号や離散データに有用なステップ関数を描きます。ステップが立ち上がる場所の制御が where です('pre'、'post'、'mid')。モダンな等価物が plt.stairs()(3.4+)で、y の値と独立したビンの境界を受け取り、ヒストグラム風のデータとよく連携します。
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(5)
y = [1, 3, 2, 4, 3]
# step: like plot but with horizontal/vertical steps
plt.step(x, y, where="post", label="post")
plt.step(x, y + 1, where="mid", label="mid")
plt.step(x, y + 2, where="pre", label="pre")
plt.legend(title="where=")
# stairs (matplotlib 3.4+): step from explicit bin edges
plt.stairs([1, 2, 1], baseline=0)
plt.show()散布図
基本の散布図
plt.scatter(x, y) が接続線なしで点をプロットします。数万の点があるとき、plt.plot(x, y, 'o') より遅いです。scatter は各点に独自のサイズと色を持たせられるからです。一様なスタイリングで最大速度を得るには、マーカー付きの plt.plot を使いましょう。
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(0)
x = rng.random(50)
y = rng.random(50)
plt.scatter(x, y)
plt.title("Basic Scatter")
plt.xlabel("x")
plt.ylabel("y")
plt.axis("equal") # equal aspect ratio
plt.show()マーカーのサイズと色
s 引数がマーカーの「面積」です(ポイント二乗。半径ではありません)。そのため s が 4 倍大きいのは半径では 2 倍です。数値配列をカラーマップへマッピングするのが、cmap 付きの c(色)引数です。密度が見えるよう、点が重なるときは alpha < 1 を使いましょう。
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(1)
n = 50
x = rng.random(n)
y = rng.random(n)
sizes = rng.random(n) * 500 # area in points^2
colors = rng.random(n) # mapped to colormap
plt.scatter(x, y, s=sizes, c=colors, cmap="viridis", alpha=0.6)
plt.colorbar(label="value")
plt.title("Bubble Chart")
plt.show()カラーマップ散布図
c へ 1 次元配列を渡すと、各点がカラーマップへマッピングされます。カラーバーの追加が plt.colorbar(sc) で(マッピングを colorbar が知るよう、scatter の戻り値を必ず渡しましょう)。カラーマップの範囲の固定が vmin/vmax です。なければ matplotlib がデータの min/max へ自動スケールします。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 200)
y = np.sin(x)
c = x # color by x value
sc = plt.scatter(x, y, c=c, cmap="plasma", vmin=0, vmax=10)
cb = plt.colorbar(sc)
cb.set_label("x position")
plt.title("Colored by x")
plt.show()透明度と過剰プロット
重なり合う点が多いと、塗りつぶしの散布図が密度を隠します。構造を明らかにするには、alpha を約 0.05 に下げ、マーカーを縮めましょう。非常に大きなデータ(10 万点以上)では、plt.hexbin や plt.hist2d がビンへ集約し、素の scatter より速く明快です。
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(2)
n = 5000
x = rng.normal(0, 1, n)
y = rng.normal(0, 1, n)
# dense scatter: low alpha reveals density
plt.scatter(x, y, s=5, alpha=0.05, c="navy")
plt.title("Density via alpha")
# alternative: hexbin for very large datasets
plt.figure()
plt.hexbin(x, y, gridsize=40, cmap="Blues")
plt.colorbar(label="count")
plt.show()カテゴリ散布図
Matplotlib には組み込みの strip プロットがないため、x 軸上の手動の jitter 付き scatter が標準の DIY アプローチです。出版品質のカテゴリプロット(box、violin、swarm)には、Matplotlib の上に構築され plt のスタイリングと統合される Seaborn を推奨します。
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(3)
groups = ["A", "B", "C"]
data = [rng.normal(0, 1, 30),
rng.normal(2, 1, 30),
rng.normal(1, 1.5, 30)]
for i, d in enumerate(data):
# add jitter on x so points do not stack on one line
jitter = rng.uniform(-0.1, 0.1, len(d))
plt.scatter(np.full(len(d), i) + jitter, d, label=groups[i])
plt.xticks(range(len(groups)), groups)
plt.legend()
plt.show()棒グラフ
縦棒グラフ
plt.bar(x, height) が縦棒を描きます。x は文字列(カテゴリ)でも構いません。戻り値の BarContainer で、個々のバーへの注釈や再着色が可能です。各バーへラベルを付けるループが plt.text() で — ラベルがバーのすぐ上に置かれるよう、ha/va('center'/'bottom')と y オフセットを調整しましょう。
import matplotlib.pyplot as plt
categories = ["Apple", "Banana", "Cherry", "Date"]
values = [25, 40, 30, 15]
bars = plt.bar(categories, values, color="tab:blue", edgecolor="black")
# annotate each bar with its value
for bar, v in zip(bars, values):
plt.text(bar.get_x() + bar.get_width()/2, v + 1,
str(v), ha="center", va="bottom")
plt.title("Fruit Sales")
plt.ylabel("units sold")
plt.ylim(0, 50)
plt.show()横棒グラフ
plt.barh(y, width) が横棒を描きます — 縦グラフでは重なり合う長いカテゴリラベルに理想的です。最初の項 目が上に現れるよう ax.invert_yaxis() を呼び、人々がリストを読むやり方に合わせましょう。width のデフォルトは 0.8 です。
import matplotlib.pyplot as plt
items = ["Reading", "Coding", "Sleep", "Exercise"]
hours = [2, 6, 8, 1]
plt.barh(items, hours, color="tab:green")
plt.xlabel("hours per day")
plt.title("Daily Activities")
# invert so the first item appears at the top
plt.gca().invert_yaxis()
plt.show()グループ化された棒グラフ
グループ化されたバーは、x 位置をバー幅の半分ずらすことで、2 つ(以上)の系列を並べます。フラッシュに置くパターンが x +/- w/2 と width w です。計算が機能するよう、数値の x 位置には np.arange を使い、その後 plt.xticks でラベルを付け直しましょう。
import matplotlib.pyplot as plt
import numpy as np
labels = ["Q1", "Q2", "Q3", "Q4"]
a = [20, 35, 30, 35]
b = [25, 32, 34, 20]
x = np.arange(len(labels))
w = 0.35
plt.bar(x - w/2, a, w, label="2023")
plt.bar(x + w/2, b, w, label="2024")
plt.xticks(x, labels)
plt.ylabel("revenue")
plt.legend()
plt.show()積み上げ棒グラフ
積み上げバーは bottom= 引数を使います:各系列が、前の系列が終わった所から始まります。3 系列以上では累積させましょう:bottom = [m+w for m, w in zip(men, women)]。積み上げバーは合計と構成を示せますが、上の系列のカテゴリ間比較は難しくなります。
import matplotlib.pyplot as plt
import numpy as np
labels = ["A", "B", "C"]
men = [20, 35, 30]
women = [25, 32, 34]
plt.bar(labels, men, label="Men")
plt.bar(labels, women, bottom=men, label="Women")
plt.legend()
plt.title("Stacked Bars")
plt.show()誤差バー付きの棒
縦の誤差バーを加えるのが yerr 引数で、端のキャップの長さを設定するのが capsize です。バーのスタイリングには error_kw を渡しましょう。非対称な誤差は yerr=[lower_errors, upper_errors] を渡します。これは barh(xerr)や plt.errorbar でも機能します。
import matplotlib.pyplot as plt
import numpy as np
labels = ["A", "B", "C"]
means = [20, 35, 30]
errors = [2, 4, 3]
plt.bar(labels, means, yerr=errors, capsize=6,
color="tab:orange", edgecolor="black",
error_kw={"ecolor": "black", "linewidth": 1.5})
plt.title("Bar with Error Bars")
plt.ylabel("mean value")
plt.show()ヒストグラム
基本のヒストグラム
plt.hist(x) がデータをビン分けしバーを描きます。bins は整数(ビン数)か明示的な境界のシーケンスにできます。デフォルトではカウントを返すため、y 軸が頻度です。戻り値は (counts, bin_edges, patches) で、さらなるカスタマイズに使えます。
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(0)
data = rng.normal(0, 1, 1000)
plt.hist(data, bins=30)
plt.title("Histogram")
plt.xlabel("value")
plt.ylabel("frequency")
plt.show()ビンの選択
ビンの選択がヒストグラムの見た目を劇的に変えます。'auto' が Sturges と Freedman-Diaconis の規則の最大を使います — 理にかなったデフォルトです。完全な制御と dataset をまたぐ比較可能なビンのために、明示的な境界配列を渡しましょう。ビンが少なすぎると構造が隠れ、多すぎるとノイズが加わります。
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(1)
data = rng.normal(0, 1, 1000)
# auto bin selection (Freedman-Diaconis, Sturges, etc.)
plt.hist(data, bins="auto", alpha=0.5, label="auto")
plt.hist(data, bins=10, alpha=0.5, label="10 bins")
plt.hist(data, bins=np.arange(-4, 4, 0.25),
alpha=0.5, label="0.25 width")
plt.legend()
plt.show()複数のヒストグラム
重なるヒストグラムには、両方の分布が見えるよう alpha < 1 が必要で、はっきり違う色を使いましょう。3 グループ以上では、stacked=True が雑然さを避けますが比較を難しくします。ヒストグラムよりきれいに重なる、滑らかな密度曲線のためには、kdeplot(Seaborn)を検討しましょう。
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(2)
a = rng.normal(0, 1, 1000)
b = rng.normal(1, 1.2, 1000)
plt.hist(a, bins=30, alpha=0.6, label="A", color="tab:blue")
plt.hist(b, bins=30, alpha=0.6, label="B", color="tab:orange")
plt.legend()
plt.show()
# stacked alternative
plt.figure()
plt.hist([a, b], bins=30, stacked=True, label=["A", "B"])
plt.legend()
plt.show()密度 / 正規化
density=True がカウントを(合計 * ビン幅)で割り、バーの面積の合計が 1 になる確率密度を作り ます。これで、ヒストグラムが異なるサンプルサイズ間で比較可能になり、理論的な PDF を重ねられます。個々のサンプルの重み付けには weights= を使いましょう。
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(3)
data = rng.normal(0, 1, 1000)
# density=True normalizes the area to 1 (PDF)
plt.hist(data, bins=30, density=True, alpha=0.6)
# overlay the theoretical PDF
from scipy.stats import norm
xs = np.linspace(-4, 4, 200)
plt.plot(xs, norm.pdf(xs), "r-", lw=2)
plt.title("Normalized Histogram + PDF")
plt.show()2D ヒストグラム
plt.hist2d が 2 変数を 2 次元グリッドへビン分けし、各セルをカウントで色付けします — 密なデータのための、散布図の離散的な親戚です。より滑らかな出力には plt.hexbin(六角形のビン)を使いましょう。どちらも cmap を受け付け、colorbar へ渡せる値を返します。
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(4)
x = rng.normal(0, 1, 10000)
y = x + rng.normal(0, 1, 10000)
plt.hist2d(x, y, bins=40, cmap="Blues")
plt.colorbar(label="count")
plt.title("2D Histogram")
plt.xlabel("x")
plt.ylabel("y")
plt.show()円グラフ
基本の円グラフ
plt.pie(x, labels) が、x の値から円を描きます。パーセンテージラベルの整形が autopct です(printf 風の文字列か関数)。最初のくさびの始まりの回転が startangle です。円が楕円ではなく真の円になるよう、常に plt.axis('equal') を呼びましょう。
import matplotlib.pyplot as plt
labels = ["Rent", "Food", "Transport", "Fun"]
sizes = [1200, 600, 300, 400]
plt.pie(sizes, labels=labels, autopct="%1.1f%%", startangle=90)
plt.title("Monthly Budget")
plt.axis("equal") # circle, not ellipse
plt.show()Explode と影
explode が sizes と同じ長さのタプルです。各値が、そのくさびを中心から外側へずらします(0 = ずらしなし)。深みのためのドロップシャドウを加えるのが shadow=True です。1 つのスライスのハイライトのため、explode は控えめに使いましょう — すべて のくさびの過剰な explode は雑然として見えます。
import matplotlib.pyplot as plt
labels = ["A", "B", "C", "D"]
sizes = [30, 25, 25, 20]
explode = (0, 0.1, 0, 0) # pull the 2nd wedge out
plt.pie(sizes, labels=labels, explode=explode,
shadow=True, autopct="%1.0f%%",
startangle=140)
plt.title("Exploded Pie")
plt.show()ドーナツチャート
ドーナツは穴のある円です:フルのくさびの代わりにリングを描くには、wedgeprops={'width': 0.4} を設定しましょう。中央の穴には、plt.text(0, 0, ...) 経由でサマリーラベルが入れられます。ドーナツが円より読みやすいのは一般に、リングの長さがくさびの角度より値をよく符号化するためです。
import matplotlib.pyplot as plt
labels = ["A", "B", "C"]
sizes = [40, 35, 25]
wedges, texts = plt.pie(sizes, labels=labels,
wedgeprops=dict(width=0.4, edgecolor="w"))
plt.title("Donut Chart")
# add center text
plt.text(0, 0, "Total\n100", ha="center", va="center", fontsize=14)
plt.show()パーセンテージと開始角度
autopct は、パーセンテージを受け取り文字列を返す関数にでき、パーセントと絶対数の両方を表示できます。くさびの方向の制御(上から始まり時計回り — 従来の読みの順序)が、startangle + counterclock=False です。パーセントラベルの配置が pctdistance です。
import matplotlib.pyplot as plt
labels = ["North", "South", "East", "West"]
sizes = [32, 24, 28, 16]
colors = ["#4C72B0", "#DD8452", "#55A868", "#C44E52"]
plt.pie(sizes, labels=labels, colors=colors,
autopct=lambda p: f"{p:.1f}%\n({p*sum(sizes)/100:.0f})",
startangle=90, counterclock=False,
pctdistance=0.75)
plt.show()ネストした円グラフ(同心円)
異なる radius と width の値を持つ 2 つの plt.pie 呼び出しが、同心円のリングを作ります — 単純な「サンバースト」です。通常、外側のリングがトップレベルのカテゴリを示し、内側のリングがその内訳を示します。内側の半径は小さく保ち、くさびを視覚的に分離するため edgecolor='w' を加えましょう。
import matplotlib.pyplot as plt
# outer ring: regions, inner ring: sub-categories
outer = [40, 30, 30]
inner = [20, 20, 15, 15, 25, 5]
outer_labels = ["A", "B", "C"]
inner_labels = ["A1", "A2", "B1", "B2", "C1", "C2"]
plt.pie(outer, labels=outer_labels, radius=1.0,
wedgeprops=dict(width=0.3, edgecolor="w"))
plt.pie(inner, labels=inner_labels, radius=0.7,
wedgeprops=dict(width=0.3, edgecolor="w"))
plt.title("Nested Pie")
plt.show()サブプロットとレイアウト
plt.subplot
plt.subplot(rows, cols, index) が、グリッド内の(1 起点の)axes を選択します — レガシーな MATLAB 風の方法です。インデックスは左から右、上から下に進みます。これが「現在の axes」を書き換えるため、以後の plt 呼び出しがそこへ描きます。新規コードには plt.subplots() を推奨します — よりきれいで、本物の Axes オブジェクトを返します。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 5, 50)
# subplot(nrows, ncols, index) -- 1-indexed!
plt.subplot(2, 2, 1)
plt.plot(x, x)
plt.subplot(2, 2, 2)
plt.plot(x, x**2)
plt.subplot(2, 2, 3)
plt.plot(x, x**3)
plt.subplot(2, 2, 4)
plt.plot(x, np.sin(x))
plt.tight_layout()
plt.show()plt.subplots
plt.subplots(nrows, ncols) が (fig, axes) を返します。axes は Axes の NumPy 配列で、axes[row, col] のようにインデックスします。目盛りを整列させスペースを節約するのが sharex/sharey です。すべてのサブプロットの上に figure レベルのタイトルを設定するのが fig.suptitle() です。ラベルの重なりを避けるため、必ず plt.tight_layout() を呼びましょう。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 100)
# one figure, 2x2 grid of Axes, shared x and y
fig, axes = plt.subplots(2, 2, figsize=(8, 6),
sharex=True, sharey=True)
axes[0, 0].plot(x, np.sin(x)); axes[0, 0].set_title("sin")
axes[0, 1].plot(x, np.cos(x)); axes[0, 1].set_title("cos")
axes[1, 0].plot(x, np.tan(x)); axes[1, 0].set_title("tan")
axes[1, 1].plot(x, -np.sin(x)); axes[1, 1].set_title("-sin")
fig.suptitle("Trig Family")
plt.tight_layout()
plt.show()GridSpec
GridSpec がサブプロットのサイズを完全に制御します — スライス でセルをマージできます(gs[0, :] = 行全体、gs[1:, 2] = 高い右列)。サイズの異なる列/行は width_ratios/height_ratios で作れます。これが、複雑なダッシュボードの標準的な道具です。
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
fig = plt.figure(figsize=(8, 6))
gs = gridspec.GridSpec(3, 3, figure=fig)
ax1 = fig.add_subplot(gs[0, :]) # full top row
ax2 = fig.add_subplot(gs[1, :2]) # middle, left 2 cols
ax3 = fig.add_subplot(gs[1:, 2]) # right, spans 2 rows
ax4 = fig.add_subplot(gs[2, 0:2]) # bottom-left
ax1.set_title("wide top")
ax3.set_title("tall right")
plt.tight_layout()
plt.show()軸の共有
sharex=True(または sharey=True)が axes をリンクし、1 つのパン/ズームが他を更新します — 積み重ねた時系列に最適です。内側の axes の冗長な目盛りラベルも隠します。共有のグループには ax.get_shared_x_axes() 経由でアクセスでき、グループから axes を外せば切り離せます。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
ax1.plot(x, np.sin(x))
ax2.plot(x, np.cos(x))
# zooming on one now zooms both
ax1.set_xlim(0, 5)
# decouple later if needed
# ax2.get_shared_x_axes().remove(ax2)
fig.suptitle("Shared x-axis")
plt.show()Tight Layout と Constrained
tight_layout() が、ラベルの重なりを防ぐため間隔を一度調整しますが、fig.suptitle を知りません — スペースを確保するには rect を渡しましょう。描画のたびに再計算し、suptitle とカラーバーを正しく扱うモダンな代替が、layout='constrained'(または fig=Figure(layout='constrained'))で、新規コードには推奨です。
import matplotlib.pyplot as plt
# tight_layout: simple, adjusts subplot spacing
fig, axes = plt.subplots(2, 2)
for ax in axes.flat:
ax.set_xlabel("x label")
ax.set_ylabel("y label")
ax.set_title("a title")
fig.suptitle("tight_layout")
plt.tight_layout()
# leave room for suptitle
plt.tight_layout(rect=[0, 0, 1, 0.95])
plt.show()
# constrained_layout: recomputes on every draw (more robust)
fig, axes = plt.subplots(2, 2, layout="constrained")
fig.suptitle("constrained_layout")
plt.show()凡例と注釈
基本の凡例
plt.legend() が、プロットされた各 artist からラベルを集めます。axes 内の位置の設定が loc です('upper right'、'lower left'、'best' など)。外部の凡例のためには、bbox_to_anchor=(x, y)(axes 分数の座標)と loc を組み合わせ、凡例ボックスのその角をその点へアンカーさせましょう。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 1, 30)
plt.plot(x, x, label="linear")
plt.plot(x, x**2, label="quadratic")
plt.plot(x, x**3, label="cubic")
plt.legend()
plt.show()
# legend outside the axes
plt.figure()
plt.plot(x, x, label="linear")
plt.plot(x, x**2, label="quadratic")
plt.legend(loc="upper left", bbox_to_anchor=(1, 1))
plt.tight_layout()
plt.show()凡例の位置と列
凡例の項目を複数の列に並べるのが ncol です — 短いラベルが多いとき有用です。凡例ボックスの見た目の制御が、frameon/framealpha/fancybox です。見出しの追加が title です。罫線のない見た目は frameon=False で、出版物ではしばしばよりきれいに見えます。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 1, 30)
for i in range(1, 6):
plt.plot(x, x**i, label=f"x^{i}")
plt.legend(loc="upper center", ncol=3, fontsize=9,
frameon=True, framealpha=0.9,
title="Powers", title_fontsize=10)
plt.title("Custom Legend")
plt.show()ポイントへの注釈
ax.annotate(text, xy, xytext) が、xytext にテキストを置き、(省略可能で)xy へ矢印を引きます。xy はデフォルトでデータ座標です。矢印のスタイリングの辞書が arrowprops で、最もよくあるのが arrowstyle='->' です。コールアウトには plt.text より annotate がはるかに柔軟です。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
plt.plot(x, y)
# mark and label the maximum
idx = np.argmax(y)
plt.annotate(f"max = {y[idx]:.2f}",
xy=(x[idx], y[idx]), # point to annotate
xytext=(x[idx]-1, 0.5), # text position
arrowprops=dict(arrowstyle="->"))
plt.show()矢印付きの注釈
コネクタのスタイリングが arrowprops です:arrowstyle('->'、'-|>'、'<->')、color、lw。矢印を曲げる のが connectionstyle で — 'arc3,rad=0.3' が曲げ、'angle3' が直角の肘を作り、'bar' が T バーを加えます。これらで、曲線に重ならずデータの周りを回る明快なコールアウトが構築できます。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 100)
plt.plot(x, x**3 - 3*x)
plt.annotate("local min", xy=(1, -2), xytext=(2, -10),
arrowprops=dict(arrowstyle="->", color="red",
lw=2, connectionstyle="arc3,rad=0.3"))
plt.annotate("local max", xy=(-1, 2), xytext=(-3, 8),
arrowprops=dict(arrowstyle="-|>", color="blue",
connectionstyle="angle3"))
plt.show()カスタム凡例のハンドル
デフォルトの凡例(プロットされた artist から構築される)が望むものでないとき、Line2D、Patch、データなしの Line2D で自分のハンドルを構築し、handles= を legend() へ渡しましょう。1 つのキーに線、パッチ、散布図のマーカーを組み合わせる凡例には、これが不可欠です。
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from matplotlib.patches import Patch
plt.plot([1, 2, 3], [1, 4, 9], "o-", color="tab:blue")
plt.plot([1, 2, 3], [1, 8, 27], "s--", color="tab:orange")
custom = [
Line2D([0], [0], color="tab:blue", marker="o", label="squared"),
Line2D([0], [0], color="tab:orange", marker="s", ls="--", label="cubed"),
Patch(facecolor="gray", label="reference band"),
]
plt.legend(handles=custom)
plt.show()スタイル、色、rcParams
組み込みスタイル
プリセットの見た目をグローバルに適用するのが plt.style.use(name) で、with ブロック内で一時的に適用するのが plt.style.context(name) です。人気のスタイルには 'ggplot'、'seaborn-v0_8-*'、'bmh'、'fivethirtyeight' があります。注意:Seaborn のスタイルは Matplotlib 3.6+ で '-v0_8' 接尾辞付きへ改名されました。
import matplotlib.pyplot as plt
# list all available styles
print(plt.style.available)
# use a style globally
plt.style.use("seaborn-v0_8-whitegrid")
# or as a context manager (temporary)
with plt.style.context("dark_background"):
plt.figure()
plt.plot([1, 2, 3], [1, 4, 9])
plt.title("dark")
plt.show()
plt.plot([1, 2, 3], [9, 4, 1])
plt.title("default again")
plt.show()カラーマップ
カラーマップには 3 つのファミリーがあります:順序付けられた 0..N のデータのための sequential(viridis、plasma)、意味のある中間点を持つデータのための diverging(coolwarm、RdBu。0 を中心に vmin/vmax と共に使う)、異なるカテゴリのための qualitative(Set2、tab10)です。知覚的に一様な viridis のようなマップを推奨します — 色覚多様性に安全で、印刷でも読めます。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
# sequential, diverging, qualitative
for cmap in ["viridis", "plasma", "coolwarm", "RdBu", "Set2"]:
plt.scatter(x, y, c=x, cmap=cmap, label=cmap)
plt.colorbar(label=cmap)
plt.title(cmap)
plt.show()カスタムカラーサイクル
線を加えるにつれ循環するプロパティのシーケンスを定義するのが、axes.prop_cycle(cycler オブジェクト)です。color、linestyle、marker なども循環できます — 同時に両方を進めるには、cycler(color=[...]) + cycler(linestyle=[...]) を組み合わせましょう。これで、すべてのプロットが一貫したブランドのパレットを得ます。
import matplotlib.pyplot as plt
from cycler import cycler
# set the default color cycle for new axes
plt.rcParams["axes.prop_cycle"] = cycler(
color=["#e41a1c", "#377eb8", "#4daf4a", "#984ea3", "#ff7f00"])
for i in range(1, 6):
plt.plot([0, 1, 2], [i]*3, label=f"line {i}", lw=4)
plt.legend()
plt.title("Custom Cycle")
plt.show()rcParams
すべてのデフォルトを制御するマスター設定辞書が rcParams です — figure サイズ、DPI、フォント、線の幅、グリッド、savefig のオプション。一貫した出力のため、スクリプトの先頭で一度設定しましょう。いくつかを一度に設定するのが plt.rcParams.update({...}) です。デフォルトを恒久化するには、mpl.rcParamsFile か matplotlibrc ファイルを使いましょう。
import matplotlib.pyplot as plt
import matplotlib as mpl
# read / set individual parameters
mpl.rcParams["figure.figsize"] = (8, 4)
mpl.rcParams["figure.dpi"] = 100
mpl.rcParams["font.size"] = 12
mpl.rcParams["axes.grid"] = True
mpl.rcParams["axes.grid.which"] = "both"
mpl.rcParams["savefig.bbox"] = "tight"
# update many at once
plt.rcParams.update({
"axes.titlesize": "large",
"axes.labelsize": "medium",
"lines.linewidth": 2,
})
plt.plot([1, 2, 3])
plt.title("Configured Defaults")
plt.show()色の形式
matplotlib.colors が、変換(to_hex、to_rgb)、名前付き色のリスト、カラーマップの構築を提供します。少数のアンカー色から連続的なカラーマップを構築するのが、LinearSegmentedColormap.from_list です。カテゴリのカスタムマップには ListedColormap(['#aaa', '#bbb', ...]) を使いましょう。これらで、ブランドのパレットに正確に一致させられます。
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
# all named colors
print(list(mcolors.CSS4_COLORS)[:5])
# convert between formats
print(mcolors.to_hex((0.1, 0.2, 0.5))) # #1a3380
print(mcolors.to_rgb("#ff8800")) # (1.0, 0.533, 0.0)
# make a custom colormap from a list of colors
cmap = mcolors.LinearSegmentedColormap.from_list(
"rg", ["red", "yellow", "green"])
import numpy as np
plt.imshow(np.linspace(0, 1, 256).reshape(1, -1),
cmap=cmap, aspect="auto")
plt.title("Custom Colormap")
plt.show()軸の設定
範囲(xlim / ylim)
可視のデータ範囲の設定が plt.xlim/plt.ylim(または ax.set_xlim/ax.set_ylim)です。None を渡すと、その範囲が自動スケールに委ねられます(例:set_ylim(None, 5) は上端だけを固定)。ハードな上限ではなく、データ範囲の分数としてパディングを加えるのが plt.margins() です。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x))
# set explicit limits
plt.xlim(2, 8)
plt.ylim(-1.5, 1.5)
# or autoscale with margin
# plt.margins(x=0.05, y=0.1)
# query current limits
print(plt.xlim()) # (2.0, 8.0)
plt.show()Ticks
目盛りが現れる場所の設定が plt.xticks(positions) で、テキストも設定するのが plt.xticks(positions, labels) です。完全に目盛りを隠すには空のリストを渡しましょう。数値の軸では通常、MaxNLocator に目盛りを自動選択させ、カテゴリや記号的な軸(pi の倍数など)だけを上書きします。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x))
# set tick positions
plt.xticks([0, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi])
# set positions AND labels
plt.xticks([0, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi],
["0", "pi/2", "pi", "3pi/2", "2pi"])
# turn off ticks
# plt.xticks([])
plt.show()目盛りの整形
精密な制御を与えるのが ticker モジュールです:目盛りがどこへ行くか決めるのが Locators(N 単位ごとは MultipleLocator、最大 N 個は MaxNLocator、log 軸には LogLocator)で、ラベルのテキストを決めるのが Formatters です(printf 風は FormatStrFormatter、任意の関数は FuncFormatter)。細かいグリッド線には minor のロケータを使いましょう。
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MultipleLocator, FormatStrFormatter, FuncFormatter
x = np.linspace(0, 5, 100)
plt.plot(x, x**2)
ax = plt.gca()
ax.xaxis.set_major_locator(MultipleLocator(1))
ax.xaxis.set_minor_locator(MultipleLocator(0.25))
ax.yaxis.set_major_formatter(FormatStrFormatter("%.0f"))
# format with a function
ax.yaxis.set_major_formatter(
FuncFormatter(lambda v, p: f"{v/1000:.1f}k"))
plt.show()Log スケール
軸を対数に切り替えるのが plt.xscale('log') / plt.yscale('log') です — 桁が大きく変わるデータには不可欠です。ゼロ近傍に線形領域を持つ log スケールが 'symlog' で、負の値も表示できます。major と minor(log 間隔)のグリッド線の両方を示すには、plt.grid(True, which='both') を使いましょう。
import matplotlib.pyplot as plt
import numpy as np
x = np.logspace(0, 4, 50) # 10^0 .. 10^4
plt.plot(x, x**2)
# log both axes
plt.xscale("log")
plt.yscale("log")
# symlog: log scale that handles negative/zero values
# plt.yscale("symlog", linthresh=1)
plt.title("Log-Log Plot")
plt.grid(True, which="both", ls="--", alpha=0.5)
plt.show()アスペクト比と Spines
等しいスケーリングを確保し円が円のままになるようにするのが、ax.set_aspect('equal') です — 幾何と地図には決定的に重要です。軸の罫線が spines で、上/右を隠すこと(「despining」)が、Seaborn が普及させたよりきれいなモダンな見た目です。spines を任意のデータ位置へ動かし、十字軸を作ることもできます。
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
theta = np.linspace(0, 2*np.pi, 100)
ax.plot(np.cos(theta), np.sin(theta))
# equal data units on x and y (a true circle)
ax.set_aspect("equal")
# hide the top and right spines
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
# move the remaining spines to the center for a cross-hair
# ax.spines["left"].set_position(("data", 0))
# ax.spines["bottom"].set_position(("data", 0))
plt.show()テキストと数式
Axes 内のテキスト
デフォルトではデータ座標にテキストを置くのが、ax.text(x, y, s) です。axes 分数の座標(0,0 = 左下、1,1 = 右上)を使うには transform=ax.transAxes を渡し、これがデータの範囲に関係なくラベルを角に固定する方法です。水平/垂直の整列の制御が ha/va です。
import matplotlib.pyplot as plt
plt.plot([0, 1], [0, 1])
# ax.text(x, y, s) -- x, y in data coords
plt.text(0.5, 0.5, "center of plot", ha="center", va="center",
fontsize=14, color="red", rotation=30)
# align to axes fraction instead of data coords
plt.text(0.02, 0.98, "top-left", transform=plt.gca().transAxes,
ha="left", va="top", bbox=dict(boxstyle="round", fc="yellow"))
plt.show()suptitle と figtext
figure 全体にわたるタイトル(すべてのサブプロットの上)を加えるのが fig.suptitle() です。スペースの確保は tight_layout(rect=[...]) で、または layout='constrained' を使いましょう。figure 分数の座標(0,0 = figure の左下)にテキストを置くのが fig.text(x, y, s) で、フッターとソースノートに有用です。
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 2)
axes[0].plot([1, 2, 3])
axes[1].plot([3, 2, 1])
# figure-level title (above all axes)
fig.suptitle("Main Title", fontsize=16, fontweight="bold")
# arbitrary figure-coordinate text
fig.text(0.5, 0.01, "figure footer text", ha="center", fontsize=9)
plt.tight_layout(rect=[0, 0.03, 1, 0.95])
plt.show()LaTeX 数式(mathtext)
Matplotlib には組み込みの mathtext エンジンがあります:LaTeX 風の数式をドル記号($...$)で包み、生の文字列(r"...")を使いましょう。よくあるコマンドが機能します:\frac、\sum、\int、ギリシャ文字 \alpha..\omega、上付き x^2、下付き x_i。外部の LaTeX インストールは不要です。バックスラッシュが Python を生き延びるよう、r 文字列を使いましょう。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 100)
plt.plot(x, np.sin(x))
# mathtext: enclose LaTeX in dollar signs
plt.title(r"$\sin(x)$ vs $x$")
plt.xlabel(r"$x$ (radians)")
plt.ylabel(r"$\sin(x)$")
# fractions, sums, greek letters
plt.text(2, 0.5, r"$\frac{a}{b} + \sum_{i=1}^{n} x_i^2$")
plt.text(2, -0.5, r"$\alpha, \beta, \gamma, \pi, \infty$")
plt.show()テキストのプロパティ
すべてのテキストオブジェクトが、豊かなプロパティのセットを受け付けます:fontsize、fontweight('bold')、fontstyle('italic')、family('serif'/'sans-serif'/'monospace')、color、背景ボックスのための bbox 辞書です。テキストオブジェクトが返されるため、後に書き換えられます(アニメーションやインタラクティブな更新に有用)。
import matplotlib.pyplot as plt
t = plt.text(0.5, 0.5, "Styled Text",
fontsize=18, fontweight="bold",
fontstyle="italic", family="serif",
color="darkblue",
bbox=dict(boxstyle="round,pad=0.5",
facecolor="lightyellow", edgecolor="black"))
# animate or update properties later
t.set_fontsize(24)
t.set_color("crimson")
plt.show()注釈(textcoords)
xytext の解釈を 制御するのが、annotate の textcoords です:'data'(デフォルト、データ単位)、'offset points'(xy に対するポイントの相対 — ラベルを点から押し出すのに最適)、'axes fraction'(axes をまたぐ 0〜1)、'figure fraction'。座標系を混ぜれば、ズームしてもコールアウトが読みやすいまま保たれます。
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [1, 4, 2, 3])
# xy in data coords, xytext in points OFFSET from xy
plt.annotate("offset text", xy=(2, 4),
xytext=(15, 15), textcoords="offset points",
arrowprops=dict(arrowstyle="->"))
# xytext in axes fraction
plt.annotate("axes corner", xy=(2, 4),
xytext=(0.8, 0.8), textcoords="axes fraction",
arrowprops=dict(arrowstyle="-|>"))
plt.show()図の保存
savefig の基本
現在の figure をファイルへ書くのが plt.savefig(path) です。決定的に重要なのは、plt.show() の「前に」呼ぶことです — show() が終了し figure が閉じ・空にされることがあり、後に保存すると空白のファイルになります。形式は拡張子が自動決定します(.png、.pdf、.svg、.jpg)。
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 2])
# save BEFORE plt.show() -- show() clears the figure
plt.savefig("plot.png")
plt.savefig("plot.pdf")
plt.show()形式
目的により形式を選びましょう:画面/Web には PNG、印刷と編集には PDF か SVG(ベクター)— ピクセレーションなしで拡縮するためです。写真風の画像だけに JPG(線とテキストで鮮明さを失います)。要素の少ないプロットでは、ベクター形式がはるかに小さいファイルも作ります。拡張子の上書きは format= で。
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
# raster formats (pixels)
plt.savefig("plot.png") # lossless, default
plt.savefig("plot.jpg", quality=95)
plt.savefig("plot.tiff", dpi=200)
# vector formats (scale without pixelation)
plt.savefig("plot.pdf") # best for publications
plt.savefig("plot.svg") # editable in Inkscape/Illustrator
# explicit format override
plt.savefig("plot.dat", format="png")DPI と解像度
ラスタ出力の解像度を設定するのが DPI(dots per inch)で、ピクセル寸法 = figsize * dpi です。画面には 72〜100 DPI で十分で、印刷には 300+ DPI が必要です。解像度の問題を完全に避けるには、ベクター形式(PDF/SVG)で保存しましょう。スクリプトをまたいで一貫した高解像度の出力のためには、rcParams で savefig.dpi を設定しましょう。
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(6, 4))
ax.plot([1, 2, 3], [1, 4, 9])
# dpi controls pixel density: width_px = figsize[0] * dpi
plt.savefig("low.png", dpi=72) # 432 x 288 px
plt.savefig("high.png", dpi=300) # 1800 x 1200 px
# set a global default DPI
plt.rcParams["savefig.dpi"] = 300
plt.savefig("global.png")bbox_inches と Pad
デフォルトの savefig は figure の長方形へ切り詰めますが、これが縁近くのラベルやタイトルをクリップすることがあります。保存領域をすべての artist を含むよう拡大するのが、bbox_inches='tight' で、その後、周囲に小さいマージンを加えるのが pad_inches です。これがほとんど常に望むもので — rcParams['savefig.bbox']='tight' でデフォルトに設定しましょう。
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
plt.title("With Long Title That Might Be Cut Off")
# tight bbox trims whitespace and keeps labels inside
plt.savefig("tight.png", bbox_inches="tight", pad_inches=0.1)
# trim even more aggressively
plt.savefig("tighter.png", bbox_inches="tight", pad_inches=0)
# preview the tight bounding box
# bbox = plt.savefig("x.png", bbox_inches="tight") # returns a Bbox透明と Facecolor
figure の背景を透過させるのが transparent=True です(PNG の alpha チャネル)— スライドや Web ページ上へのプロットの重ね合わせに理想的です。保存される背景色の設定が facecolor で(画面上の色を上書きします)。axes の背景は、ax.set_facecolor() が別に制御します。レイヤー化されたデザインのために両方を組み合わせましょう。
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 4, 9])
ax.set_facecolor("#f0f0f0")
# transparent background (alpha channel)
plt.savefig("transparent.png", transparent=True)
# explicit figure face color
plt.savefig("colored.png", facecolor="lightblue", edgecolor="none")
# control which elements are saved
plt.savefig("full.png", facecolor=fig.get_facecolor())3D プロット(mplot3d)
3D Axes のセットアップ
3D の axes を作るのが、projection='3d' です(add_subplot 経由か、subplots での subplot_kw)。すべての 2D メソッドが機能し、z 固有のもの(set_zlabel、plot_surface、scatter など)も加わります。3D の対応は mplot3d ツールキット経由で、Matplotlib に同梱され追加インストールは不要です。
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
# add a 3D axes via projection
ax = fig.add_subplot(projection="3d")
# or from subplots
# fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_zlabel("Z")
ax.set_title("3D Axes")
plt.show()3D 散布図
3D の axes 上の ax.scatter(x, y, z) が空間に点をプロットし、s と c の引数が 2D の散布図と同様に機能します。色のマッピングの表示には fig.colorbar(sc) を加えましょう。3D 散布図はクラスタの探索に最適ですが、静的な 3D プロットが深さを隠し得ることに注意しましょう — 対話的に回転するか、1 次元を色で符号化しましょう。
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(0)
n = 200
x = rng.normal(0, 1, n)
y = rng.normal(0, 1, n)
z = rng.normal(0, 1, n)
c = np.sqrt(x**2 + y**2 + z**2)
fig = plt.figure()
ax = fig.add_subplot(projection="3d")
sc = ax.scatter(x, y, z, c=c, cmap="viridis")
fig.colorbar(sc, label="distance from origin")
ax.set_title("3D Scatter")
plt.show()3D サーフェス
色付きのサーフェスを描くのが plot_surface(X, Y, Z) です。X、Y、Z は、np.meshgrid が作る一致する形状の 2 次元配列でなければなりません。スキップするグリッド点数の制御が、rstride/cstride です(低い = より滑らかだが遅い)。Z による着色が cmap で、カラーバーを加えましょう(3D の figure に合わせるには shrink)。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-5, 5, 80)
y = np.linspace(-5, 5, 80)
X, Y = np.meshgrid(x, y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
fig = plt.figure()
ax = fig.add_subplot(projection="3d")
surf = ax.plot_surface(X, Y, Z, cmap="coolwarm",
rstride=1, cstride=1,
linewidth=0, antialiased=True)
fig.colorbar(surf, shrink=0.5, aspect=10)
ax.set_title("3D Surface")
plt.show()3D ワイヤフレームとコンター
グリッド線だけを描くのが plot_wireframe です(フルサーフェスより軽く、構造の表示に良い)。サーフェスの下の平面へ塗りつぶしコンターを投影するのが、zdir='z' と offset 付きの ax.contourf です — よくある「3D の下の 2D」の可視化です。豊かな地形のプロットのため、surface + 投影されたコンターを組み合わせましょう。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 30)
y = np.linspace(-3, 3, 30)
X, Y = np.meshgrid(x, y)
Z = X * np.exp(-X**2 - Y**2)
fig = plt.figure()
ax = fig.add_subplot(projection="3d")
ax.plot_wireframe(X, Y, Z, color="black", rstride=1, cstride=1)
ax.set_title("Wireframe")
# 3D contour (filled) projected at the bottom
fig = plt.figure()
ax = fig.add_subplot(projection="3d")
ax.contourf(X, Y, Z, zdir="z", offset=-0.5, cmap="viridis")
ax.set_title("3D Contour")
plt.show()3D 棒グラフ
位置 (x, y) に、底 z から始まり幅 dx、dy、高さ dz の長方形のバーを描くのが、ax.bar3d(x, y, z, dx, dy, dz) です。3D の感触のための照明を加えるのが shade=True です。meshgrid から始めるときは、座標配列を .ravel() で平坦化しましょう。3D の棒は読みにくくなり得ます — 可能な限りグループ化された 2D の棒を推奨します。
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(projection="3d")
x = np.arange(3)
y = np.arange(3)
X, Y = np.meshgrid(x, y)
X, Y = X.ravel(), Y.ravel()
Z = np.zeros_like(X)
dz = np.array([1, 2, 3, 2, 3, 1, 3, 1, 2])
ax.bar3d(X, Y, Z, dx=0.6, dy=0.6, dz=dz,
shade=True, color="tab:orange")
ax.set_title("3D Bar Chart")
plt.show()コンタープロット
コンター線
Z が一定の等値線を引くのが plt.contour(X, Y, Z) です。X、Y は meshgrid から来ます。コンターの数(または正確な値)の設定が levels で、各線へ値のラベルを付けるのが plt.clabel(cs) です。コンター線は正確ですがまばらです。塗りつぶしの領域には、contourf と組み合わせましょう。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) * np.cos(Y)
# line contours
cs = plt.contour(X, Y, Z, levels=15, colors="black", linewidths=0.8)
plt.clabel(cs, inline=True, fontsize=8)
plt.title("Contour Lines")
plt.colorbar(cs)
plt.show()塗りつぶしコンター
コンターレベルの間の領域を色で満たすのが plt.contourf('f' に注意)で、滑らかなヒートマップ風の見た目を与えます。contour と同様、グリッド化された X、Y、Z が必要です。解像度の制御が levels です。気温、標高、確率密度のような 2 次元のスカラー場を可視化する標準的な方法が、contourf です。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-2, 2, 100)
y = np.linspace(-2, 2, 100)
X, Y = np.meshgrid(x, y)
Z = X**2 + Y**2
cf = plt.contourf(X, Y, Z, levels=20, cmap="viridis")
plt.colorbar(cf, label="Z")
plt.title("Filled Contour")
plt.xlabel("X")
plt.ylabel("Y")
plt.show()コンターのラベル付け(clabel)
コンター線をその Z 値で注釈するのが plt.clabel(cs) で、ラベルに合わせて線を切るのが inline=True です。数値の整形が fmt です('%.2f' か関数)。特定の等値線だけをラベルするには levels=[...] を渡しましょう。ラベル付きのコンターが、カラーバーを要さず正確な値を伝えます。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(x, y)
Z = X * np.exp(-X**2 - Y**2)
cs = plt.contour(X, Y, Z, 10, colors="black")
plt.clabel(cs, inline=True, fontsize=9, fmt="%.2f")
# label only specific levels
# plt.clabel(cs, levels=[-0.1, 0, 0.1])
plt.title("Labeled Contours")
plt.show()カラーバー
カラーキーを加えるのが plt.colorbar(mappable) で — マッピングを知るため、contour/imshow/scatter の戻り値を必ず渡しましょう。カスタマイズは set_label/set_ticks です。サブプロットでは、カラーバーが軸からスペースを奪うことがあります。複数の axes にわたる配置の制御には、ax= 引数か fig.colorbar(mappable, ax=axes) を使いましょう。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 5, 100)
y = np.linspace(0, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) + np.cos(Y)
cf = plt.contourf(X, Y, Z, cmap="RdBu")
# basic colorbar
cb = plt.colorbar(cf)
cb.set_label("Z value")
cb.set_ticks([-2, -1, 0, 1, 2])
# place colorbar with specific size and padding
# cb = plt.colorbar(cf, fraction=0.046, pad=0.04)
plt.title("Colorbar Example")
plt.show()meshgrid と griddata
contour/contourf は、正規のグリッド上のデータを必要とします。まばらなサンプルには、scipy.interpolate.griddata で meshgrid へ補間しましょう(メソッド:'linear'、'nearest'、'cubic')。範囲にわたる meshgrid の便利な省略形が np.mgrid[...] です。元の点を上にプロットすれば、データがまばらな場所が分かります。
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import griddata
# scattered (x, y, z) samples
rng = np.random.default_rng(0)
pts = rng.uniform(-2, 2, (200, 2))
z = np.sin(pts[:,0]) * np.cos(pts[:,1])
# build a regular grid
grid_x, grid_y = np.mgrid[-2:2:100j, -2:2:100j]
# interpolate scattered data onto the grid
grid_z = griddata(pts, z, (grid_x, grid_y), method="cubic")
plt.contourf(grid_x, grid_y, grid_z, levels=20, cmap="plasma")
plt.scatter(pts[:,0], pts[:,1], c="white", s=5, alpha=0.5)
plt.colorbar(label="z")
plt.title("Scattered -> Grid -> Contour")
plt.show()画像の表示(imshow)
imshow の基本
2 次元配列をヒートマップとして、または 3 次元(H, W, 3)の配列を RGB 画像として表示するのが plt.imshow(arr) です。デ フォルトの原点は左上(origin='upper')で、画像の慣例と一致します — 数学的な軸には origin='lower' を設定しましょう。きれいな画像表示のため目盛りを隠すのが plt.axis('off') です。
import matplotlib.pyplot as plt
import numpy as np
# a 2D array is shown as a heatmap (color = value)
rng = np.random.default_rng(0)
img = rng.random((10, 10))
plt.imshow(img, cmap="viridis")
plt.colorbar(label="value")
plt.title("imshow of a 2D array")
plt.show()
# a 3D array (H, W, 3 or 4) is shown as an RGB(A) image
rgb = rng.integers(0, 256, (50, 50, 3), dtype=np.uint8)
plt.imshow(rgb)
plt.axis("off")
plt.title("RGB image")
plt.show()カラーマップとカラーバー
配列のピクセルをデータ座標へマッピングするのが extent=[xmin, xmax, ymin, max] です。なければ imshow がピクセルインデックスを使います。行 0 を下に置くのが origin='lower' です(数学の慣例)。画像を axes を満たすよう引き伸ばすのが aspect='auto' で、デフォルトの 'equal' が正方形のピクセルを保ちます。カラーバーへは画像オブジェクトを渡しましょう。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 200)
y = np.linspace(-3, 3, 200)
X, Y = np.meshgrid(x, y)
Z = np.sin(X**2 + Y**2) / (X**2 + Y**2 + 1)
im = plt.imshow(Z, extent=[-3, 3, -3, 3], origin="lower",
cmap="RdBu", aspect="auto")
cb = plt.colorbar(im)
cb.set_label("intensity")
plt.title("imshow with extent")
plt.show()補間
拡大時にピクセルがどう混ぜられるかの制御が interpolation です:'none'/'nearest' がくっきりしたブロックを示し(生のピクセルデータの表示に良し)、'bilinear'/'bicubic' がピクセル間を滑らかにします(ヒートマップに良し)。補間が変えるのは見た目だけです。下流のデータではありません。小さな配列では、個々のセルが見えるよう 'nearest' を WANT にしたいことがしばしばあります。
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(1)
small = rng.random((5, 5))
methods = ["none", "bilinear", "bicubic", "nearest"]
fig, axes = plt.subplots(1, 4, figsize=(12, 3))
for ax, m in zip(axes, methods):
ax.imshow(small, interpolation=m, cmap="magma")
ax.set_title(m)
ax.axis("off")
plt.tight_layout()
plt.show()vmin / vmax と norm
カラーマップへマッピングされるデータ範囲を固定するのが vmin/vmax です(外れ値をクリップします)。非線形のマッピングには norm= を使いましょう:桁が大きく変わるデータには LogNorm、意味のある中間点(異常なら 0 など)で diverging マップを中心化するには TwoSlopeNorm です。norm と vmin/vmax は相互排他です — 1 つだけ渡しましょう。
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LogNorm, TwoSlopeNorm
rng = np.random.default_rng(2)
Z = rng.random((50, 50)) * 1000 + 1
# clamp the colormap range
plt.imshow(Z, vmin=100, vmax=500, cmap="viridis")
plt.colorbar()
plt.title("clipped range")
plt.show()
# log-scaled colors
plt.imshow(Z, norm=LogNorm(vmin=1, vmax=1001), cmap="plasma")
plt.colorbar()
plt.title("log scale")
plt.show()
# diverging norm centered on a midpoint
# norm = TwoSlopeNorm(vmin=-1, vcenter=0, vmax=1)ファイルからの画像表示
画像を NumPy 配列へロードするのが、mpimg.imread です(PNG は float 0〜1、JPEG は 0〜255 の uint8)。表示は plt.imshow、配列のディスクへの書き戻しは plt.imsave です。RGB 画像は色を保ち、シングルチャネルの画像には cmap='gray' を渡しましょう。注意:重要でない画像処理には、PIL/pillow の方が有能です。
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
# read an image file into a numpy array
img = mpimg.imread("photo.png") # shape (H, W, 3) or (H, W, 4)
print(img.shape, img.dtype)
plt.imshow(img)
plt.axis("off")
plt.show()
# save the (possibly modified) array back to a file
# plt.imsave("out.png", img)
# drop the alpha channel if present
if img.shape[-1] == 4:
img = img[..., :3]極座標プロット
Polar Axes
axes を極座標に変えるのが、projection='polar' です。x が角度(theta、ラジアン)で、y が半径(r)です。すべての標準メソッドが機能しますが、(theta, r) で動きます。極座標プロットが理想的なのは、方向性のあるデータ、周期関数、円形の対称性です。目盛りの設定は、ax.set_thetagrids と ax.set_rgrids で。
import matplotlib.pyplot as plt
import numpy as np
# create a polar axes via projection
fig = plt.figure()
ax = fig.add_subplot(projection="polar")
# or from subplots
# fig, ax = plt.subplots(subplot_kw={"projection": "polar"})
theta = np.linspace(0, 2*np.pi, 100)
ax.plot(theta, np.sin(2*theta))
plt.show()極座標の折れ線グラフ
極座標の ax 上で、plot(theta, r) が、theta が角度で r が半径の曲線を描きます。半径の範囲の切り詰めが set_rmax で、半径/角度の目盛り位置のカスタマイズが、set_rticks と set_thetagrids です。極座標の折れ線グラフがきれいに示すのは周期関数で — 正弦波が閉じたループに巻き付きます。
import matplotlib.pyplot as plt
import numpy as np
theta = np.linspace(0, 2*np.pi, 200)
fig, ax = plt.subplots(subplot_kw={"projection": "polar"})
ax.plot(theta, 1 + np.cos(theta), label="cardioid")
ax.plot(theta, np.abs(np.sin(2*theta)), label="rose")
ax.set_rmax(2.0)
ax.set_rticks([0.5, 1.0, 1.5])
ax.set_thetagrids([0, 90, 180, 270])
ax.legend(loc="upper right")
plt.show()レーダー / スパイダーチャート
レーダーチャートは、カテゴリごとに 1 軸を持つ極座標の折れ線グラフです。トリックは、曲線がループへ閉じるよう最初の値/角度を末尾に追加し、内部を alpha 付きで塗ることです。xticks をカテゴリの角度へ設定し、ラベルを付けましょう。レーダーは多変量のプロファイルを比較できますが誤解を招くことがあるため、控えめに使います。
import matplotlib.pyplot as plt
import numpy as np
labels = ["Speed", "Power", "Range", "Comfort", "Price"]
values = [8, 7, 6, 5, 9]
N = len(labels)
# close the loop
angles = np.linspace(0, 2*np.pi, N, endpoint=False).tolist()
values += values[:1]
angles += angles[:1]
fig, ax = plt.subplots(subplot_kw={"projection": "polar"})
ax.plot(angles, values, "o-")
ax.fill(angles, values, alpha=0.25)
ax.set_xticks(angles[:-1])
ax.set_xticklabels(labels)
ax.set_title("Radar Chart")
plt.show()極座標の棒(ローズ)
極座標の axes 上の ax.bar を使うのが、ローズ(または極座標棒)チャート です — 各バーが角度のセクタを占めます。風向や波周期の分布のような、方向性のあるヒストグラムに有用です。追加の次元として、(表示のように)半径でバーに色を付けましょう。中心からのバーの積み上げやオフセットは、bottom= で可能です。
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(0)
N = 12
theta = np.linspace(0, 2*np.pi, N, endpoint=False)
widths = 2*np.pi / N
radii = rng.uniform(1, 5, N)
fig, ax = plt.subplots(subplot_kw={"projection": "polar"})
bars = ax.bar(theta, radii, width=widths, bottom=0,
edgecolor="black")
# color bars by radius
for r, bar in zip(radii, bars):
bar.set_facecolor(plt.cm.viridis(r / radii.max()))
ax.set_title("Rose Diagram")
plt.show()極座標の設定
0 ラジアンを上へ動かすのが set_theta_zero_location('N') で、角度を時計回りに増やすのが set_theta_direction(-1) です — コンパスの慣例です。データとの重なりを避けるため、半径の目盛りラベルを任意の角度へ移すのが、set_rlabel_position(angle) です。これらの調整が、数学の極座標プロットを方向/コンパスのプロットへ変えます。
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(subplot_kw={"projection": "polar"})
ax.plot(np.linspace(0, 2*np.pi, 100), np.linspace(0, 1, 100))
# rotate 0 degrees to the top, go clockwise
ax.set_theta_zero_location("N")
ax.set_theta_direction(-1)
# radial limits and ticks
ax.set_rlim(0, 1.2)
ax.set_rticks([0.25, 0.5, 0.75, 1.0])
ax.set_rlabel_position(135) # move radial labels out of the way
# label directions in degrees
ax.set_thetagrids([0, 90, 180, 270], labels=["E","N","W","S"])
plt.show()Twin Axes
twinx(第 2 の Y)
x 軸を共有しつつ右に自分の y 軸を持つ新しい axes を作るのが、ax.twinx() です。異なる単位の 2 つの量(気温と湿度など)をプロットする標準的な方法です。読者がどのスケールがどの系列に属するか分かるよう、各軸とその目盛りを曲線に合わせて色分けしましょう。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
fig, ax1 = plt.subplots()
ax1.plot(x, np.sin(x), "b-")
ax1.set_xlabel("x")
ax1.set_ylabel("sin(x)", color="b")
ax1.tick_params(axis="y", labelcolor="b")
# a second axes sharing the same x, with an independent y
ax2 = ax1.twinx()
ax2.plot(x, x*10, "r-")
ax2.set_ylabel("10*x", color="r")
ax2.tick_params(axis="y", labelcolor="r")
plt.title("twinx: two y-scales")
plt.show()twiny(第 2 の X)
水平の対応物が ax.twiny() です:y 軸を共有しつつ、上に自分の x 軸を持つ新しい axes です。同じデータを 2 つの x スケールに対して示すのに使いましょう(メートルとフィート、秒と分など)。同じ色分けのヒントが適用されます — 軸の色を曲線に合わせましょう。
import matplotlib.pyplot as plt
import numpy as np
y = np.linspace(0, 10, 50)
fig, ax1 = plt.subplots()
ax1.plot(np.exp(y), y, "g-")
ax1.set_ylabel("y")
ax1.set_xlabel("exp(y)", color="g")
# second axes sharing y, independent x on top
ax2 = ax1.twiny()
ax2.plot(y**2, y, "m-")
ax2.set_xlabel("y^2", color="m")
plt.title("twiny: two x-scales")
plt.show()組み合わせた Twin チャート
軸を twinning すると、各 axes が自分の凡例を持ちます。1 つの結合した凡例を示すには、両方の axes から線のハンドルをリストへ集め、ax1.legend(lines, labels) を呼びましょう。これが、二重軸のチャートのために単一のキーを保つ慣用的な方法で、読者が両方の系列を一度に識別できます。
import matplotlib.pyplot as plt
import numpy as np
t = np.linspace(0, 5, 100)
temp_c = 20 + 5*np.sin(t) # Celsius
humidity = 60 - 5*t # percent
fig, ax1 = plt.subplots(figsize=(8, 4))
l1, = ax1.plot(t, temp_c, "r-o", label="Temperature (C)")
ax1.set_xlabel("time (s)")
ax1.set_ylabel("Temperature (C)", color="r")
ax1.tick_params(axis="y", labelcolor="r")
ax2 = ax1.twinx()
l2, = ax2.plot(t, humidity, "b-s", label="Humidity (%)")
ax2.set_ylabel("Humidity (%)", color="b")
ax2.tick_params(axis="y", labelcolor="b")
# combine legends from both axes
lines = [l1, l2]
ax1.legend(lines, [l.get_label() for l in lines], loc="upper right")
plt.title("Temperature & Humidity")
plt.show()Twin Axes の Despine
Twin axes は自然に、倍になった上の罫線を作ります。よりきれいな見た目のため、両方の axes で上の spines を隠し、左/右の spines をそれぞれの y 軸に合わせて色付けしましょう。色付きの目盛りラベルと組み合わせれば、チャートを雑然とさせずに、どのスケールがどの曲線に属するかが明確に伝わります。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(x, np.sin(x), color="tab:blue")
ax2.plot(x, np.cos(x), color="tab:orange")
# remove the top spine so the two axes don't double-border
ax1.spines["top"].set_visible(False)
ax2.spines["top"].set_visible(False)
# color the spines to match their axes
ax1.spines["left"].set_color("tab:blue")
ax2.spines["right"].set_color("tab:orange")
plt.title("Clean Twin Axes")
plt.show()異なる単位での Twin
第 2 のプロットされた系列が不要なときがあります — 変換された単位(km/miles、C/F)の第 2 の軸が欲しいだけです。twiny() を作り、set_xlim で範囲を整列させ、その後、変換された値へ手動で xticks/xticklabels を設定しましょう。これで、1 つのデータ系列に 2 つの単位系が注釈されます。
import matplotlib.pyplot as plt
import numpy as np
km = np.linspace(0, 100, 50)
mile = km * 0.621371
fig, ax1 = plt.subplots()
ax1.plot(km, np.sin(km/10), "tab:purple")
ax1.set_xlabel("distance")
ax1.set_ylabel("signal", color="tab:purple")
ax2 = ax1.twiny()
ax2.set_xlim(ax1.get_xlim()) # align x limits
# relabel the top ticks in miles
new_ticks = np.array([0, 25, 50, 75, 100])
ax2.set_xticks(new_ticks)
ax2.set_xticklabels([f"{m:.0f}" for m in new_ticks*0.621371])
ax2.set_xlabel("miles")
plt.show()誤差バーと塗りつぶし領域
errorbar
縦の誤差バー付きで点をプロットするのが plt.errorbar(x, y, yerr) です — 不確実性のある実験データの標準です。プロット形式文字列が fmt です('o-' = マーカー + 線)。誤差バーのスタイリングは、ecolor、elinewidth、capsize です。水平の誤差は xerr=、2 次元の不確実性には両方を使いましょう。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 5, 10)
y = np.exp(-x)
yerr = 0.1 + 0.1*x # error grows with x
plt.errorbar(x, y, yerr=yerr, fmt="o-", color="tab:blue",
ecolor="gray", elinewidth=1.5, capsize=4,
markersize=6, label="exp(-x) +/- err")
plt.legend()
plt.title("Error Bar Plot")
plt.show()非対称な誤差
非対称の不確実性には、yerr を 2 x N の配列として渡しましょう:行 0 が下方向の誤差で、行 1 が上方向の誤差です。誤差が歪んでいるとき(ポアソンカウントなど)によくあります。非対称の水平の不確実性のための xerr にも、同じパターンが適用されます。
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(5)
y = np.array([2, 3, 5, 4, 6])
# separate lower and upper errors (each a 1-D array)
yerr = [[0.5, 1, 0.8, 0.6, 1.2], # lower
[1.0, 0.8, 1.5, 1.0, 0.7]] # upper
plt.errorbar(x, y, yerr=yerr, fmt="s", color="tab:green",
capsize=5)
plt.title("Asymmetric Error Bars")
plt.show()
# horizontal asymmetric errors work the same way
# xerr = [[...lower...], [...upper...]]fill_between
2 つの y 曲線の間の領域を色付けするのが fill_between(x, y1, y2) です — 信頼区間、誤差帯、範囲に最適です。真偽値配列が True の所に塗りを限定するのが、where= です(曲線が交差するなら interpolate=True)。帯越しに背後の曲線が見えるよう、alpha < 1 を保ちましょう。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
std = 0.2
plt.plot(x, y, "b-", label="mean")
# shade +/- one standard deviation
plt.fill_between(x, y - std, y + std, color="blue", alpha=0.2,
label="+/- 1 std")
# shade only where a condition holds
plt.fill_between(x, y, 0, where=(y > 0), color="green", alpha=0.2,
label="y > 0")
plt.legend()
plt.show()stackplot
複数の系列を互いの上に積み上げるのが plt.stackplot(x, y1, y2, ...) で、連続的な x(通常は時間)にわたる合計と構成の両方を示します。積み上げバーと違い、連続データ向けです。総高がすべての系列の合計です。レイヤー間の境界が明確になるよう、alpha 付きのはっきり違う色を使いましょう。
import matplotlib.pyplot as plt
import numpy as np
years = np.arange(2010, 2021)
a = np.array([10, 12, 14, 15, 17, 18, 20, 22, 23, 25, 27])
b = np.array([ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
c = np.array([ 3, 4, 4, 5, 6, 6, 7, 8, 8, 9, 10])
plt.stackplot(years, a, b, c, labels=["A", "B", "C"],
colors=["#4C72B0", "#55A868", "#C44E52"], alpha=0.8)
plt.legend(loc="upper left")
plt.title("Stacked Area Chart")
plt.xlabel("year")
plt.ylabel("value")
plt.show()fill(多角形)
任意の多角形を閉じて色付けするのが plt.fill(x, y) です — 領域のハイライトや曲線下の色付けに有用です。曲線下を塗るには、x の値をその逆順と連結し、y の値をゼロと連結しましょう。複数の離散した塗り領域には、2 次元配列を渡すか fill を繰り返し呼びます。
import matplotlib.pyplot as plt
import numpy as np
# fill a closed polygon defined by its vertices
x = [0, 1, 1, 0, 0]
y = [0, 0, 1, 1, 0]
plt.fill(x, y, color="tab:cyan", alpha=0.5)
# shade under a curve
xs = np.linspace(0, 2*np.pi, 100)
ys = np.sin(xs)
plt.fill(np.r_[xs, xs[::-1]],
np.r_[ys, np.zeros_like(ys)],
color="tab:orange", alpha=0.3)
plt.title("Filled Polygons")
plt.show()Seaborn 統合
Seaborn の紹介
Seaborn が Matplotlib の上に構築された高レベルの統計プロットライブラリです:pandas の DataFrame を受け付け、グループ化/集約を処理し、より良いデフォルトを使います。すべての Seaborn 関数が Matplotlib の Axes(または Figure)を返すため、plt/ax の呼び出しでカスタマイズを続けられます。Seaborn のスタイルへの切り替えは、sns.set_theme() を一度呼びましょう。
# install seaborn
pip install seaborn
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
# Seaborn is built ON matplotlib: any sns plot returns an Axes
# and accepts an ax= argument, so you can mix freely.
sns.set_theme() # apply seaborn's default style
tips = sns.load_dataset("tips")
ax = sns.scatterplot(data=tips, x="total_bill", y="tip", hue="time")
ax.set_title("Tips dataset")
plt.show()Seaborn のスタイル
axes の見た目(グリッド、背景)の設定が sns.set_style で、出力媒体('paper'、'talk'、'poster')のためのフォント/線の拡縮が set_context、カラーサイクルの設定が set_palette です。上/右の spines の除去が sns.despine() です。これらが 1〜2 行で、洗練されたデフォルトの見た目へ構成されます。
import seaborn as sns
import matplotlib.pyplot as plt
# five built-in themes: darkgrid, whitegrid, dark, white, ticks
sns.set_style("whitegrid")
sns.set_context("notebook") # paper, notebook, talk, poster
# set the color palette
sns.set_palette("Set2")
import numpy as np
for i in range(4):
plt.plot(np.arange(10), np.arange(10)+i)
plt.title("Seaborn-styled")
plt.show()
# remove the top/right spines (despine) for a clean look
# sns.despine()relplot(リレーショナル)
リレーショナルプロットのための figure レベルのインターフェースが sns.relplot です:kind は 'scatter'(デフォルト)か 'line' です。データを自動的にサブプロットへ(ファセットとして)分割するのが col/row で — 手動のサブプロットよりはるかに楽です。戻り値の FacetGrid の .fig と .axes で、タイトルとレイアウトの微調整のために Matplotlib へ降りられます。
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")
# scatter or line, faceted by a categorical variable
g = sns.relplot(data=tips, x="total_bill", y="tip",
hue="smoker", style="time", col="day",
kind="scatter", height=3, aspect=1.2)
g.fig.suptitle("Tips by day", y=1.03)
plt.show()histplot と kdeplot
非推 奨になった distplot のモダンな代替が sns.histplot です:ヒストグラムを描き、カーネル密度推定を重ねられます(kde=True)。正規化が stat='density' で、グループを独立に正規化し続けるのが common_norm=False です。滑らかな密度曲線だけを描くのが sns.kdeplot で、分布の比較に有用です。
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")
# histogram with an overlaid KDE (density curve)
sns.histplot(data=tips, x="total_bill", bins=20, kde=True,
hue="time", stat="density", common_norm=False)
plt.title("Histogram + KDE")
plt.show()
# standalone KDE
plt.figure()
sns.kdeplot(data=tips, x="total_bill", hue="time", fill=True)
plt.show()heatmap
色分けされた行列を、省略可能なセルの注釈付きで描くのが sns.heatmap です(annot=True)。0 を中心とする diverging の cmap(coolwarm)により、正/負の相関が視覚的にはっきり分かります。plt.imshow + plt.text + colorbar を包むため、相関行列と混同行列のための多くのボイラープレートを節約します。
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
# correlation matrix
tips = sns.load_dataset("tips")
num = tips.select_dtypes("number").drop(columns=["size"])
corr = num.corr()
sns.heatmap(corr, annot=True, cmap="coolwarm", center=0,
vmin=-1, vmax=1, square=True,
linewidths=0.5, fmt=".2f")
plt.title("Correlation Heatmap")
plt.show()pairplot と violinplot
すべての数値列のペアのための散布図のグリッドを、カテゴリの hue で色分けして作るのが sns.pairplot です — 新しい dataset の関係の探索で最速の方法です。box プロットと密度推定を組み合わせ、グループごとに分布の形状を示すのが sns.violinplot です。どちらも下では純粋な Matplotlib で、さらにカスタマイズできます。
import seaborn as sns
import matplotlib.pyplot as plt
iris = sns.load_dataset("iris")
# scatter matrix: every numeric column vs every other
g = sns.pairplot(iris, hue="species", height=2.5)
g.fig.suptitle("Iris pairplot", y=1.01)
plt.show()
# violin plot: box + kernel density on each side
plt.figure()
sns.violinplot(data=iris, x="species", y="sepal_length",
inner="quartile")
plt.show()インタラクティブとアニメーション
スライダーウィジェット
インタラクティブなスライダーを加えるのが、matplotlib.widgets.Slider です。それ用の axes を作り(figure 分数での plt.axes([left, bottom, width, height] 経由で、多くは figure の下部)、コールバックを on_changed へ配線し、その内側でプロットデータを更新しましょう。更新の呼び出しは fig.canvas.draw_idle() です。インタラクティブなバックエンドが必要です(Agg ではない)。
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
import numpy as np
fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.25)
x = np.linspace(0, 10, 500)
line, = ax.plot(x, np.sin(x))
# axes for the slider
ax_freq = plt.axes([0.2, 0.1, 0.6, 0.03])
slider = Slider(ax_freq, "freq", 0.1, 5.0, valinit=1.0)
def update(val):
line.set_ydata(np.sin(slider.val * x))
fig.canvas.draw_idle()
slider.on_changed(update)
plt.show()ボタン
クリック可能なボタンを加えるのが、matplotlib.widgets.Button です。スライダーと同様、独自の axes が必要です(figure 分数の座標で配置)。コールバックは、通常無視するイベントオブジェクトを受け取ります。複数のウィジェット(スライダー、ボタン、チェックボックス)を組み合わせれば、Matplotlib 内に直接、簡単なデータ探索のダッシュボードが作れます。
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
import numpy as np
fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.2)
(ln,) = ax.plot(np.random.rand(10))
ax_btn = plt.axes([0.7, 0.05, 0.2, 0.075])
btn = Button(ax_btn, "Resample")
def reshuffle(event):
ln.set_ydata(np.random.rand(10))
fig.canvas.draw_idle()
btn.on_clicked(reshuffle)
plt.show()CheckButtons
チェックボックスのリストを描画するのが CheckButtons です。コールバックがトグルされたラベルのテキストを受け取るため、それにマッチして各 artist の可視性を切り替えましょう。視聴者が系列をオ ン/オフできるようにするのに使います。すべてのウィジェットと同様、インタラクティブなバックエンドが必要で、ウィンドウが開いたまま保たれる必要があります。
import matplotlib.pyplot as plt
from matplotlib.widgets import CheckButtons
import numpy as np
x = np.linspace(0, 5, 200)
l1, = plt.plot(x, np.sin(x), label="sin")
l2, = plt.plot(x, np.cos(x), label="cos")
plt.subplots_adjust(right=0.8)
rax = plt.axes([0.82, 0.4, 0.15, 0.2])
check = CheckButtons(rax, ["sin", "cos"], [True, True])
def toggle(label):
if label == "sin": l1.set_visible(not l1.get_visible())
if label == "cos": l2.set_visible(not l2.get_visible())
plt.draw()
check.on_clicked(toggle)
plt.show()カーソルとマウスイベント
イベント(button_press_event、motion_notify_event、key_press_event、scroll_event)をコールバックへリンクするのが mpl_connect です。イベントオブジェクトは、event.xdata/event.ydata(データ座標)と event.inaxes(どの axes か、または None)を運びます。これがカスタムインタラクションの基礎です — 十字線、クリックでの注釈、カスタムズームの道具。
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [1, 4, 2, 3])
def on_click(event):
if event.inaxes != ax:
return
print(f"clicked at x={event.xdata:.2f} y={event.ydata:.2f}")
def on_move(event):
if event.inaxes == ax:
ax.set_title(f"x={event.xdata:.2f}, y={event.ydata:.2f}")
fig.canvas.draw_idle()
fig.canvas.mpl_connect("button_press_event", on_click)
fig.canvas.mpl_connect("motion_notify_event", on_move)
plt.show()アニメーション(FuncAnimation)
update(frame) を繰り返し呼ぶことでアニメーションを駆動するのが、FuncAnimation です。blit=True が速さのためにその分だけを再描画できるよう、update は(タプルとして)変わった artist を返さなければなりません。フレーム間の遅延が interval です(ミリ秒)。保存には writer が必要です(mp4 には 'ffmpeg'、gif には 'pillow')。アニメーションオブジェクト(ani)を参照したまま保ちましょう — さもないとガベージコレクトされ 止まります。
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
fig, ax = plt.subplots()
x = np.linspace(0, 2*np.pi, 200)
line, = ax.plot(x, np.sin(x))
def update(frame):
line.set_ydata(np.sin(x + frame / 10.0))
return line,
ani = animation.FuncAnimation(fig, update, frames=100,
interval=50, blit=True, repeat=True)
# save to a file (requires ffmpeg or pillow installed)
# ani.save("wave.mp4", writer="ffmpeg")
# ani.save("wave.gif", writer="pillow")
plt.show()関連する Matplotlib スニペット
Copy-paste ready code for common tasks.
Line Plot
Plot lines with markers, colors, and styles.
Bar Chart
Draw vertical, horizontal, and grouped bars.
Scatter Plot
Visualize relationships with size and color encodings.
Subplots
Arrange multiple axes with subplots and GridSpec.
Labels and Legend
Annotate plots with text, arrows, and legend options.
Styles and Themes
Apply built-in styles and customize rcParams.
Save Figure
Export figures to PNG, PDF, and SVG with DPI control.
3D Plot
Render surfaces and scatter in 3D.
Was this helpful?