3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Plotly] 3D散布図に凡例(グループ色分け)と軸線を追加する

Posted at

はじめに

image.png

3D散布図は、そのままでも"空間的な分布"が自然に理解できますが、凡例(グループ識別)と軸線(中心線)を追加するだけでデータの意味や構造が一気に分かりやすくなります。今回はPlotlyでそれらを追加する方法を整理します。

目的

  • 3D散布図に凡例(グループ別色分け)を追加する
  • 3D空間に軸線(X, Y, Zの中心線)を追加して位置関係を明確化する
  • Colabでもそのまま動くコードを使って、見やすい3D散布図を作る

実装例:ランダム点群の作成

import plotly.graph_objects as go
import numpy as np

np.random.seed(0)
x, y, z = np.random.randn(3, 200)

fig = go.Figure(data=[go.Scatter3d(
    x=x, y=y, z=z,
    mode='markers',
    marker=dict(size=4, color='royalblue', opacity=0.8)
)])
fig.update_layout(scene=dict(aspectmode='data'), title="Base Scatter3D")
fig.show()

まずは点群だけの基本形。ここに「凡例」と「軸線」を加えていきます。

image.png

1. 3D散布図に凡例(グループ色分け)を追加する

グループラベルを作る

group = np.random.choice(['A', 'B', 'C'], size=200)

グループごとにtraceを追加する

Plotlyでは「凡例」=「複数trace」。グループ別に座標を分けて追加します。

fig = go.Figure()

colors = {'A': 'red', 'B': 'green', 'C': 'blue'}

for g in ['A', 'B', 'C']:
    mask = (group == g)
    fig.add_trace(go.Scatter3d(
        x=x[mask], y=y[mask], z=z[mask],
        mode='markers',
        marker=dict(size=4, color=colors[g], opacity=0.8),
        name=f'Group {g}'        # ← これが凡例に表示される
    ))

fig.update_layout(
    title="3D Scatter with Legend (Groups)",
    scene=dict(aspectmode='data')
)

fig.show()

各traceのname=が凡例として自動表示されます。凡例のON/OFFクリックでグループの表示切り替えも可能。

image.png

2. 3D空間に「軸線」を追加する

3D散布図では、X=0, Y=0, Z=0の軸があると"どの方向に広がっているのか"が一目でわかりやすくなります。

中心軸(X軸・Y軸・Z軸)を追加

# 軸線を描くための座標(長さはデータ範囲に合わせる)
axis_len = 3

axes = [
    dict(name='X-axis', xs=[-axis_len, axis_len], ys=[0,0], zs=[0,0], color='black'),
    dict(name='Y-axis', xs=[0,0], ys=[-axis_len, axis_len], zs=[0,0], color='black'),
    dict(name='Z-axis', xs=[0,0], ys=[0,0], zs=[-axis_len, axis_len], color='black')
]

fig = go.Figure()

# 点群(A〜C)
for g in ['A', 'B', 'C']:
    mask = (group == g)
    fig.add_trace(go.Scatter3d(
        x=x[mask], y=y[mask], z=z[mask],
        mode='markers',
        marker=dict(size=4, color=colors[g], opacity=0.8),
        name=f'Group {g}'
    ))

# 軸線(lines)
for ax in axes:
    fig.add_trace(go.Scatter3d(
        x=ax['xs'], y=ax['ys'], z=ax['zs'],
        mode='lines',
        line=dict(color=ax['color'], width=6),
        name=ax['name'],
        showlegend=True
    ))

fig.update_layout(
    title="3D Scatter with Legend + Axes",
    scene=dict(aspectmode='data')
)

fig.show()

image.png

軸線追加のポイント

要素 内容
mode='lines' 2点を結ぶ線で軸を描画する
line.width=6 軸線を太めにして強調
showlegend=True 凡例にも軸名を表示可能
axis_len 自由に長さを設定(データ範囲に合わせる)

3Dグラフでは、軸が"空間の基準"になるため、分布が理解しやすくなります。

3. 背景・グリッドを整えて見やすくする

fig.update_layout(
    scene=dict(
        xaxis=dict(backgroundcolor='rgb(240,240,240)', gridcolor='white'),
        yaxis=dict(backgroundcolor='rgb(240,240,240)', gridcolor='white'),
        zaxis=dict(backgroundcolor='rgb(245,245,245)', gridcolor='white'),
        aspectmode='data'
    )
)
fig.show()

背景が整うことで、点群と軸線がさらに見やすくなり、3D全体の空間構造が理解しやすくなります。
image.png

まとめ

image.png

凡例をnameで設定し、軸線をlinesで追加するだけで、3D散布図の見やすさが大きく向上します。
背景を整えることで奥行きや立体感が伝わりやすくなり、クラスタリングや特徴量分析、PCAの可視化にも活用できます。
少し手を加えるだけで、3D散布図がぐっと“読める可視化”になります。

参考情報

3
3
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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?