我正在尝试制作一个动画,其中PatchCollection
围绕原点旋转。最简单的方法似乎是使用FuncAnimation
根据关于matplotlib change a Patch in PatchCollection的回答,我正在使用PatchCollection
类的扩展,它允许我更新各个补丁的位置
动画函数仅调用其中一个类方法并返回已更新的集合:
fig, ax = plt.subplots(1)
grid = HexagonalGrid()
ax.add_collection(grid)
def animate(frame):
grid.rotateGrid(0.1)
return (grid,)
anim = anim.FuncAnimation(fig, animate, blit=True)
使用RegularPolygon
补丁时,所有补丁都可以正常工作:
class HexagonalGrid(UpdateablePatchCollection):
def __init__(self, latticeParameter = 5):
self.patches = self._initiatePatches(hexRadius)
UpdateablePatchCollection.__init__(self, self.patches, match_original=True, animated=True)
def _initiatePatches(self, hexRadius):
patches = []
for :
#calculates the correct starting position for each patch
patches.append(self._createHex(x,y,hexRadius))
def _createHex(self, x,y, hexRadius):
return matplotlib.patches.RegularPolygon(
(x, y),
numVertices = 6,
radius = hexRadius,
orientation = 0,
fc = (0.1, 0.1, 0.1, 0.1), # fill colour RGBA (black and transparent)
ec = 'black' # edge colour
)
def rotateGrid(self, angle):
for patch in self.patches:
x, y = patch.xy
xNew = x * math.cos(angle) - y * math.sin(angle)
yNew = x * math.sin(angle) + y * math.cos(angle)
patch.xy = (xNew, yNew)
patch.orientation = patch.orientation + angle
但是,当尝试使用Rectangle
修补程序执行此操作时,除了以下函数之外,这些修补程序是同一个类:
def _createRectangle(self, x, y, width, height):
return matplotlib.patches.Rectangle(
(x, y),
width,
height,
fc=(0.1, 0.1, 0.1, 0.1),
ec='black',
animated=True
)
def rotateGrid(self, angle):
for patch in self.patches:
x, y = patch.xy
xNew = x * math.cos(angle) - y * math.sin(angle)
yNew = x * math.sin(angle) + y * math.cos(angle)
patch.xy = (xNew, yNew)
patch.angle = patch.angle + angle
矩形不随栅格旋转
(为了清楚起见:我希望矩形也能旋转45度)
我已经尝试用替换旋转
patch.set_transform(patch.get_transform() + matplotlib.transforms.Affine2D().rotate(angle))
但是通过移动和扩大补丁,这有一些非常奇怪的行为
有人知道如何使矩形旋转吗
在对matplotlib源代码进行了一些研究之后,我发现了问题所在。如果其他人遇到相同或类似的问题,请阅读下面的解决方案,看看它是否对您有帮助
在我文章的最后一部分,我已经提到了
Rectangle.set_transform()
函数的可能用法。问题在于此setter函数的后续调用因为我想修改现有的转换,所以我使用了getter
Rectangle.get_transform()
,并在其中添加了另一个转换。 出于某种原因,Rectangle
的转换的getter(但可能是所有Patches
)不返回设置值。即:打印
False
在本例中使用的正确getter是
rect.get_data_transform()
,之后可以添加后续转换相关问题 更多 >
编程相关推荐