使用matplotlib绘制动画二维网格

2024-06-25 06:18:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要创建一个函数来使用python3.5+Matplotlib绘制动画二维有限元。基本上,我有节点坐标和它们的连通性,以及不同时刻节点值的矩阵:

值[i,j]:第i个节点在第j个时间瞬间的节点值。

我在网上找到了很多例子(比如in here),但没有一个真正帮助我解决问题。在

这是我做的代码。它在一个时间瞬间绘制网格:

import numpy as np
import matplotlib
matplotlib.use('TkAgg')
#---
from matplotlib import pyplot as plt
from matplotlib.collections import PolyCollection
from matplotlib import animation as animation
#---

nelements    = 32
nodesperside = 5
nnodes       = nodesperside*nodesperside
(xmin, xmax) = (0.0, 1.0)
(ymin, ymax) = (0.0, 1.0)
ntimes       = 10

x = np.linspace(xmin, xmax, nodesperside)
y = np.linspace(ymin, ymax, nodesperside)

xx, yy = np.meshgrid(x, y)

xc = np.reshape(xx, (nnodes, ))
yc = np.reshape(yy, (nnodes, ))

nodenum = np.linspace(0,  nnodes - 1, nnodes)

coord       = np.zeros((nnodes, 3))
coord[:, 0] = nodenum
coord[:, 1] = xc
coord[:, 2] = yc

#---
# Conectividade global:
connect = np.zeros((nelements, 4), dtype = 'int')
connect[:, 0] = np.ones((nelements))
connect[ 0, 1: 4] = np.array([0, 1, 6])
connect[ 1, 1: 4] = np.array([1, 2, 7])
connect[ 2, 1: 4] = np.array([2, 3, 8])
connect[ 3, 1: 4] = np.array([3, 4, 9])
connect[ 4, 1: 4] = np.array([0, 6, 5])
connect[ 5, 1: 4] = np.array([1, 7, 6])
connect[ 6, 1: 4] = np.array([2, 8, 7])
connect[ 7, 1: 4] = np.array([3, 9, 8])
connect[ 8, 1: 4] = np.array([5, 6, 11])
connect[ 9, 1: 4] = np.array([6, 7, 12])
connect[10, 1: 4] = np.array([7, 8, 13])
connect[11, 1: 4] = np.array([8, 9, 14])
connect[12, 1: 4] = np.array([5, 11, 10])
connect[13, 1: 4] = np.array([6, 12, 11])
connect[14, 1: 4] = np.array([7, 13, 12])
connect[15, 1: 4] = np.array([8, 14, 13])
connect[16, 1: 4] = np.array([10, 11, 16])
connect[17, 1: 4] = np.array([11, 12, 17])
connect[18, 1: 4] = np.array([12, 13, 18])
connect[19, 1: 4] = np.array([12, 14, 19])
connect[20, 1: 4] = np.array([10, 16, 15])
connect[21, 1: 4] = np.array([11, 17, 16])
connect[22, 1: 4] = np.array([12, 18, 17])
connect[23, 1: 4] = np.array([13, 19, 18])
connect[24, 1: 4] = np.array([15, 16, 21])
connect[25, 1: 4] = np.array([16, 17, 22])
connect[26, 1: 4] = np.array([17, 18, 23])
connect[27, 1: 4] = np.array([18, 19, 24])
connect[28, 1: 4] = np.array([15, 21, 20])
connect[29, 1: 4] = np.array([16, 22, 21])
connect[30, 1: 4] = np.array([17, 23, 22])
connect[31, 1: 4] = np.array([18, 24, 23])
#---

pressao = np.zeros((nnodes, ntimes))
for col in range(ntimes):
    pressao[:, col] = col*np.ones((nnodes))

vertices = list()
for elemento in range(nelements):
    nodes = connect[elemento, 1: 4]
    vertices.append(list(zip(coord[nodes, 1], coord[nodes, 2])))

pi      = pressao[:, 1]
colecao = PolyCollection(vertices, array = pi, edgecolors = 'b')
fig, ax = plt.subplots()
ax.add_collection(colecao)
ax.autoscale_view()
fig.colorbar(colecao, ax = ax)
plt.show()

有没有什么可以简化的,就像在Matlab中一样:

^{pr2}$

这里有谁能告诉我如何创建动画情节函数吗?在

提前谢谢大家


Tags: infromimport节点matplotlibasconnectnp