Matplotlib による 3D プロット上の 2D データ

Beginner

This tutorial is from open-source community. Access the source code

はじめに

この実験では、ax.plotzdir キーワードを使用して、3D プロットの特定の軸に 2D データをプロットする方法を示します。Python の matplotlib ライブラリを使用して 3D プロットを作成します。

VM のヒント

VM の起動が完了したら、左上隅をクリックして ノートブック タブに切り替え、Jupyter Notebook を使用して練習します。

場合によっては、Jupyter Notebook が読み込み完了するまで数秒待つ必要があります。Jupyter Notebook の制限により、操作の検証を自動化することはできません。

学習中に問題が発生した場合は、Labby にお問い合わせください。セッション後にフィードバックを提供してください。そうすれば、迅速に問題を解決します。

ライブラリのインポート

最初のステップは、必要なライブラリをインポートすることです。3D グラフをプロットするには、matplotlibnumpy が必要です。

import matplotlib.pyplot as plt
import numpy as np

3D プロットの作成

2 番目のステップは、ax = plt.figure().add_subplot(projection='3d') を使用して 3D プロットを作成することです。

ax = plt.figure().add_subplot(projection='3d')

3D プロットに 2D データをプロットする

3 番目のステップは、ax.plotax.scatter を使用して 3D プロットに 2D データをプロットすることです。ax.plot 関数は、x 軸と y 軸を使用してサインカーブをプロットします。ax.scatter 関数は、x 軸と z 軸に散布図データをプロットします。

## Plot a sin curve using the x and y axes.
x = np.linspace(0, 1, 100)
y = np.sin(x * 2 * np.pi) / 2 + 0.5
ax.plot(x, y, zs=0, zdir='z', label='curve in (x, y)')

## Plot scatterplot data (20 2D points per colour) on the x and z axes.
colors = ('r', 'g', 'b', 'k')

## Fixing random state for reproducibility
np.random.seed(19680801)

x = np.random.sample(20 * len(colors))
y = np.random.sample(20 * len(colors))
c_list = []
for c in colors:
    c_list.extend([c] * 20)
## By using zdir='y', the y value of these points is fixed to the zs value 0
## and the (x, y) points are plotted on the x and z axes.
ax.scatter(x, y, zs=0, zdir='y', c=c_list, label='points in (x, z)')

プロットのカスタマイズ

4 番目のステップは、凡例を追加し、軸の範囲とラベルを設定し、視点を変更することでプロットをカスタマイズすることです。

## Make legend, set axes limits and labels
ax.legend()
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.set_zlim(0, 1)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

## Customize the view angle so it's easier to see that the scatter points lie
## on the plane y=0
ax.view_init(elev=20., azim=-35, roll=0)

plt.show()

プロットを表示する

最後のステップは、コードを実行して 3D プロットを表示することです。

まとめ

この実験では、ax.plotzdir キーワードを使用して、3D プロットの特定の軸に 2D データをプロットする方法を学びました。また、凡例を追加し、軸の範囲とラベルを設定し、視点を変更することでプロットをカスタマイズする方法も学びました。