0
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】散布図・ヒートマップの描画で気をつけたい設定

0
Posted at

散布図・ヒートマップの描画設定をまとめる備忘録

はじめに

Python(matplotlib)で散布図や相関ヒートマップを描画する際、デフォルト設定のまま出力すると意図しない情報の損失や誤読が起きることがある。
本記事では、そうした問題が起きやすい設定と、それに対する改善手順を自分用にまとめる。

前提環境

  • Python 3系
  • numpy / pandas / matplotlib
pip install numpy pandas matplotlib

以下、デフォルト設定で描画した場合と改善後の結果を先に示す。

散布図

scatter_comparison.png

左:デフォルト設定。点が不透明で重なり合い、密集部の構造が読み取れない。
右:改善後。透過・スケール調整・カラーマップと凡例の追加により密度と分布の構造が可視化されている。

ヒートマップ

heatmap_comparison.png

左:デフォルト設定。単方向カラーマップで正負の区別がつかず、補間でセル境界が不明瞭。
右:改善後。発散型カラーマップ・ゼロ中心固定・NaN明示・相関係数のテキスト表記により相関構造が正確に表現されている。

以下、それぞれの詳細を記述する。


0. 検証用データの作成

実データは使わず、問題を再現しやすい架空データ(Irisデータセット風)を生成する。
散布図用には「局所的に密集したデータ(種ごとのクラスタ)」「外れ値」を含める。
ヒートマップ用には、「相関を持つ特徴量」と「相関行列の計算時にゼロ除算で NaN を誘発する定数列」を含める。

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import TwoSlopeNorm

# 共通設定
AXIS_LABEL_SIZE = 12
TITLE_SIZE = 13
TICK_SIZE = 10
SCATTER_FIGSIZE = (5, 4)
HEATMAP_FIGSIZE = (5.5, 4.5)
DPI = 300

def apply_axis_style(ax):
    ax.tick_params(direction="in", labelsize=TICK_SIZE)

def style_colorbar(cbar, label=None):
    cbar.ax.tick_params(direction="in", labelsize=TICK_SIZE)
    if label:
        cbar.set_label(label, fontsize=AXIS_LABEL_SIZE)

def simulate_iris_like(n_per_species=60, seed=42):
    rng = np.random.default_rng(seed)

    species_params = {
        "setosa": (5.0, 3.45, 1.50, 0.25),
        "versicolor": (5.95, 2.80, 4.30, 1.30),
        "virginica": (6.60, 3.00, 5.60, 2.00),
    }

    rows = []
    for species, (mu_sl, mu_sw, mu_pl, mu_pw) in species_params.items():
        latent = rng.normal(0, 1, n_per_species)
        sepal_length = mu_sl + 0.35 * latent + rng.normal(0, 0.18, n_per_species)
        sepal_width = mu_sw - 0.18 * latent + rng.normal(0, 0.15, n_per_species)
        petal_length = mu_pl + 0.55 * latent + rng.normal(0, 0.18, n_per_species)
        petal_width = mu_pw + 0.30 * latent + rng.normal(0, 0.08, n_per_species)

        # 非負制約のようなクリッピングで外れ値的な挙動を含める
        petal_width = np.clip(petal_width, 0.05, None)

        for i in range(n_per_species):
            rows.append(
                {
                    "species": species,
                    "sepal_length": sepal_length[i],
                    "sepal_width": sepal_width[i],
                    "petal_length": petal_length[i],
                    "petal_width": petal_width[i],
                }
            )

    df = pd.DataFrame(rows)
    # NaNを誘発するための定数列を意図的に混入
    df["CONST"] = 1.0
    return df

def get_corr_matrix(df):
    cols = ["sepal_length", "sepal_width", "petal_length", "petal_width", "CONST"]
    return df[cols].corr(numeric_only=True)

# データの生成と色の定義
df = simulate_iris_like(n_per_species=60, seed=42)
corr = get_corr_matrix(df)

colors = {
    "setosa": "#1f77b4",
    "versicolor": "#2ca02c",
    "virginica": "#d62728",
}

1. 散布図の可視化

データ数が多くなると、プロットが重なり分布の密度が見えなくなる問題(オーバープロット)が発生する。

1-1. デフォルト設定で描画した場合

デフォルト設定で描画する最小サンプルを以下に示す。

def draw_bad_scatter(ax, df, colors):
    for species, color in colors.items():
        g = df[df["species"] == species]
        # alphaを1.0で描画
        ax.scatter(g["sepal_length"], g["petal_length"], s=60, alpha=1.0, color=color)

    ax.set_title("BAD scatter", fontsize=TITLE_SIZE)
    apply_axis_style(ax)

fig, ax = plt.subplots(figsize=SCATTER_FIGSIZE)
draw_bad_scatter(ax, df, colors)
fig.tight_layout()
fig.savefig("scatter_bad.png", dpi=DPI, bbox_inches="tight")
plt.close(fig)

実行すると scatter_bad.png が生成される。

scatter_bad.png

点が不透明で重なり合い、密集度が読み取れない。さらに凡例がないため各色がどのグループを指すのか不明となる。

1-2. 改善手順

意図した分布を描画するため、以下の修正を加える。

  1. alpha(不透明度)を下げて透過させ、重なりの濃淡を表現する。
  2. linewidths(枠線)を指定してマーカー境界を見えやすくし、同時にプロットサイズ(s)を小さくする。
  3. legend(凡例)を明示する。
  4. パーセンタイルで外れ値を除外し、表示スケールを固定する。
  5. 目盛りを内向き(direction="in")にする。

表示範囲を意図的にクリッピングした場合は、一部のデータを除外した事実をタイトル等で必ず記載する(今回はコード内でクリップ範囲を明示)。

def draw_good_scatter(ax, df, colors):
    for species, color in colors.items():
        g = df[df["species"] == species]
        ax.scatter(
            g["sepal_length"],
            g["petal_length"],
            s=15,
            alpha=0.6,
            linewidths=0.3, # 枠線を追加
            edgecolors="white",
            color=color,
            label=species, # 凡例用のラベルを追加
        )

    # 1% - 99% パーセンタイルでスケールを固定
    x = df["sepal_length"]
    y = df["petal_length"]
    x1, x2 = np.percentile(x, [1, 99])
    y1, y2 = np.percentile(y, [1, 99])
    ax.set_xlim(x1, x2)
    ax.set_ylim(y1, y2)

    ax.set_xlabel("sepal_length", fontsize=AXIS_LABEL_SIZE)
    ax.set_ylabel("petal_length", fontsize=AXIS_LABEL_SIZE)
    ax.set_title("GOOD scatter", fontsize=TITLE_SIZE)
    
    # 凡例の追加
    ax.legend(frameon=False, fontsize=TICK_SIZE, title="species", title_fontsize=TICK_SIZE)

    apply_axis_style(ax)

fig, ax = plt.subplots(figsize=SCATTER_FIGSIZE)
draw_good_scatter(ax, df, colors)
fig.tight_layout()
fig.savefig("scatter_good.png", dpi=DPI, bbox_inches="tight")
plt.close(fig)

scatter_good.png


2. ヒートマップの可視化

相関係数は -1 ~ 1 の範囲を取り、「0(無相関)」を中心とする正負の極性を持つ。こうしたデータを可視化する際、デフォルト設定では極性が表現されない。

2-1. デフォルト設定で描画した場合

相関行列をそのまま imshow に渡すサンプル。

def draw_bad_heatmap(ax, corr):
    # bilinear補間と単方向のカラーマップ(viridis等)が使われる
    im = ax.imshow(corr.values, cmap="viridis", interpolation="bilinear")

    labels = list(corr.columns)
    ax.set_xticks(np.arange(len(labels)))
    ax.set_xticklabels(labels, rotation=0, fontsize=TICK_SIZE) # 軸ラベルの文字潰れ
    ax.set_yticks(np.arange(len(labels)))
    ax.set_yticklabels(labels, fontsize=TICK_SIZE)

    ax.set_xlabel("Features", fontsize=AXIS_LABEL_SIZE)
    ax.set_ylabel("Features", fontsize=AXIS_LABEL_SIZE)
    ax.set_title("BAD heatmap", fontsize=TITLE_SIZE)
    apply_axis_style(ax)
    return im

fig, ax = plt.subplots(figsize=HEATMAP_FIGSIZE)
im = draw_bad_heatmap(ax, corr)
cbar = fig.colorbar(im, ax=ax)
style_colorbar(cbar)
fig.tight_layout()
fig.savefig("heatmap_bad.png", dpi=DPI, bbox_inches="tight")
plt.close(fig)

heatmap_bad.png

画像の補間(bilinear)により独立したセル同士の数値が混合される。
単方向のカラーマップが使われているため「どこが相関ゼロか」が視認できず、NaN セルの扱い(一番右下)も未処理で背景と同化している。

2-2. 改善手順

各セルの独立性と正負の境界を明示するために、以下のように修正する。

  1. マトリクスのセル値が混ざらないよう、補間を nearest にする。
  2. 発散型(Diverging)カラーマップ(今回は coolwarm)を指定する。
  3. TwoSlopeNorm を使い、カラーマップの中心値を「0」に厳密に固定する。
  4. 欠損箇所(NaN)に対し、.set_bad() で明示的な色(グレー等)を設定する。
  5. 各セルに相関係数のテキストを重畳して具体的な数値を可視化する。
  6. x軸ラベルが重ならないよう 45度回転(rotation=45)させる。
def draw_good_heatmap(ax, corr):
    mat = corr.values
    # NaN(計算不能・欠損)セルを分離して管理
    masked = np.ma.masked_invalid(mat)
    
    cmap = plt.cm.coolwarm.copy()
    cmap.set_bad("lightgray") # NaNセル用のカラーを設定
    
    # 最小・最大値を固定し、0を中心に配置
    norm = TwoSlopeNorm(vcenter=0, vmin=-1, vmax=1)

    im = ax.imshow(masked, cmap=cmap, norm=norm, interpolation="nearest")

    labels = list(corr.columns)
    ax.set_xticks(np.arange(len(labels)))
    # X軸のラベルを傾けて重なりを回避
    ax.set_xticklabels(labels, rotation=45, ha="right", fontsize=TICK_SIZE)
    ax.set_yticks(np.arange(len(labels)))
    ax.set_yticklabels(labels, fontsize=TICK_SIZE)

    # セルにテキストで数値を重ねる
    for i in range(mat.shape[0]):
        for j in range(mat.shape[1]):
            value = mat[i, j]
            if np.isnan(value):
                continue
            # 背景色に応じて文字色を白黒反転
            text_color = "white" if (value >= 0.5 or value <= -0.5) else "black"
            ax.text(
                j,
                i,
                f"{value:.2f}",
                ha="center",
                va="center",
                color=text_color,
                fontsize=9,
            )

    ax.set_xlabel("Features", fontsize=AXIS_LABEL_SIZE)
    ax.set_ylabel("Features", fontsize=AXIS_LABEL_SIZE)
    ax.set_title("GOOD heatmap", fontsize=TITLE_SIZE)
    apply_axis_style(ax)
    return im

fig, ax = plt.subplots(figsize=HEATMAP_FIGSIZE)
im = draw_good_heatmap(ax, corr)
cbar = fig.colorbar(im, ax=ax)
style_colorbar(cbar, label="correlation")
fig.tight_layout()
fig.savefig("heatmap_good.png", dpi=DPI, bbox_inches="tight")
plt.close(fig)

heatmap_good.png


3. 確認ポイントまとめ

今回の設定手順における確認ポイントを以下にまとめる。

  • 散布図
    • alpha 指定でデータの密集度(濃淡)を透過させて表現する。
    • linewidths やマーカーの大きさを調整し視認性を高める。
    • グループ分けしたデータは凡例・色の割り振りを設定する。
    • 外れ値を考慮し描画スケールを手動でパーセンタイル固定する。
  • ヒートマップ
    • セルごとに値が独立した行列データを表現する場合は画像補間(平滑化)をしない。
    • データに正負(またはゼロの基準)があるなら発散型カラーマップを採用し、値の中心を 0 に固定する。
    • NaN が発生した際に背景等と同化しないよう、欠損用の明瞭な色を事前に設定しておく。
    • 各セルに数値ラベルがあれば、より厳密な相関構造の把握につながる。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?