scatter【散布図】

メモ ( 基本 マーカーの指定方法 凡例の指定方法 データの指定方法 関連設定 ) 構文 設定・グラフパーツ

メモ

scatterのサンプル

基本

  • 座標・マーカー(スタイル等)を指定
  • マーカーのサイズと色が同じ場合、plot【折れ線グラフ】の方が高速

マーカーの指定方法

凡例の指定方法

  • 手動作成
    • scatter【散布図】呼び出し毎に label【凡例ラベル】を指定
    • legend【凡例 設定】
  • 自動作成 (色 または サイズで分類)
    • scatter【散布図】の戻り値 (PathCollection) の legend_elements【凡例項目作成】3.1 で凡例項目を自動作成
    • legend【凡例 設定】(上記戻り値を指定)
      複数凡例:add_artist【アーティスト追加】

データの指定方法

関連設定

構文

matplotlib.pyplot.scatter(
    x (データx座標)※data,
    y (データy座標)※data,
    s (マーカーサイズ)※data =None,
    c (マーカー色)※data =None,
    marker (マーカースタイル)=None,
    cmap (カラーマップ)=None,
    norm (正規化)=None,
    vmin (正規化の最小値)=None,
    vmax (正規化の最大値)=None,
    alpha (アルファ値)=None,
    *, 3.4
    linewidths (マーカー外枠の幅)※data =None,
    verts (マーカー頂点)3.23.4=None,
    edgecolors (マーカー外枠の色)※data =None,
    *, 3.4
    plotnonfinite (bool:有限値以外の描画有無)3.1 =False,
    data (ラベル名指定データ)=None,
    **kwargs (その他プロパティ)(※data))
matplotlib.axes.Axes.scatter(同上)
戻り値PathCollection

x (float | 配列形式 | shape(n,))※dataデータのx座標
y (float | 配列形式 | shape(n,))※dataデータのy座標
s (float | 配列形式 | shape(n,))※dataマーカーサイズ (ポイント単位2)
    省略:rcParams['lines.markersize']2
c (配列形式 | list(color【色定義】)| color【色定義】)※dataマーカー色
    省略:color【各種色】facecolor・facecolors【塗りつぶし色】を使用 (省略:rcParams["axes.prop_cycle"])
    下記指定
    ・カラーマップ番号のスカラー・シーケンス
    ・2次元配列 (行:RGB または RGBA)
    ・color【色定義】のシーケンス
    ・color【色定義】の文字列
marker (str | MarkerStyle)マーカースタイル (詳細:マーカー定義マーカースタイル )
    省略:rcParams["scatter.marker"] (デフォルト:'o')
cmap (str | Colormap)カラーマップ (c【マーカー色】がfloat配列の場合のみ有効)
    省略:rcParams["image.cmap"] (デフォルト:'viridis')
norm (Normalize)正規化 (c【マーカー色】がfloat配列の場合のみ有効)
    省略:colors.Normalize
vmin (float | None)正規化の最小値
vmax (float | None)正規化の最大値
alpha (float | None)アルファ値 (0:透明 ~ 1:不透明)
linewidths (float | 配列形式) キーワード引数3.4※dataマーカー外枠の幅 (Collection.linewidths 参照)
    省略:rcParams["lines.linewidth"] (デフォルト:1.5)
verts3.23.4マーカー頂点 (marker 省略時)
edgecolors (str | color【色定義】 | color【色定義】のシーケンス) キーワード引数3.4※dataマーカー外枠の色 (Collection.edgecolors 参照)
    省略:rcParams["scatter.edgecolors"] (デフォルト:'face')
    下記指定
    ・'face':facecolor【塗りつぶし色】使用
    ・'none':なし
    ・color【色定義】
    ・color【色定義】のシーケンス
plotnonfinite (bool) キーワード引数3.1有限値以外の描画有無
data (キーワード引数)ラベル名指定データ (※data:ラベル名指定可・詳細は、データの指定方法 参照・下記が対象)
    ・x (データのx座標)
    ・y (データのy座標)
    ・s (マーカーサイズ)
    ・c (マーカー色)
    ・linewidths (マーカー外枠の幅)
    ・edgecolors (マーカー外枠の色)
    ・facecolor・facecolors (塗りつぶし色)
    ・color (各種色)
kwargs (可変長キーワード引数)Collection【コレクション】のプロパティ

Collection【コレクション】のプロパティ

親:matplotlib.artist.Artist ・ matplotlib.cm.ScalarMappable
プロパティデフォルト●設定●取得備考
agg_filtercallableagg フィルター
alphaアルファ値 (0:透明 ~ 1:不透明)
animatedboolアニメーション使用の有無
antialiased
antialiaseds
aa 3.1
bool
list( bool )
rcParams["patch.antialiased"]:True■●アンチエイリアス処理の有無
capstyleCapStyle 3.4
str
rcParams["patch.capstyle"]■●線端スタイル
スタイル備考
'butt'
_enums.CapStyle.butt
butt
'projecting'
_enums.CapStyle.projecting
projecting
'round'
_enums.CapStyle.round
round
clim
clip_boxclipbox
clip_on
clip_path
cmapColormaprcParams["image.cmap"]:'viridis'■●カラーマップ
color各種色 (edgecolor【外枠の色】facecolor【塗りつぶし色】)
contains 3.3callableピッカーイベント (参照:picker【ピッカーイベント】)
edgecolor
edgecolors
ec 3.1
color【色定義】
list( color【色定義】)
'face':塗りつぶし色
rcParams["patch.edgecolor"]:'black'■●外枠・塗りつぶしパターンの色
facecolor
facecolors
fc 3.1
color【色定義】
list( color【色定義】)
'none'
rcParams["patch.facecolor"]:'C0'■●塗りつぶし色
figureFigure所属フィギュア
fillbool塗りつぶしの有無
gidstrグループId (識別子として利用可)
hatchstr■●塗りつぶしパターン (繰り返しで高密度 / 組合せ可)
パターン備考
'/'斜線 (左下がり)
'\'斜線 (右下がり)
'|'垂直線
'-'平行線
'+'格子
'x'斜め格子
'o' (小文字オー)円 (小)
'O' (大文字オー)円 (大)
'.' (ドット)ドット
'*'星印
in_layoutboolレイアウト計算に含めるか否か
joinstyleJoinStyle 3.4
str
rcParams["patch.joinstyle"]■●結合スタイル
スタイル備考
'bevel'
_enums.JoinStyle.bevel
bevel
'miter'
_enums.JoinStyle.miter
miter
'round'
_enums.JoinStyle.round
round
labelobject凡例ラベル (アンダースコアで始まるラベルは対象外)
linestyle
linestyles
ls 3.1
dashes
str
(offset, on-off-seq)
上記の list
'solid'■●線種
スタイル備考
'-' (ダッシュ)
'solid'
solid実線
'--' (ダブルダッシュ)
'dashed'
dashed破線
'-.'
'dashdot'
dashdot一点鎖線
':' (コロン)
'dotted'
dotted点線
(offset, on-off-seq)
(offset, on-off-seq)
ユーザ定義
offset:開始位置オフセット
on-off-seq:線のありなしの対
例:二点鎖線
(0, (6.5, 1.5, 1, 1.5, 1, 1.5))
linewidth
linewidths
lw 3.1
float
list( float )
rcParams["patch.linewidth"]:1.0■●外枠の幅
normNormalizeNone■●正規化
offset_position 3.3str'screen'■●オフセット座標系
備考
'screen'スクリーン座標
'data'データ座標
offset_transform
offsets(float, float)
上記の list
(0, 0)■●
path_effectsAbstractPathEffect
paths
pickerNone
bool
float
callable
NoneNone:ピッカーイベントなし
bool:ピッカーイベント有無
float:ピッカー有効半径
callable:ピッカーイベント hit(bool), props(dict) = picker(artist, mouseevent)
pickradiusfloat5.0■●ピッカー有効半径
(≦ 0:パス内 / 0<:2倍の範囲)
rasterizedboolラスタライズ(ビットマップ) 描画の強制有無
sketch_params
snapbool
None
スナップ (ピクセル位置補正) の有無
(Agg・MacOSX バックエンドのみサポート)
transformTransform
transOffsetTransformIdentityTransform
urlslist( str )None■●ハイパーリンクURL (SVG のみ対応)
visiblebool表示有無
zorderfloatZオーダー (大きい方が手前)

設定・グラフパーツ

設定・グラフパーツ の抜粋〔

pyplot.axes.Axes.その他
タイトルsuptitle【タイトル設定 (全体)】
title【タイトル設定】
set_title【タイトル設定】
get_title【タイトル取得】
Axes3D.set_title【タイトル設定】
figure.Figure.suptitle【タイトル設定 (全体)】
figure.SubFigure.suptitle
凡例legend【凡例 設定】3.5 / 3.73.8
quiverkey【ベクトルの凡例 追加】
figure.Figure.legend【凡例 設定 (全体)】3.73.8
PathCollection.legend_elements【凡例項目作成】
get_legend【凡例 取得】
get_legend_handles_labels【凡例 取得 (ハンドル・ラベル)】
軸ラベルxlabel【x軸ラベル 設定】3.3
ylabel【y軸ラベル 設定】3.3
set_xlabel【x軸ラベル 設定】3.3
set_ylabel【y軸ラベル 設定】3.3
Axes3D.set_zlabel【z軸ラベル 設定】

get_xlabel【x軸ラベル 取得】
get_ylabel【y軸ラベル 取得】
Axes3D.get_zlabel【z軸ラベル 取得】
figure.Figure.supxlabel【x軸ラベル(全体) 設定】3.43.6
figure.Figure.supylabel【y軸ラベル(全体) 設定】3.43.6
figure.SubFigure.supxlabel
figure.SubFigure.supylabel
clabel【等高線ラベル 設定】
bar_label【バーラベル】3.43.7
グリッド線grid【グリッド線 設定】3.5grid【グリッド線 設定】3.5
get_xgridlines【x軸グリッド線 取得】
get_ygridlines【y軸グリッド線 取得】
(Axes3D.grid【3Dグリッド線 取得・設定】)
Axes3D.get_zgridlines【z軸グリッド線 取得】
axis.Axis.grid【軸グリッド線 設定】3.5
axis.Axis.get_gridlines【軸グリッド線 取得】
triplot【三角形分割】
rgrids【放射状グリッド線 取得・設定】
thetagrid【放射状シータグリッド線 取得・設定】
projections.polar.PolarAxes.set_rgrids【放射状グリッド線 設定】
projections.polar.PolarAxes.set_thetagrid【放射状シータグリッド線 設定】
表示範囲xlim【x軸表示範囲 取得・設定】
ylim【y軸表示範囲 取得・設定】
axis【表示範囲等 取得・設定】3.1~3.4 / 3.7
set_xlim【x軸表示範囲 設定】3.1 / 3.6
set_ylim【y軸表示範囲 設定】3.1 / 3.6
get_xlim【x軸表示範囲 取得】
get_ylim【y軸表示範囲 取得】
axis【表示範囲等 取得・設定】3.1~3.4 / 3.7
projections.polar.PolarAxes.set_rlim【極座標範囲 設定】
Axes3D.set_xlim【3D x軸表示範囲 設定】
Axes3D.set_xlim3d【3D x軸表示範囲 設定】
Axes3D.set_ylim【3D y軸表示範囲 設定】
Axes3D.set_ylim3d【3D y軸表示範囲 設定】
Axes3D.set_zlim【3D z軸表示範囲 設定】
Axes3D.set_zlim3d【3D z軸表示範囲 設定】
Axes3D.get_xlim3d【3D x軸表示範囲 取得】
Axes3D.get_ylim3d【3D y軸表示範囲 取得】
Axes3D.get_zlim3d【3D z軸表示範囲 取得】
データ上限・下限set_xbound【x軸データ上限・下限 設定】
set_ybound【y軸データ上限・下限 設定】
get_xbound【x軸データ上限・下限 取得】
get_ybound【y軸データ上限・下限 取得】
projections.polar.PolarAxes.set_rmax【極座標上限 設定】
projections.polar.PolarAxes.set_rmin【極座標下限 設定】
目盛りxticks【x軸目盛り (ラベル) 取得・設定】3.6
yticks【y軸目盛り (ラベル) 取得・設定】3.6
locator_params【目盛り制御】
minorticks_on
minorticks_off
ticklabel_format【目盛りフォーマット設定 (指数形式)】
tick_params【目盛り・グリッド線 外観変更】
set_xticks【x軸目盛り 設定】3.2 / 3.5
set_yticks【y軸目盛り 設定】3.2 / 3.5
Axes3D.set_zticks【z軸目盛り 設定】

set_xticklabels【x軸目盛りラベル 設定】3.3 / 3.5
set_yticklabels【y軸目盛りラベル 設定】3.3 / 3.5
Axes3D.set_zticklabels【z軸目盛りラベル 設定】

get_xticks【x軸目盛り 取得】3.2
get_yticks【y軸目盛り 取得】3.2
Axes3D.get_zticks【z軸目盛り 取得】

get_xticklabels【x軸目盛りラベル 取得】3.3 / 3.6
get_yticklabels【y軸目盛りラベル 取得】3.3 / 3.6
Axes3D.get_zticklabels【z軸目盛りラベル 取得】

get_xmajorticklabels【x軸目盛りラベル 取得 (主)】3.3 / 3.6
get_ymajorticklabels【y軸目盛りラベル 取得 (主)】3.3 / 3.6
get_xminorticklabels【x軸目盛りラベル 取得 (補助)】3.3 / 3.6
get_yminorticklabels【y軸目盛りラベル 取得 (補助)】3.3 / 3.6
get_xticklines
get_yticklines
xaxis_date
yaxis_date
minorticks_on
minorticks_off
ticklabel_format【目盛りフォーマット設定 (指数形式)】
tick_params【目盛り・グリッド線 外観変更】
locator_params【目盛り制御】
fmt_xdata
fmt_ydata
ticker【目盛りモジュール】
axis.Axis.set_ticks【目盛り 設定】
axis.Axis.set_ticklabels【目盛りラベル 設定】
axis.Axis.set_tick_params【目盛り・グリッド線 外観変更】
axis.XAxis.set_ticks_position【x軸目盛り位置 設定】
axis.YAxis.set_ticks_position【y軸目盛り位置 設定】
Axes3D.locator_params【目盛り制御】

axis.Axis.set_major_formatter【フォーマッタ設定 (主)】
axis.Axis.set_minor_formatter【フォーマッタ設定 (補助)】
axis.Axis.set_major_locator【ロケータ設定 (主)】
axis.Axis.set_minor_locator【ロケータ設定 (補助)】
axis.Axis.get_ticklabels【目盛りラベル取得】
axis.Axis.get_majorticklabels【目盛りラベル取得 (主)】
axis.Axis.get_minorticklabels【目盛りラベル取得 (補助)】
axis.Axis.get_major_formatter【フォーマッタ取得 (主)】
axis.Axis.get_minor_formatter【フォーマッタ取得 (補助)】
axis.Axis.get_ticklocs
axis.Axis.get_major_locator【ロケータ取得 (主)】
axis.Axis.get_minor_locator【ロケータ取得 (補助)】
figure.Figure.autofmt_xdate【x軸日付目盛りラベル回転】
axis.Axis.get_tick_params【目盛り・グリッド線 外観取得】3.7
直線
範囲
axhline【水平線 (単一)】
axvline【垂直線 (単一)】
hlines【水平線 (複数)】3.3
vlines【垂直線 (複数)】3.3
axhspan【水平範囲】
axvspan【垂直範囲】
axline【直線】3.3

基本

import matplotlib.pyplot as plt
import numpy as np

# 初期設定
fig, axs = plt.subplots(
    1, 2,
    figsize=(6, 3),
    tight_layout=True,
)
N = 10
SIZE = 100

# 散布図 (左)
axs[0].scatter(
    np.random.rand(N),
    np.random.rand(N),
    SIZE,
)
axs[0].scatter(
    np.random.rand(N),
    np.random.rand(N),
    SIZE,
)
axs[0].scatter(
    np.random.rand(N),
    np.random.rand(N),
    SIZE,
)

# 散布図 (右)
axs[1].scatter(
    np.random.rand(N),
    np.random.rand(N),
    SIZE,
    c='red',
    marker='o',
)
axs[1].scatter(
    np.random.rand(N),
    np.random.rand(N),
    SIZE,
    c='green',
    marker='s',
)
axs[1].scatter(
    np.random.rand(N),
    np.random.rand(N),
    SIZE,
    c='blue',
    marker='D',
)

# 表示
plt.show()

scatterのサンプル画像


マーカーの指定方法

import matplotlib.pyplot as plt
import numpy as np

# 初期設定
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = \
    ['Yu Gothic', 'Hiragino Maru Gothic Pro', 'Noto Sans CJK JP']
fig, axs = plt.subplots(
    1, 3,
    figsize=(9, 3),
    tight_layout=True,
)
N = 10

# 色・マーカースタイル・アルファ値
SIZE_0 = 100
ALPHA = 0.3
axs[0].set_title('色・マーカースタイル・アルファ値')
axs[0].scatter(
    np.random.rand(N), np.random.rand(N),
    s=SIZE_0,
    c='red',
    marker='o',
    alpha=ALPHA,
)
axs[0].scatter(
    np.random.rand(N), np.random.rand(N),
    s=SIZE_0,
    c='green',
    marker='s',
    alpha=ALPHA,
)
axs[0].scatter(
    np.random.rand(N), np.random.rand(N),
    s=SIZE_0,
    c='blue',
    marker='D',
    alpha=ALPHA,
)

# 外枠の幅・外枠の色・線種
SIZE_1 = 400
LINE_WIDTH_1 = 2
axs[1].set_title('外枠の幅・外枠の色・線種')
axs[1].scatter(
    np.random.rand(N), np.random.rand(N),
    s=SIZE_1,
    linewidth=LINE_WIDTH_1,
    edgecolor='red',
    linestyle='--',
)
axs[1].scatter(
    np.random.rand(N), np.random.rand(N),
    s=SIZE_1,
    linewidth=LINE_WIDTH_1,
    edgecolor='green',
    linestyle='-.',
)
axs[1].scatter(
    np.random.rand(N), np.random.rand(N),
    s=SIZE_1,
    linewidth=LINE_WIDTH_1,
    edgecolor='blue',
    linestyle=':',
)

# 中抜き・白抜き
SIZE_2 = 100
LINE_WIDTH_2 = 2
axs[2].set_title('中抜き・白抜き')
axs[2].set_facecolor('lightgray')
axs[2].scatter(
    np.random.rand(N), np.random.rand(N),
    s=SIZE_2,
    c='none',
    linewidth=LINE_WIDTH_2,
    edgecolor='red',
)
axs[2].scatter(
    np.random.rand(N), np.random.rand(N),
    s=SIZE_2,
    c='white',
    linewidth=LINE_WIDTH_2,
    edgecolor='green',
)

# 表示
plt.show()

scatterのサンプル画像


凡例の指定方法

import matplotlib.pyplot as plt
import numpy as np

# 初期設定
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = \
    ['Yu Gothic', 'Hiragino Maru Gothic Pro', 'Noto Sans CJK JP']
fig, axs = plt.subplots(
    2, 2,
    figsize=(8, 6),
    tight_layout=True,
)

# 手動作成
axs[0, 0].set_title('手動作成')
x1 = np.random.rand(5)
y1 = np.random.rand(5)
axs[0, 0].scatter(x1, y1, 100, label='Data1')
x2 = np.random.rand(5)
y2 = np.random.rand(5)
axs[0, 0].scatter(x2, y2, 100, label='Data2')
x3 = np.random.rand(5)
y3 = np.random.rand(5)
axs[0, 0].scatter(x3, y3, 100, label='Data3')
axs[0, 0].legend(title='凡例', loc=(1.1, 0))

# 自動作成 (colors)
N_1 = 15
axs[0, 1].set_title('自動作成 (colors)')
x = np.random.rand(N_1)
y = np.random.rand(N_1)
color = np.random.randint(1, 5, size=N_1)
scatter = axs[0, 1].scatter(x, y, s=100, c=color)
handles, labels = scatter.legend_elements(prop='colors')
axs[0, 1].legend(
    handles,
    labels,
    title='colors',
    loc=(1.1, 0),
)

# 自動作成 (sizes)
N_2 = 15
axs[1, 0].set_title('自動作成 (sizes)')
x = np.random.rand(N_2)
y = np.random.rand(N_2)
size = np.random.randint(25, 225, size=N_2)
scatter = axs[1, 0].scatter(x, y, s=size)
handles, labels = scatter.legend_elements(prop='sizes')
axs[1, 0].legend(
    handles,
    labels,
    title='sizes',
    loc=(1.1, 0),
)

# 自動作成 (colors・sizes)
N_3 = 20
axs[1, 1].set_title('自動作成 (colors・sizes)')
x = np.random.rand(N_3)
y = np.random.rand(N_3)
size = np.random.randint(25, 225, size=N_3)
color = np.random.randint(1, 5, size=N_3)
scatter = axs[1, 1].scatter(x, y, s=size, c=color)
legend_3 = axs[1, 1].legend(
    *scatter.legend_elements(prop='colors'),
    title="colors",
    loc=(1.1, 0.5),
)
axs[1, 1].add_artist(legend_3)
axs[1, 1].legend(
    *scatter.legend_elements(prop='sizes', num=5),
    title='sizes',
    loc=(1.1, 0),
)

# 表示
plt.show()

scatterのサンプル画像


データの指定方法

import matplotlib.pyplot as plt

# 初期設定
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = \
    ['Yu Gothic', 'Hiragino Maru Gothic Pro', 'Noto Sans CJK JP']
fig, axs = plt.subplots(
    1, 2,
    figsize=(6, 3),
    tight_layout=True,
)

# 通常指定
axs[0].set_title('通常指定')
axs[0].scatter(
    [1, 2, 3, 4],
    [1, 2, 3, 4],
    [100, 200, 300, 400],
    ['red', 'green', 'blue', 'cyan'],
)

# ラベル名指定
axs[1].set_title('ラベル名指定')
axs[1].scatter(
    'data_x',
    'data_y',
    'data_s',
    'data_c',
    data={
        'data_x': [1, 2, 3, 4],
        'data_y': [1, 2, 3, 4],
        'data_s': [100, 200, 300, 400],
        'data_c': ['red', 'green', 'blue', 'cyan'],
    },
)

# 表示
plt.show()

scatterのサンプル画像


設定・グラフパーツ

import matplotlib.pyplot as plt
import numpy as np

# 初期設定
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] =\
    ['Yu Gothic', 'Hiragino Maru Gothic Pro', 'Noto Sans CJK JP']
fig, axs = plt.subplots(
    1, 2,
    figsize=(6, 3),
    tight_layout=True,
)
plt.suptitle('suptitle【タイトル (全体)】')

# 散布図 (左)
axs[0].scatter(
    np.random.rand(5), np.random.rand(5),
    200,
)
axs[0].scatter(
    np.random.rand(5), np.random.rand(5),
    200,
)
axs[0].scatter(
    np.random.rand(5), np.random.rand(5),
    200,
)
# タイトル設定
axs[0].set_title('title【タイトル設定】')
# グリッド
axs[0].grid()
# 表示範囲 設定
axs[0].set_xlim(-0.1, 1.1)
axs[0].set_ylim(-0.1, 1.1)
# 目盛り設定
axs[0].set_xticks([0, 0.5, 1])
axs[0].set_yticks([0, 0.5, 1])

# 散布図 (右)
axs[1].scatter(
    np.random.rand(5), np.random.rand(5),
    100,
    label='Data1',
)
axs[1].scatter(
    np.random.rand(5), np.random.rand(5),
    100,
    label='Data2',
)
axs[1].scatter(
    np.random.rand(5), np.random.rand(5),
    100,
    label='Data3',
)
# タイトル設定
axs[1].set_title('title【タイトル設定】')
# 凡例
axs[1].legend(title='凡例', bbox_to_anchor=(1, 0.5))
# 表示範囲 設定
axs[1].set_xlim(-0.1, 1.1)
axs[1].set_ylim(-0.1, 1.1)
# 目盛り設定
axs[1].set_xticks([0, 0.5, 1])
axs[1].set_yticks([0, 0.5, 1])
# 目盛りラベル設定
axs[1].set_xticklabels(['X0', 'X1', 'X2'])
axs[1].set_yticklabels(['Y0', 'Y1', 'Y2'])
# 水平線・垂直線 追加
axs[1].axhline(0.5)
axs[1].axvline(0.5)

# 表示
plt.show()

scatterのサンプル画像