繪製三維圖:dom
mplot3d工具包提供了點、線、等值線、曲面和全部其餘基本組件以及三維旋轉縮放的三維繪圖。ide
1.散點的三維數據圖工具
from mpl_toolkits.mplot3d import axes3d #須要從mplot3d模塊中導入axes 3D類型spa
import numpy as np3d
import matplotlib.pyplot as pltorm
fig=plt.figure()對象
ax=fig.gca(projection='3d') #經過將關鍵字projection='3d'應用到座標軸對象上來實現三維繪圖blog
class1=0.6*np.random.standard_normal((200,3))ip
ax.plot(class1[:,0],class1[:,1],class1[:,2],'o')get
class2=1.2*np.random.standard_normal((200,3))+np.array([5,4,0])
ax.plot(class2[:,0],class2[:,1],class2[:,2],'o')
class3=0.3*np.random.standard_normal((200,3))+np.array([0,3,2])
ax.plot(class3[:,0],class3[:,1],class3[:,2],'o')
2. 表面圖(Surface plots)
基本用法:ax.plot_surface(X,Y,Z,alpha=0.5)
X,Y,Z:數據 color:代表顏色 cmap:圖層
示例:
from mpl_toolkits.mplot3d import axes3d
import numpy as np
import matplotlib.pyplot as plt
fig=plt.figure()
ax=fig.gca(projection='3d')
X,Y,Z=axes3d.get_test_data(0.05)
ax.plot_surface(X,Y,Z,alpha=0.5)
3. 線框圖(Wireframe plots)
基本用法:ax.plot_wireframe(X, Y, Z, *args, **kwargs)
示例:
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
fig=plt.figure()
ax=fig.gca(projection='3d')
X,Y,Z=axes3d.get_test_data(0.05)
ax.plot_wireframe(X,Y,Z,rstride=5,cstride=5)
ax.contour(X,Y,Z,zdir='z',offset=-100) #等高線
ax.contour(X,Y,Z,zdir='x',offset=-40)
ax.contour(X,Y,Z,zdir='y',offset=40)
ax.set_xlim3d(-40,40) #設置座標軸極限的標準
ax.set_ylim3d(-40,40)
ax.set_zlim3d(-100,100)
ax.set_xlabel('X axis') #設置標籤的命令
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
#結果圖:
4. 散點繪製(Scatter plots)
基本用法:ax.scatter(xs, ys, zs, s=20, c=None, depthshade=True, *args, *kwargs)
示例:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
def randrange(n, vmin, vmax):
'''
Helper function to make an array of random numbers having shape (n, )
with each number distributed Uniform(vmin, vmax).
'''
return (vmax - vmin)*np.random.rand(n) + vmin
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
n = 100
for c, m, zlow, zhigh in [('r', 'o', -50, -25), ('b', '^', -30, -5)]:
xs = randrange(n, 23, 32)
ys = randrange(n, 0, 100)
zs = randrange(n, zlow, zhigh)
ax.scatter(xs, ys, zs, c=c, marker=m)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()
#結果圖以下:
5.條形圖(Bar plots)
基本方法:ax.bar(left, height, zs=0, zdir='z', *args, **kwargs
示例:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
for c, z in zip(['r', 'g', 'b', 'y'], [30, 20, 10, 0]):
xs = np.arange(20)
ys = np.random.rand(20)
cs = [c] * len(xs)
cs[0] = 'c'
ax.bar(xs, ys, zs=z, zdir='y', color=cs, alpha=0.8)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show() #結果圖: