首頁 > 軟體

matplotlib 3D模型繪製一朵小紅花

2022-02-16 13:01:07

前言:

在github上看到一個有趣的程式碼,雖然情人節已經過了兩天,但還是想和大家分享^_^

1. 含苞待放

  3D模型的繪製需要網格點,關於網格點的作用,在基於python,Matplotlib繪製函數的等高線與三維影象的博文中已經介紹,這裡不再贅述。

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

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

x = np.linspace(0, 1, num=30)
t = np.linspace(0, 1, num=1200) * 20 * np.pi + 4 * np.pi
x, t = np.meshgrid(x, t)

p = 0.5 * np.pi * np.exp(-t / (8 * np.pi))
change = np.sin(15 * t) / 150
u = 1 - (1 - np.mod(3.3 * t, 2 * np.pi) / np.pi)**4 / 2 + change
y = 2 * (x**2 - x)**2 * np.sin(p)
r = u * (x * np.sin(p) + y * np.cos(p)) * 1.5
h = u * (x * np.cos(p) - y * np.sin(p))

# PiYG_r
# RdBu_r
surf = ax.plot_surface(r * np.cos(t), r * np.sin(t), h,
                       rstride=1, cstride=1, cmap=plt.cm.RdPu_r)
plt.savefig('img/img1.png')
plt.show()

2. 灼灼其華

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

fig = plt.figure()
ax = Axes3D(fig)
# plt.axis('off')

x = np.linspace(0, 1, num=30)
t = np.linspace(0, 1, num=1200) * 50 * np.pi - 4 * np.pi
x, t = np.meshgrid(x, t)

p = 0.5 * np.pi * np.exp(-t / (8 * np.pi))
change = np.sin(20 * t) / 50
u = 1 - (1 - np.mod(3.3 * t, 2 * np.pi) / np.pi)**4 / 2 + change
y = 2 * (x**2 - x)**2 * np.sin(p)
r = u * (x * np.sin(p) + y * np.cos(p)) * 1.5
h = u * (x * np.cos(p) - y * np.sin(p))

ax = ax.plot_surface(r * np.cos(t), r * np.sin(t), h,
                     rstride=1, cstride=1, cmap=plt.cm.RdPu_r)

plt.savefig('img/img2.png')
plt.show()

有關mpl_toolkits.mplot3d的使用可以參考官方檔案

更多的顏色搭配可參考matplotlib的colormap官方手冊

 到此這篇關於matplotlib 3D模型繪製一朵小紅花的文章就介紹到這了,更多相關3D模型繪製內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com