Matplotlib チートシート
最終更新
figure と axes
figure は画像全体です。axes はその中の1つのグラフで、以下の呼び出しのほとんどは ax のメソッドです。
| やりたいこと | コード |
|---|---|
| pyplot をインポート | import matplotlib.pyplot as plt |
| グラフ1つの figure | fig, ax = plt.subplots() |
| サイズをインチで指定 | fig, ax = plt.subplots(figsize=(8, 4)) |
| axes に描画 | ax.plot(x, y) |
| figure を表示 | plt.show() |
| 高解像度の PNG で保存 | fig.savefig("chart.png", dpi=150, bbox_inches="tight") |
| ベクター形式で保存 | fig.savefig("chart.svg"), fig.savefig("chart.pdf") |
| 背景を透明に | fig.savefig("chart.png", transparent=True) |
| figure を閉じてメモリを解放 | plt.close(fig) |
| 1枚だけなら手軽な pyplot スタイル | plt.plot(x, y)
plt.title("Quick look")
plt.show() |
グラフの種類
| やりたいこと | コード |
|---|---|
| 折れ線グラフ | ax.plot(x, y) |
| 散布図 | ax.scatter(x, y, s=20, alpha=0.7) |
| 値で色分けした散布図とカラーバー | points = ax.scatter(x, y, c=y, cmap="viridis")
fig.colorbar(points, ax=ax) |
| 棒グラフ | ax.bar(cats, a) |
| 横棒グラフ | ax.barh(cats, a) |
| 積み上げ棒グラフ | ax.bar(cats, a, label="2025")
ax.bar(cats, b, bottom=a, label="2026") |
| グループ化した棒グラフ | pos = np.arange(len(cats))
ax.bar(pos - 0.2, a, width=0.4)
ax.bar(pos + 0.2, b, width=0.4)
ax.set_xticks(pos, labels=cats) |
| ヒストグラム | ax.hist(data, bins=30) |
| 箱ひげ図 | ax.boxplot([data, data * 2], tick_labels=["A", "B"]) |
| バイオリンプロット | ax.violinplot([data, data * 2]) |
| 円グラフ | ax.pie([40, 35, 25], labels=cats, autopct="%1.0f%%") |
| 2本の曲線の間を塗る | ax.fill_between(x, y - 0.2, y + 0.2, alpha=0.3) |
| エラーバー | ax.errorbar([1, 2, 3], [4, 5, 3], yerr=[0.5, 0.3, 0.6], fmt="o", capsize=4) |
| ステップグラフ | ax.step(x, y, where="mid") |
| 2次元配列のヒートマップ | image = ax.imshow(np.random.default_rng(0).random((5, 5)), cmap="magma")
fig.colorbar(image, ax=ax) |
| 塗りつぶし等高線図 | X, Y = np.meshgrid(x, x)
ax.contourf(X, Y, np.sin(X) * np.cos(Y), levels=20) |
| 大量の点の密度 | ax.hexbin(data, data + np.random.default_rng(1).normal(size=200), gridsize=20) |
| 水平または垂直の基準線 | ax.axhline(0, color="gray", linestyle="--"), ax.axvline(5) |
| 範囲を塗りつぶす | ax.axvspan(2, 4, alpha=0.2) |
線、マーカー、色
| やりたいこと | コード |
|---|---|
| 色、太さ、線のスタイル | ax.plot(x, y, color="tab:red", linewidth=2, linestyle="--") |
| 点にマーカーを付ける | ax.plot(x, y, marker="o", markersize=4) |
| 短いフォーマット文字列 | ax.plot(x, y, "g--o") |
| 透明度 | ax.plot(x, y, alpha=0.5) |
| 線のスタイル | "-", "--", "-.", ":" |
| マーカーのコード | "o", "s", "^", "x", ".", "*" |
| 色の指定方法 | "tab:blue", "C1", "#1f77b4", (0.2, 0.4, 0.6) |
| カラーマップから n 色 | colors = plt.colormaps["viridis"](np.linspace(0, 1, 5)) |
| 独自のカラーサイクル | ax.set_prop_cycle(color=["#0b7285", "#e8590c", "#5f3dc4"]) |
| 枠線とハッチング付きの棒 | ax.bar(cats, a, color="white", edgecolor="black", hatch="//") |
タイトル、ラベル、凡例
| やりたいこと | コード |
|---|---|
| タイトルと軸ラベル | ax.set_title("Sales"), ax.set_xlabel("Month"), ax.set_ylabel("EUR") |
| まとめて1回で設定 | ax.set(title="Sales", xlabel="Month", ylabel="EUR") |
| 線のラベルから凡例 | ax.plot(x, y, label="sin")
ax.legend() |
| 凡例の位置と列数 | ax.legend(loc="upper right", ncols=2, frameon=False) |
| 凡例をグラフの外に | ax.legend(loc="center left", bbox_to_anchor=(1, 0.5)) |
| データ座標にテキスト | ax.text(5, 0.5, "note") |
| 矢印付きの注釈 | ax.annotate("peak", xy=(1.57, 1), xytext=(3, 1.2), arrowprops=dict(arrowstyle="->")) |
| 棒に値ラベル | bars = ax.bar(cats, a)
ax.bar_label(bars) |
| figure 全体のタイトル | fig.suptitle("Q1 report") |
| ラベルに数式 | ax.set_xlabel(r"$\alpha$ (rad)") |
軸、目盛り、スケール
| やりたいこと | コード |
|---|---|
| 軸の範囲 | ax.set_xlim(0, 10), ax.set_ylim(bottom=0) |
| 対数スケール | ax.set_yscale("log") |
| 目盛りとそのラベルを指定 | ax.set_xticks([0, 5, 10], labels=["start", "middle", "end"]) |
| 目盛りラベルを回転 | ax.tick_params(axis="x", labelrotation=45) |
| グリッド線 | ax.grid(True, alpha=0.3) |
| パーセント表示の軸 | from matplotlib.ticker import PercentFormatter
ax.yaxis.set_major_formatter(PercentFormatter(1.0)) |
| 3桁区切り | ax.yaxis.set_major_formatter("{x:,.0f}") |
| 上と右の枠線を消す | ax.spines[["top", "right"]].set_visible(False) |
| 右側に第2の y 軸 | ax2 = ax.twinx()
ax2.plot(x, y * 100, color="tab:orange") |
| 両軸を同じスケールに | ax.set_aspect("equal") |
| 軸を反転 | ax.invert_yaxis() |
| 軸を完全に非表示 | ax.axis("off") |
| 読みやすい日付ラベル | fig.autofmt_xdate() |
subplots とレイアウト
plt.subplots(rows, cols) は axes の NumPy 配列を返します。配列と同じようにインデックスで指定しましょう。
| やりたいこと | コード |
|---|---|
| グラフのグリッド | fig, axs = plt.subplots(2, 2, figsize=(8, 6)) |
| そのうち1つに描画 | axs[0, 1].plot(x, y) |
| すべてをループ | for ax in axs.flat:
ax.grid(True) |
| グラフ間で軸を共有 | fig, axs = plt.subplots(1, 3, sharey=True) |
| 重ならない余白 | fig, axs = plt.subplots(2, 2, layout="constrained") |
| 描画後に重なりを解消 | fig.tight_layout() |
| 幅の違う列 | fig, axs = plt.subplots(1, 2, width_ratios=[3, 1]) |
| 幅の広いパネルを含む名前付きレイアウト | fig, axd = plt.subplot_mosaic([["top", "top"], ["left", "right"]])
axd["top"].plot(x, y) |
| グラフの中に小さなグラフ | inset = ax.inset_axes([0.6, 0.6, 0.35, 0.35]) |
| 空のパネルを非表示 | axs[0].axis("off") |
スタイルとデフォルト設定
| やりたいこと | コード |
|---|---|
| 組み込みスタイルを使う | plt.style.use("ggplot") |
| スタイルの一覧 | plt.style.available |
| seaborn なしで seaborn 風に | plt.style.use("seaborn-v0_8-whitegrid") |
| 1つの figure だけにスタイルを適用 | with plt.style.context("dark_background"):
fig, ax = plt.subplots() |
| デフォルトのフォントサイズ | plt.rcParams["font.size"] = 12 |
| デフォルトの figure サイズと解像度 | plt.rcParams["figure.figsize"] = (8, 4), plt.rcParams["figure.dpi"] = 120 |
| デフォルトに戻す | plt.style.use("default") |
| よく使うカラーマップ: 連続、発散、グレー | "viridis", "coolwarm", "Greys" |
pandas から描画する
pandas は Matplotlib で描画します。ax= を渡せば自分の axes に描け、pandas が返す ax をそのまま使うこともできます。
| やりたいこと | コード |
|---|---|
| DataFrame の列を自分の axes に | df.plot(x="month", y="sales", ax=ax) |
| グループ集計の棒グラフ | df.groupby("city")["sales"].sum().plot.bar(ax=ax) |
| pandas が描いたグラフを続けて調整 | ax = df.plot(x="month", y="sales")
ax.set_title("Sales") |
| 列を直接 Matplotlib に渡す | ax.plot(df["month"], df["sales"]) |
Matplotlib 3.11: 旧書式と今の書き方
古いチュートリアルからコピーしたコードは、Matplotlib 3.11 ではエラーや警告になることがあります。代わりに Matplotlib 3.11 の列の書き方を使いましょう。
| やりたいこと | Matplotlib 3.11 | 旧書式 |
|---|---|---|
| 箱ひげ図のラベル | ax.boxplot([data, data * 2], tick_labels=["A", "B"]) | labels=["A", "B"] |
| 横向きの箱ひげ図やバイオリンプロット | ax.boxplot(data, orientation="horizontal") | vert=False |
| カラーマップを取得 | plt.colormaps["viridis"] | plt.cm.get_cmap("viridis") |
| seaborn スタイル | plt.style.use("seaborn-v0_8") | plt.style.use("seaborn") |
データをわかりやすいグラフにするための Matplotlib のコードを、タスク別にまとめました。figure と axes、グラフの種類、線と色、タイトルと凡例、軸と目盛り、subplots とレイアウト、スタイル、pandas からの描画まで揃っています。各行は貼り付けてすぐ使える短いコードと、その動作を説明する一文で構成されています。
すべてオブジェクト指向スタイル (fig, ax = plt.subplots() のあと ax のメソッドを呼ぶ書き方) を使い、Coddy で動いている Matplotlib 3.11 向けに書いています。boxplot の labels= のような古い書き方は最後の表にだけ載せ、今の書き方と並べています。例では x = np.linspace(0, 10, 50)、y = np.sin(x) と、正規分布の値のサンプル data を使います。Python 自体が初めての方は Python チートシート から始めて、pandas、NumPy、scikit-learn のチートシートもあわせて手元に置いておきましょう。
Matplotlib チートシートのよくある質問
この Matplotlib チートシートは無料ですか?
plt と ax の違いは何ですか?
plt.plot() はその時点でアクティブな axes に描画するので、グラフ1つなら手軽です。fig, ax = plt.subplots() は figure と axes をオブジェクトとして返すので、ax.plot() は必ず意図した場所に描画されます。グラフが複数あるときや、残しておくコードには ax スタイルを使いましょう。figure のサイズを変えるには?
figsize をインチで渡します: fig, ax = plt.subplots(figsize=(10, 5))。すべての figure のデフォルトを変えるなら plt.rcParams["figure.figsize"] = (10, 5) を設定します。保存したファイルのピクセルサイズは figsize × dpi です。グラフを高解像度で保存するには?
fig.savefig("chart.png", dpi=300, bbox_inches="tight") を呼びます。dpi を高くするほど PNG が鮮明になり、bbox_inches="tight" で余白を切り詰めます。印刷やスライド用なら、どのサイズでも鮮明なままの SVG か PDF で保存しましょう。subplots のタイトルやラベルが重なるのはなぜですか?
plt.subplots(2, 2, layout="constrained") のように layout="constrained" を付けて figure を作れば、Matplotlib がタイトル、ラベル、カラーバーのスペースを確保します。既存の figure なら、描画後に fig.tight_layout() を呼びましょう。このチートシートはどの Matplotlib バージョンに対応していますか?
boxplot の labels= (現在は tick_labels=) や plt.cm.get_cmap (現在は plt.colormaps[...]) のように新しいバージョンで削除または名前変更された呼び出しは、最後の表で今の書き方と並べています。