Matplotlib scatter() 関数


Matplotlib 参考文档Matplotlib リファレンスドキュメント

scatter()散布図の描画に使用され、各データポイントのサイズ、色、透明度を個別に設定できます。

plot() とは異なり、scatter() では各ポイントに異なる外観属性を設定でき、3次元または4次元データの分布関係の表示に適しています。

関数定義

pyplot インターフェース

matplotlib.pyplot.scatter(x, y, s=None, c=None, marker='o', cmap=None,
    norm=None, vmin=None, vmax=None, alpha=None, linewidths=None,
    edgecolors=None, **kwargs)

Axes インターフェース

Axes.scatter(x, y, s=None, c=None, marker='o', cmap=None, norm=None,
    vmin=None, vmax=None, alpha=None, linewidths=None, edgecolors=None,
    **kwargs)

パラメータの説明

パラメータ型説明
x, yarray-likeデータポイントの x 座標と y 座標(必須)
sfloat または array-likeポイントのサイズ。スカラー(すべてのポイントで同じ)または配列(ポイントごとに異なるサイズ)を指定できます。
ccolor または array-likeポイントの色。固定色または数値配列(cmap による色のマッピングと組み合わせる)を指定できます。
markerstrマーカー形状:'o'(円)、's'(四角)、'^'(上三角)、'v'(下三角)、'D'(ひし形)、'*'(星)、'+'(プラス)、'x'(バツ) など。デフォルトは 'o'
cmapstr または Colormapカラーマップ。c が数値配列の場合に使用します。例:'viridis', 'plasma'
normNormalizeデータからカラーマップへの正規化方法
vmin, vmaxfloatカラーマッピングのデータ範囲。範囲外のポイントはクリップされます。
alphafloat または array-like透明度。0〜1 の間
linewidthsfloat または array-likeポイントのエッジの線幅
edgecolorscolor または array-likeポイントのエッジの色。'face' は塗りつぶし色を使用し、'none' はエッジなし。
labelstr凡例ラベル

scatter() の主な利点はs、c、alphax/y と同じ長さの配列を指定できることで、1枚の散布図で3〜4次元のデータ情報を同時に表示できます。


使用例

例 1:基本的な散布図

サンプル

import matplotlib.pyplot as plt
import numpy as np

# ランダムデータを生成
np.random.seed(42)
x = np.random.rand(50)
y = np.random.rand(50)

fig, ax = plt.subplots(layout='constrained')

ax.scatter(x, y, color='steelblue', edgecolors='white',
           linewidth=0.5, s=80)
ax.set_title('Basic Scatter Plot')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.grid(True, alpha=0.3)
plt.show()

例 2:サイズと色の両方を変化させる(多次元データの表示)

サンプル

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(42)
n = 100

# 4次元のデータ
x = np.random.rand(n) * 10           # 次元1: x 座標
y = np.random.rand(n) * 10           # 次元2: y 座標
colors = np.random.rand(n) * 100     # 次元3: 色(数値)
sizes = np.random.rand(n) * 300      # 次元4: サイズ
alpha_values = np.random.rand(n) * 0.7 + 0.3  # 次元5: 透明度

fig, ax = plt.subplots(figsize=(8, 6), layout='constrained')

scatter = ax.scatter(x, y,
                     c=colors,           # 色がデータに応じて変化
                     s=sizes,            # サイズがデータに応じて変化
                     alpha=0.6,          # 透明度を固定
                     cmap='viridis',     # カラーマッピング
                     edgecolors='white',
                     linewidth=0.5)

# カラーバーを追加
cbar = fig.colorbar(scatter, ax=ax)
cbar.set_label('Color Value')

ax.set_title('Multi-dimensional Scatter Plot')
ax.set_xlabel('X Coordinate')
ax.set_ylabel('Y Coordinate')
ax.grid(True, alpha=0.2)
plt.show()

例 3:複数グループの散布図の比較

サンプル

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(42)

# 3つの異なる分布のデータを生成
group1_x = np.random.normal(2, 0.5, 100)
group1_y = np.random.normal(2, 0.5, 100)

group2_x = np.random.normal(6, 0.5, 100)
group2_y = np.random.normal(6, 0.5, 100)

group3_x = np.random.normal(4, 1.0, 100)
group3_y = np.random.normal(4, 1.0, 100)

fig, ax = plt.subplots(figsize=(8, 6), layout='constrained')

# 各グループで異なる色とマーカーを使用
ax.scatter(group1_x, group1_y, c='#e74c3c', marker='o',
           s=60, label='Group A (tight cluster)')
ax.scatter(group2_x, group2_y, c='#2E7DCC', marker='s',
           s=60, label='Group B (tight cluster)')
ax.scatter(group3_x, group3_y, c='#3498db', marker='^',
           s=60, label='Group C (spread cluster)')

ax.set_title('Multi-group Scatter Comparison')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.legend()
ax.grid(True, alpha=0.2)
plt.show()

例 4:カラーバー付き散布図(バブルチャート)

サンプル

import matplotlib.pyplot as plt
import numpy as np

# 模擬データ:異なる都市の人口、GDP、所属地域
np.random.seed(42)
n = 30
population = np.random.randint(50, 500, n)    # 人口(バブルのサイズを決定)
gdp = np.random.randint(100, 1000, n)         # GDP(色の濃淡を決定)
region = np.random.choice(['North', 'South', 'East', 'West'], n)
x = np.random.rand(n) * 100
y = np.random.rand(n) * 100

fig, ax = plt.subplots(figsize=(9, 6), layout='constrained')

scatter = ax.scatter(x, y,
                     s=population,            # バブルのサイズ = 人口
                     c=gdp,                   # バブルの色 = GDP
                     cmap='YlOrRd',           # 黄-オレンジ-赤のカラーマッピング
                     alpha=0.7,
                     edgecolors='gray',
                     linewidth=0.5)

ax.set_title('Bubble Chart: City Population vs GDP')
ax.set_xlabel('X Coordinate')
ax.set_ylabel('Y Coordinate')

# カラーバーを追加し、GDP とラベル付け
cbar = fig.colorbar(scatter, ax=ax, label='GDP')
ax.grid(True, alpha=0.2)
plt.show()

よくある質問

scatter() と plot() の違いは?

plot()折れ線グラフに適しており、すべてのポイントが同じ色とマーカースタイルを共有するため、レンダリング効率が高いです。

scatter()散布図に適しており、各ポイントのサイズと色を個別に設定できます。ただし、各ポイントが独立した Artist であるため、データ量が多い場合は遅くなります。

データポイントが非常に多い(数万以上)場合は、plot() にマーカーを指定して使用し、パフォーマンスを向上させることを優先的に検討してください。

s パラメータの単位は?

sポイントの面積(単位は平方ポイント points^2)を表し、直径ではありません。

例えばs=100とs=400、後者の面積は前者の4倍で、直径は約2倍です。


Matplotlib 参考文档Matplotlib リファレンスドキュメント

その他の拡張