动画Delaunay三角剖分-Python

如何解决动画Delaunay三角剖分-Python

是否可以使用Matplotlib对delaunay三角剖分进行动画处理?下图绘制了按ItemTime分组的顶点。我希望对此进行动画处理,而不是绘制每次迭代。

我可能也有一些时间点,这些时间点包含的点不足以充分描绘出三角剖分。对于这些时间点,我只是希望度过这段时间并转到下一个时间点。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import delaunay
import matplotlib.animation as animation
import matplotlib.gridspec as gridspec

# data frame containing time points without adequate points (3)
#df = pd.DataFrame({
#    'Time' : [1,1,2,3,3],#    'Item' : ['A','B','A','B'],#    'X' : [5,5,6,4,2],#    'Y' : [5,7,6],#        })

fig = plt.figure(figsize = (8,10))

grid = gridspec.GridSpec(1,2)
gridsize = (1,2)

ax = plt.subplot2grid(gridsize,(0,0))
ax2 = plt.subplot2grid(gridsize,1))

A_coord = df.loc[df['Item'] == 'A']
B_coord = df.loc[df['Item'] == 'B']

def make_points(x):
    return np.array(list(zip(x['X'],x['Y'])))

A_points = A_coord.groupby(['Time']).apply(make_points)
B_points = B_coord.groupby(['Time']).apply(make_points)

for p in A_points:
    tri = delaunay(p)
    a_del = ax.triplot(*p.T,tri.simplices,color = 'orange')

for p in B_points:
    tri = delaunay(p)
    b_del = ax.triplot(*p.T,color = 'purple')

#def animate(i) :

    #a_del.set_data#()
    #b_del.set_data#()    

#ani = animation.FuncAnimation(fig,animate,blit = False)

编辑2:

我希望保持图形的稳定,因为我在上面绘制其他对象时。因此,我只想动画化三角剖分中的变化。

df = pd.DataFrame({
    'Time' : [1,'Item' : ['A','X' : [5,5],'Y' : [5,4],})


A_coord = df.loc[df['Item'] == 'A']
B_coord = df.loc[df['Item'] == 'B']

def make_points(x):
    return np.array(list(zip(x['X'],x['Y'])))

A_points = A_coord.groupby(['Time']).apply(make_points)
B_points = B_coord.groupby(['Time']).apply(make_points)

A_points = A_points.values
B_points = B_points.values

fig = plt.figure(figsize = (8,10))

grid = gridspec.GridSpec(2,2)
gridsize = (2,0),colspan = 2)
ax.set_xlim(0,20)
ax.set_ylim(0,20)

ax2 = plt.subplot2grid(gridsize,(1,0))
ax3 = plt.subplot2grid(gridsize,1))

fig,ax = plt.subplots(nrows=1,ncols=2,figsize=(12,8))

def one_frame(i):

    ax[0].clear();ax[1].clear()

    try:
        a_points = np.unique(A_points[i],axis=0)
        tri_a = delaunay(a_points)
        ax[0].triplot(*a_points.T,tri_a.simplices,color = 'orange')
    except Exception:
        pass

    try:
        b_points = np.unique(B_points[i],axis=0)
        tri_b = delaunay(b_points)
        ax[1].triplot(*b_points.T,tri_b.simplices,color = 'purple')
    except Exception:
        pass


ani = animation.FuncAnimation(fig,one_frame,blit = False)

enter image description here

解决方法

可能是队友,尝试使用此代码

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import Delaunay
import matplotlib.animation as animation

# data frame containing time points without adequate points (3)
df = pd.DataFrame({
   'Time' : [1,1,2,3,3],'Item' : ['A','B','A','B'],'X' : [5,5,6,4,2],'Y' : [5,7,6],})
A_coord = df.loc[df['Item'] == 'A']
B_coord = df.loc[df['Item'] == 'B']

def make_points(x):
    return np.array(list(zip(x['X'],x['Y'])))

A_points = A_coord.groupby(['Time']).apply(make_points)
B_points = B_coord.groupby(['Time']).apply(make_points)

A_points = A_points.values
B_points = B_points.values

fig,ax = plt.subplots(nrows=1,ncols=2,figsize=(12,8))

def one_frame(i):
    
    ax[0].clear();ax[1].clear()
    
    try:
        a_points = np.unique(A_points[i],axis=0)
        tri_a = Delaunay(a_points)
        ax[0].triplot(*a_points.T,tri_a.simplices,color = 'orange')
    except Exception as e:
        print("frame %i,point a can't print because of \n%s" % (i,e))
    
    try:
        b_points = np.unique(B_points[i],axis=0)
        tri_b = Delaunay(b_points)
        ax[1].triplot(*b_points.T,tri_b.simplices,color = 'purple')
    except Exception as e:
        print("frame %i,point b can't print because of \n%s" % (i,e))

ani = animation.FuncAnimation(fig,one_frame,range(3),blit = False)
ani.save('test.gif',writer='pillow',fps=1)

输出为

output


更新

可以保留figax,其想法是在每帧的开头删除最后一帧的三角形(Line2D对象)

for item in triangles_a:
    try:
        item.remove()
    except Exception as e:
        continue 
for item in triangles_b:
    try:
        item.remove()
    except Exception as e:
        continue

删除三角形不会影响figax的其他部分。 例如,在下面的示例中,两个圆在动画过程中不会受到影响。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import Delaunay
import matplotlib.animation as animation

# data frame containing time points without adequate points (3)
df = pd.DataFrame({
   'Time' : [1,x['Y'])))

A_points = A_coord.groupby(['Time']).apply(make_points)
B_points = B_coord.groupby(['Time']).apply(make_points)

A_points = A_points.values
B_points = B_points.values

fig = plt.figure(figsize = (8,10))
grid = gridspec.GridSpec(2,2)
gridsize = (2,2)

ax0 = plt.subplot2grid(gridsize,(0,0),colspan = 2)
ax1 = plt.subplot2grid(gridsize,(1,colspan = 1)
ax2 = plt.subplot2grid(gridsize,1),colspan = 1)

ax1.set_xlim(0,8);ax1.set_ylim(0,8)
ax2.set_xlim(0,8);ax2.set_ylim(0,8)
    
# things that won't be affected 
circle_0 = plt.Circle((4,4),color='violet',fill=False)
ax1.add_artist(circle_0)

circle_1 = plt.Circle((5,color='deepskyblue',fill=False)
ax2.add_artist(circle_1)
    
triangles_a,triangles_b = [],[]
def one_frame(i):
    
    global triangles_a,triangles_b
    for item in triangles_a:
        try:
            item.remove()
        except Exception as e:
            continue 
    for item in triangles_b:
        try:
            item.remove()
        except Exception as e:
            continue
    
    try:
        a_points = np.unique(A_points[i],axis=0)
        tri_a = Delaunay(a_points)
        obj_a = ax1.triplot(*a_points.T,color = 'orange')
        triangles_a.extend(obj_a)
    except Exception as e:
        print("frame %i,axis=0)
        tri_b = Delaunay(b_points)
        obj_b = ax2.triplot(*b_points.T,color = 'purple')
        triangles_b.extend(obj_b)
    except Exception as e:
        print("frame %i,fps=1)

输出

output

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?