在常熟市公司網(wǎng)站建設(shè)哪家好蘇州seo安嚴(yán)博客
文章目錄
- 頂點(diǎn)
- 棱
- 實(shí)現(xiàn)正二十面體
plotly 的 Python 軟件包是一個(gè)開源的代碼庫,它基于 plot.js,而后者基于 d3.js。我們實(shí)際使用的則是一個(gè)對(duì) plotly 進(jìn)行封裝的庫,名叫 cufflinks,能讓你更方便地使用 plotly 和 Pandas 數(shù)據(jù)表協(xié)同工作。
一言以蔽之,plotly是一款擅長交互的Python繪圖庫,下面就初步使用一下這個(gè)庫的三維繪圖功能。此前曾經(jīng)用matplotlib畫了正二十面體和足球:Python繪制正二十面體;畫足球,這次用plotly復(fù)現(xiàn)一下正二十面體的繪制過程,也體驗(yàn)一下這兩個(gè)繪圖包的差異。
來繪制一個(gè)正二十面體。
頂點(diǎn)
正20面體的12個(gè)頂點(diǎn)剛好可以分為三組,每一組都是一個(gè)符合黃金分割比例的長方形,而且這三個(gè)長方形是互相正交的。
所以,想繪制一個(gè)正二十面體是比較容易的
import plotly
import plotly.express as px
import numpy as np
from itertools import product
G = (np.sqrt(5)-1)/2
def getVertex():pt2 = [(a,b) for a,b in product([1,-1], [G, -G])]pts = [(a,b,0) for a,b in pt2]pts += [(0,a,b) for a,b in pt2]pts += [(b,0,a) for a,b in pt2]return np.array(pts)xs, ys, zs = getVertex().Tfig = px.scatter_3d(x=xs, y=ys, z=zs, size=np.ones_like(xs)*0.5)
fig.show()
得到頂點(diǎn)
棱
接下來連接這12個(gè)頂點(diǎn),由于點(diǎn)數(shù)較少,所以直接遍歷也不至于運(yùn)算量爆炸。另一方面,正二十面體邊長相同,而這些相同的邊連接的也必然是最近的點(diǎn),所以接下來只需建立頂點(diǎn)之間的距離矩陣,并抽取出距離最短的線。
def getDisMat(pts):N = len(pts)dMat = np.ones([N,N])*np.inffor i in range(N):for j in range(i):dMat[i,j] = np.linalg.norm([pts[i]-pts[j]])return dMatpts = getVertex()
dMat = getDisMat(pts)
# 由于存在舍入誤差,所以得到的邊的數(shù)值可能不唯一
ix, jx = np.where((dMat-np.min(dMat))<0.01)
接下來,繪制正二十面體的棱
edges = []
for k in range(len(ix)):edges.append(pts[ix[k]].tolist() + [k])edges.append(pts[jx[k]].tolist() + [k])edges = np.array(edges)fig = px.line_3d(edges, x=0, y=1, z=2, color=3)
fig.show()
效果如圖所示
實(shí)現(xiàn)正二十面體
接下來要對(duì)面上色。由于三棱成個(gè)面,所以只需得到所有三條棱的組合,只要這三條棱可以組成三角形,就能獲取所有的三角面。當(dāng)然,這一切的前提是,正二十面體只有30個(gè)棱,即使遍歷多次,也無非27k的計(jì)算量,是完全沒問題的。
def isFace(e1, e2, e3):pts = np.vstack([e1, e2, e3])pts = np.unique(pts, axis=0)return len(pts)==3edges = [pts[[i,j]] for i,j in zip(ix, jx)]
from itertools import combinations
faces = [es for es in combinations(edges, 3) if isFace(*es)]
最后得到的faces
有20個(gè)元素,每個(gè)元素由3條棱組成,每條棱有兩個(gè)頂點(diǎn),故而可以縮減為三個(gè)頂點(diǎn)。
ptFace = [np.unique(np.vstack(f),axis=0) for f in faces]
ptFace = np.vstack(ptFace)
接下來繪制一下,plotly
繪制三角面的邏輯是,除了需要指定三角面的三個(gè)坐標(biāo)之外,還需指定三角面的頂點(diǎn)序號(hào)
import plotly.figure_factory as ff
simplices = np.arange(len(ptFace)).reshape(-1,3)
fig = ff.create_trisurf(x=ptFace[:,0], y=ptFace[:,1], z=ptFace[:,2],simplices=simplices)
fig.show()
效果如下