Matplotlibで3次元の散布図を描画する

コード

from matplotlib import pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d.axes3d import Axes3D

#グラフをポップアップで表示する設定
%matplotlib qt

#適当にデータを生成する。
X = np.array([1,4,6,8,9,3,5,3,5,6])
Y = np.array([5,9,5,1,2,4,3,7,8,9])
Z = np.array([2,4,6,5,0,2,7,4,5,1])

fig = plt.figure()
ax = Axes3D(fig)

ax.scatter(X,Y,Z,c='blue',alpha=0.3,label='test')

ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')

ax.legend()

plt.show()

グラフポップアップで表示すると、ドラッグ&ドロップでグラフを動かすことができる。

球を書いてみた。

#媒介変数表示を利用して球を書いてみる
#参考:https://manabitimes.jp/math/1029
fig = plt.figure()
ax = Axes3D(fig)

r = 1.5 # 半径を指定
theta_1_0 = np.linspace(0, np.pi*2, 100) 
theta_2_0 = np.linspace(0, np.pi*2, 100)
theta_1, theta_2 = np.meshgrid(theta_1_0, theta_2_0)

#x,y,zの曲座標表示 
x = np.cos(theta_2)*np.sin(theta_1) * r 
y = np.sin(theta_2)*np.sin(theta_1) * r
z = np.cos(theta_1) * r

ax.plot_wireframe(x, y, z, color="red",alpha=0.1, linewidth=0.5) 
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')

ax.legend()

plt.show()

以上

関連書籍