這裏我們用到matplotlib、numpy和Axes3D庫
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
點線圖:
print("點線圖")
fig = plt.figure()
ax = Axes3D(fig)
X = np.arange(0,20,0.25)
Y = np.arange(0,20,0.25)
Z = np.sin(X+Y)
ax.plot(X,Y,Z,color='red',linestyle="--")
plt.show()
散點圖:
print("散點圖")
fig = plt.figure()
ax = Axes3D(fig)
for c,m,zlow,zhigh in [("r","o",0,8),("b","^",7,15)]:
x = np.random.uniform(0,10,100)
y = np.random.uniform(0,10,100)
z = np.random.uniform(zlow,zhigh,100)
ax.scatter(x,y,z,color=c,marker=m)
plt.show()
表面圖:
print("表面圖")
fig = plt.figure()
ax = Axes3D(fig)
arr1 = np.array([1,2,3])
arr2 = np.array([4,5])
np.meshgrid(arr1,arr2) #(1,5) (2,5) (3,5) (1.4) (2.4) (3,4)
print(np.meshgrid(arr1,arr2))
x = np.arange(-5,5,0.25)
y = np.arange(-5,5,0.25)
x,y = np.meshgrid(x,y)
r = np.sqrt(x**2+y**2)
z = np.sin(r)
ax.plot_surface(x,y,z,rstride=5,cstride=5,cmap="rainbow") #cmap是顏色
plt.show()
將一個2D圖變成3D:
print("2D圖畫在3D圖上")
fig = plt.figure()
ax = Axes3D(fig)
x = np.arange(0,20,0.5)
y = np.sin(x)
# !!!! plt.畫圖函數(二維),ax.畫圖函數(三維)
plt.plot(x,y)
plt.show()
ax.plot(x,y,zs=0,zdir="y",color="orange") #zdir:把某個軸的值變成z軸
plt.show()
for c,z in zip(["r","y","b","g"],[30,20,10,0]):
ax.plot(x,y,zs = z,zdir="y" ,color=c)
plt.show()
print("柱狀圖2D轉3D")
fig = plt.figure()
ax = Axes3D(fig)
x = np.arange(0,7)
y = np.random.uniform(2,20,7)
for c,z in zip(["r","y","b","g"],[30,20,10,0]):
ax.bar(x,y,z,zdir="y",color=c,alpha=0.8)
plt.xlabel("X")
plt.ylabel("Y")
ax.set_zlabel("Z")
plt.show()
用matplotlib畫動態圖:
print("用matplotlib畫動態圖")
plt.ion()
plt.show()
x = np.random.uniform(0,10,100)
y = np.random.uniform(0,10,100)
for c in ["r","y","b","g"]:
plt.scatter(x,y,color=c)
plt.pause(1) #表示時間間隔,單位是秒
plt.ioff()
plt.show()
友情鏈接:http://dublogger.cn/