カンテラの光の下で

dNaga392's memorandom

【matplotlib】散布図を3D描画する

要点

使用例

import matplotlib.pyplot as plt
import seaborn as sns
from mpl_toolkits.mplot3d import axes3d  # Axes3D のために必要

df = sns.load_dataset('iris')
xs = df['sepal_length']
ys = df['sepal_width']
zs = df['petal_length']

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

ax.scatter(xs, ys, zs)

ax.set_title('Matplot 3d scatter plot')  # タイトル
ax.set_xlabel('sepal_length')  # X軸ラベル
ax.set_ylabel('sepal_width')  # Y軸ラベル
ax.set_zlabel('petal_length')  # Z軸ラベル

plt.show()

mpl-ax3d-scatter.png

特定のグループごとに描画する場合

hue = 'species'
labels = set(df[hue])
dataset = []
for x in labels:
    xs = df[df[hue]==x]['sepal_length']
    ys = df[df[hue]==x]['sepal_width']
    zs = df[df[hue]==x]['petal_length']
    dataset.append((xs, ys, zs))

fig = plt.figure()

ax = fig.add_subplot(1, 1, 1, projection='3d')
for data, label in zip(dataset, labels):
    ax.scatter(xs, ys, zs, label=label)
ax.set_title('Matplot 3d scatter plot')  # タイトル
ax.set_xlabel('sepal_length')  # X軸ラベル
ax.set_ylabel('sepal_width')  # Y軸ラベル
ax.set_zlabel('petal_length')  # Z軸ラベル
ax.legend(loc=2, title='legend', shadow=True)  # 凡例

plt.show()

mpl-ax3d-scatter-hue.png