# 六角形メッシュでアニメーション(python) まず、ライブラリをインポートする。 ``` "" $-1 library import$ """ import numpy as np import matplotlib.pyplot as plt import math import random random.seed(314) import matplotlib.animation as animation ``` 次に、六角形を生成する。 ``` """ $0 parameter input$ """ w = math.sqrt(3) h = w/2 N = 2000 #number of mesh num_x = 50 #x方向の長さ num_y = 40 #y方向の長さ #num_x have to devide N T = 100 """ $1 making polygon$ """ def hexagonal_mesh(n_mesh, x_o, y_o): x1 = np.array([-0.5, 0.5, 1, 0.5, -0.5, -1]) y1 = np.array([h, h, 0, -h, -h ,0]) xl=list() yl=list() for i in range(n_mesh): x_center = x_o + 3/2 * (i % num_x) #真ん中のx座標 y_center = y_o - 2 * h * int(i / num_x) if i %2 == 0 else y_o + h - 2 * h * int(i / num_x) #真ん中のy座標 if x_center ** 2 + y_center ** 2 >= 200: continue xl.append(x1 + x_center) if i % 2 == 0: yl.append(y1 + y_center) else: yl.append(y1 + y_center) return (np.array(xl), np.array(yl)) ``` 今回は試しに、六角形を色塗りしてみる。 ``` """ $2 defining color of polygon$ """ def col(x): if x % 6 in (0, 1): return "red" elif x % 6 in (2, 3): return "orange" elif x % 6 in (4, 5): return "blue" ``` 最後に、アニメーションにしてみる。 ``` """ $3 making animation$ """ fig = plt.figure() ax = fig.add_subplot(111) ax.set_aspect('equal') ax.axis("off") xl, yl = hexagonal_mesh(N, -3 / 4 * num_x, h * num_y) ims = [] for j in range(T): im = plt.fill(xl[0],yl[0],fc=col(j)) for i in range(1,len(xl)): poly = plt.fill(xl[i],yl[i],fc=col(i+j)) im = im + poly ims.append(im) ani = animation.ArtistAnimation(fig, ims, interval=100) ani.save("hexagonal_mesh_simple.gif", writer="imagemagick") plt.show() ``` 出来上がったアニメーションがこちら。 ![スクリーンショット 2024-03-08 15.36.35](https://hackmd.io/_uploads/rk8VzNdp6.png) 上手く行っているが、アニメーションにするのに時間がかかる印象があった。 四角形メッシュでは、"imshow"が使えたから早かったのか??? 素早く六角形メッシュを塗り分けるコードを作りたい。