我為創建 x、y 和 t 的 3D 陣列的 2D 擴散方程創建了 pcolormesh。特定 t 的靜態二維圖很簡單。我怎樣才能在所有的時間步長上設定影片?
我使用以下方法創建我的 3D 陣列:
set array for x and y
grid_size = 100
t_iter = 1000
D = .01
length = 1.0
tmax = 1.0
dx = dy = length/grid_size
dt = tmax/t_iter
rho = np.zeros((grid_size, grid_size, t_iter))
#rho[:] = 1.2
rho[grid_size//2, grid_size//2, 0] = 1.2 # set the initial configuration
for n in range(t_iter-1):
for j in range(grid_size-1):
for i in range(grid_size-1):
pxx = rho[i 1,j,n] rho[i-1,j,n] - 2*rho[i,j,n]
pyy = rho[i,j 1,n] rho[i,j-1,n] - 2*rho[i,j,n]
rho[i,j,n 1] = D*dt*(pxx/dx**2 pyy/dy**2)
我可以使用 pcolormesh(沒有標簽和東西)為 t 的特定值繪制資料:
plt.pcolormesh(rho[:,:,500])

我試過這個,但它沒有“影片”任何東西。我錯過了什么?
from matplotlib.animation import FuncAnimation
fig, ax = plt.subplots()
mesh = ax.pcolormesh(rho[:,:,0])
def animate(i):
ax.pcolormesh(rho[:,:,i])
anim = FuncAnimation(fig, animate, interval=10, frames=t_iter-1, repeat=False)
plt.draw()
plt.show()

uj5u.com熱心網友回復:
出了三件事:
- 在 中
animate(),應更新網格。mesh.set_array()設定新值。作為內部資料結構需要一維陣列,該二維陣列,應“弄清”:mesh.set_array(rho[:, :, i].ravel())。 animate()應該回傳已更改元素的串列。后面的逗號return mesh,是 Python 的一種方法,可以創建一個只有一個元素的“元組”。- 這里最棘手的問題是最好所有影像都使用相同的顏色映射。
vmin告訴哪個值映射到“最低”顏色(默認 viridis 映射中的深紫色),而vmax對應于“最高”顏色(viridis 中的黃色)的值。如果他們是凈一套明確,matplotlib會計算它們的最小和最大的第一形象,0而1.2在這種情況下。這些值不適用于其他影像。通常,整體最小值和最大值給出合適的值。但是,在這種情況下,影像的“有趣”部分的范圍要窄得多。我嘗試使用第 1 個和第 99 個百分位數,這似乎效果很好,但您可能希望調整這些值。
更新后的代碼:
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
grid_size = 100
t_iter = 1000
D = .01
length = 1.0
tmax = 1.0
dx = dy = length / grid_size
dt = tmax / t_iter
rho = np.zeros((grid_size, grid_size, t_iter))
# rho[:] = 1.2
rho[grid_size // 2, grid_size // 2, 0] = 1.2 # set the initial configuration
for n in range(t_iter - 1):
for j in range(grid_size - 1):
for i in range(grid_size - 1):
pxx = rho[i 1, j, n] rho[i - 1, j, n] - 2 * rho[i, j, n]
pyy = rho[i, j 1, n] rho[i, j - 1, n] - 2 * rho[i, j, n]
rho[i, j, n 1] = D * dt * (pxx / dx ** 2 pyy / dy ** 2)
fig, ax = plt.subplots()
mesh = ax.pcolormesh(rho[:, :, 0], vmin=np.percentile(rho.ravel(), 1), vmax=np.percentile(rho.ravel(), 99))
def animate(i):
mesh.set_array(rho[:, :, i].ravel())
return mesh,
anim = FuncAnimation(fig, animate, interval=10, frames=t_iter, repeat=False)
plt.show()
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/336816.html
標籤:Python matplotlib jquery-动画
下一篇:HowtoPlotin3DPrincipalComponentAnalysisVisualizations,usingthefastPCAscriptfromthisanswer
