我正在尝试使用 python matplotlib 绘制一个蜂窝动画,其中每个六边形逐渐添加(以螺旋方式向外,每次刷新时添加 1 个六边形(例如 200 毫秒))。我以前使用过 matplotlib 动画,并且我知道如何使用补丁的 对单个补丁进行动画处理/翻译set_xy()
,然后从 animate 函数返回该特定补丁。
但是在这个特定的项目中,我每次都尝试从 animate 函数中创建一个新的补丁/六边形,这让我卡住了。正如您从下面我当前的代码中看到的那样,现在我只是使用一种原始方法来添加一个新的六边形“层”并重复 3 次。它没有做我想要的动画,它增加了一整层六边形,而不仅仅是一个六边形。
如果有人可以指导我如何添加更多的多边形/补丁,而不是仅仅翻译一个补丁,那么在每个动画帧中,我将很高兴继续我的正确编码的追求。
import matplotlib.animation as animation
import matplotlib.pyplot as plt
import matplotlib.path as mpltPath
from matplotlib.patches import Polygon as poly
import numpy as np
import time
fig, ax = plt.subplots()
ax.set_aspect('equal')
plt.xlim(-5, 5)
plt.ylim(-5, 5)
class Hex():
registry = []
radius = 0.5
dist_apart = radius * np.cos(np.radians(30))*1.1
def __init__(self, center):
global ax
self.idx = len(self.__class__.registry)
self.center = center
self.vertices = self.__class__.create_vertices(self.center)
self.__class__.registry.append(self)
ax.add_patch(poly(self.vertices, fill = False))
@classmethod
def check_is_occupied(cls, center):
path = mpltPath.Path(cls.create_vertices(center))
for each_hex in cls.registry:
if path.contains_point(each_hex.center):
return True
else:
return False
@classmethod
def create_vertices(cls, center):
return np.transpose(np.array([cls.radius*(np.cos(np.radians(np.linspace(0, 300, 6))))+center[0], cls.radius*(np.sin(np.radians(np.linspace(0, 300, 6))))+center[1]]))
def fill_surround(self):
for pos in range(6):
new_center = [self.center[0] + self.__class__.dist_apart*2*np.sin(np.radians(60*(pos%6))), self.center[1] + self.__class__.dist_apart*2*np.cos(np.radians(60*(pos%6)))]
if not self.__class__.check_is_occupied(new_center):
Hex(new_center)
a = Hex([0,0])
lister = list(Hex.registry)
for each in lister:
each.fill_surround()
lister = list(Hex.registry)
for each in lister:
each.fill_surround()
lister = list(Hex.registry)
for each in lister:
each.fill_surround()
plt.show()