matplotlibで3Dプロット

matplotlibの三次元プロットで複数axisを生成する方法がありましたので、コードを書いてみました。

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

N = 20

fig = plt.figure(figsize = (8, 6))

ax = fig.add_subplot(2, 2, 1, projection = '3d', azim = 0)
bx = fig.add_subplot(2, 2, 2, projection = '3d', azim = 30)
cx = fig.add_subplot(2, 2, 3, projection = '3d', azim = 120)
dx = fig.add_subplot(2, 2, 4, projection = '3d', azim = 210)

axes = [ax, bx, cx, dx]
colors = ['red', 'blue', 'green', 'orange']
markers = ['o', '^', 'x', 'D']

for axis, i in zip(axes, range(4)):
	np.random.seed(i)
	
	sample = np.random.uniform(0, 3, size = (N, 3))
	
	X = sample[:, 0]
	Y = sample[:, 1]
	Z = sample[:, 2]
	
	axis.scatter(X, Y, Z, color = colors[i], marker = markers[i], alpha = .5)
	
	axis.set_xlabel(r'X axis')
	axis.set_ylabel('Y axis')
	axis.set_zlabel('Z axis')
	
	axis.set_xlim(0, 3.5)
	axis.set_ylim(0, 3.5)
	axis.set_zlim(0, 3.5)
	
	axis.set_xticks(range(4))
	axis.set_yticks(range(4))
	axis.set_zticks(range(4))	
	
	axis.set_xticklabels(range(4))
	axis.set_yticklabels(range(4))
	axis.set_zticklabels(range(4))
	
	
	
	axis.grid(True)


fig.tight_layout()
plt.show()

こんな感じの図が得られると思います。

f:id:jinpei0908:20160822185853p:plain

三次元プロットが一つでいい場合は

ax = Axes3D(fig)

のように書いても大丈夫ですが、いくつか並べる必要があるときには上記のやり方でやったほうがいいと思います。

あと乱数生成の時に先にnp.random.seedと書くとその直後に生成される乱数は固定のものが出てきます。

import numpy as np

np.random.seed(0)

print(np.random.randn(6, 2))
print('\n')

print(np.random.randn(6, 2))
print('\n')
np.random.seed(0)

print(np.random.randn(6, 2))
print('\n')

とすると

[[ 1.76405235 0.40015721]
[ 0.97873798 2.2408932 ]
[ 1.86755799 -0.97727788]
[ 0.95008842 -0.15135721]
[-0.10321885 0.4105985 ]
[ 0.14404357 1.45427351]]


[[ 0.76103773 0.12167502]
[ 0.44386323 0.33367433]
[ 1.49407907 -0.20515826]
[ 0.3130677 -0.85409574]
[-2.55298982 0.6536186 ]
[ 0.8644362 -0.74216502]]


[[ 1.76405235 0.40015721]
[ 0.97873798 2.2408932 ]
[ 1.86755799 -0.97727788]
[ 0.95008842 -0.15135721]
[-0.10321885 0.4105985 ]
[ 0.14404357 1.45427351]]
となります。

参考は以下に

bicycle1885.hatenablog.com

http://d.hatena.ne.jp/sobasobasoba/touch/20131230/1388367688http://d.hatena.ne.jp/sobasobasoba/touch/20131230/1388367688d.hatena.ne.jp