def anim_to_html(anim, fps=None, embed_frames=True, default_mode='loop'): """Generate HTML representation of the animation""" if fps is None and hasattr(anim, '_interval'): # Convert interval in ms to frames per second fps = 1000. / anim._interval plt.close(anim._fig) if hasattr(anim, "_html_representation"): return anim._html_representation else: # tempfile can't be used here: we need a filename, and this # fails on windows. Instead, we use a custom filename generator #with tempfile.NamedTemporaryFile(suffix='.html') as f: with _NameOnlyTemporaryFile(suffix='.html') as f: anim.save(f.name, writer=HTMLWriter(fps=fps, embed_frames=embed_frames, default_mode=default_mode)) html = open(f.name).read() anim._html_representation = html return html
#global im1 #im1.remove() global im2, cbar im2.remove() cbar.remove() global im3 im3.lines.remove() axs.patches = [] global im4 im4.remove() global im5 im5.remove() #def viewInv(msh,iteration): #, linewidth=lw.T #%% #interact(viewInv,msh = mesh2d, iteration = IntSlider(min=0, max=len(txii)-1 ,step=1, value=0)) # set embed_frames=True to embed base64-encoded frames directly in the HTML anim = animation.FuncAnimation(fig, animate, frames=survey2D.nSrc, interval=500) # anim.save(home_dir + '\\animation.html', writer=HTMLWriter(embed_frames=True, fps=1))
mrk_props = dict(boxstyle="square,pad=0.3",fc="w", ec="k", lw=2) ax2.text(0.01, 0.9, 'Line ID#', transform=fig.transFigure, ha="left", va="center", size=8, bbox=mrk_props) mrk_props = dict(boxstyle="square,pad=0.3",fc="b", ec="k", lw=2) for jj in range(len(uniqueID)): ax2.text(0.125, (float(jj)+1.)/(len(uniqueID)+2), ".", transform=fig.transFigure, ha="right", va="center", size=8, bbox=mrk_props) mrk_props = dict(boxstyle="square,pad=0.3",fc="r", ec="k", lw=2) ax2.text(0.125, (float(ii)+1.)/(len(uniqueID)+2), ".", transform=fig.transFigure, ha="right", va="center", size=8, bbox=mrk_props) def removeFrame(): global ax1, ax2, fig fig.delaxes(ax1) fig.delaxes(ax2) #fig.delaxes(ax3) plt.draw() anim = animation.FuncAnimation(fig, animate, repeat = False, frames=len(uniqueID), interval=1000) anim.save(home_dir + '\\animation.html', writer=HTMLWriter(embed_frames=True,fps=1))
pt.set_data([], []) pt.set_3d_properties([]) return lines + pts # animation function. This will be called sequentially with the frame number def animate(i): # we'll step two time-steps per frame. This leads to nice results. i = (2 * i) % x_t.shape[1] for line, pt, xi in zip(lines, pts, x_t): x, y, z = xi[:i + 1].T line.set_data(x, y) line.set_3d_properties(z) pt.set_data(x[-1:], y[-1:]) pt.set_3d_properties(z[-1:]) ax.view_init(30, 0.3 * i) fig.canvas.draw() return lines + pts # instantiate the animator. anim = animation.FuncAnimation(fig, animate, init_func=init, frames=200, interval=30, blit=True) # set embed_frames=False so that frames will be stored individually anim.save('lorenz_animation.html', writer=HTMLWriter(embed_frames=False))
# indx = np.isnan(rho) == False # np.savetxt(fid, np.c_[Pmid[indx,:],rho[indx]], fmt='%e',delimiter=' ',newline='\n') # fid.close() def removeFrame(): global ax1, fig fig.delaxes(ax1) plt.draw() anim = animation.FuncAnimation(fig, animate, frames=len(endl) , interval=1000, repeat = False) #/home/dominiquef/3796_AGIC_Research/DCIP3D/MtISa anim.save('Data_slice.html', writer=HTMLWriter(embed_frames=True,fps=1)) if dType == 'TDEM': os.chdir(work_dir + inp_dir[dType]) AllData = np.loadtxt('Airborne_TDEM.dat', dtype = float, skiprows = 1) xy = AllData[:,:2] data = AllData[:,2:] times = np.loadtxt('times.txt', dtype = float) # TDEMData = [] # for file in glob.glob("*FWR*") :
import numpy as np from matplotlib import pyplot as plt from matplotlib import animation from JSAnimation import HTMLWriter fig = plt.figure(figsize=(4, 3)) ax = plt.axes(xlim=(0, 10), ylim=(-2, 2)) line, = ax.plot([], [], lw=2) def init(): line.set_data([], []) return line, def animate(i): x = np.linspace(0, 10, 1000) y = np.cos(i * 0.02 * np.pi) * np.sin(x - i * 0.02 * np.pi) line.set_data(x, y) return line, anim = animation.FuncAnimation(fig, animate, init_func=init, frames=100, interval=20, blit=True) # set embed_frames=True to embed base64-encoded frames directly in the HTML anim.save('animation.html', writer=HTMLWriter(embed_frames=True))
def plot(rho1=None, rho2=None, rho3=None, t=None, x=None, title='Spin Transport', interval=100, filename=None): if rho1 is None: raise ValueError('rho1 not defined') if rho2 is None: raise ValueError('rho2 not defined') if rho3 is None: raise ValueError('rho3 not defined') if t is None: raise ValueError('t not defined') if x is None: raise ValueError('x not defined') fig1 = plt.figure() lines = [ plt.plot([], [], 'r-', label=r'$\rho_1$'), plt.plot([], [], 'b-', label=r'$\rho_2$'), plt.plot([], [], 'g-', label=r'$\rho_3$') ] plt.legend() plt.xlim(0, 1) plt.ylim(np.min(np.hstack([rho1, rho2, rho3])), np.max(np.hstack([rho1, rho2, rho3]))) plt.xlabel('$x$') plt.title(title) time_label = plt.text(0.95, 0.05, 't=0 s', horizontalalignment='right', verticalalignment='baseline', transform=fig1.axes[0].transAxes) line_ani = animation.FuncAnimation(fig1, update_plot, t.shape[0], fargs=(lines, time_label, rho1, rho2, rho3, t, x), interval=interval) if filename is not None: extension = filename.split('.')[-1] if extension == 'mp4': Writer = animation.writers['ffmpeg'] writer = Writer(fps=15, metadata={}, bitrate=1800) elif extension == 'gif': Writer = animation.writers['imagemagick'] writer = Writer(fps=15) elif extension == 'html': from JSAnimation import HTMLWriter writer = HTMLWriter() else: raise ValueError('"{}" is not a known file extension'.format( filename.split('.')[-1])) line_ani.save(filename, writer=writer) else: plt.show()
mrk_props = dict(boxstyle="square,pad=0.3",fc="b", ec="k", lw=2) for jj in range(len(uniqueID)): ax2.text(0.1, (float(jj)+1.)/(len(uniqueID)+2), ".", transform=fig.transFigure, ha="right", va="center", size=8, bbox=mrk_props) mrk_props = dict(boxstyle="square,pad=0.3",fc="r", ec="k", lw=2) ax2.text(0.1, (float(ii)+1.)/(len(uniqueID)+2), ".", transform=fig.transFigure, ha="right", va="center", size=8, bbox=mrk_props) def removeFrame(): global ax1, ax2,ax3,ax4, ax5, ax6, fig fig.delaxes(ax1) fig.delaxes(ax2) fig.delaxes(ax3) fig.delaxes(ax4) fig.delaxes(ax5) fig.delaxes(ax6) plt.draw() anim = animation.FuncAnimation(fig, animate, frames=len(uniqueID) , interval=1000, repeat = False) # anim.save(home_dir + '\\Invmodels.html', writer=HTMLWriter(embed_frames=True,fps=1))
def plot(rho1=None, rho2=None, rho3=None, t=None, x=None, title='Spin Transport', interval=100, filename=None, frames=[0, -1], time_p=3, subplots=False): if rho1 is None: raise ValueError('rho1 not defined') if rho2 is None: raise ValueError('rho2 not defined') if rho3 is None: raise ValueError('rho3 not defined') if t is None: raise ValueError('t not defined') if x is None: raise ValueError('x not defined') rho1 = rho1[frames[0]:frames[1], :] rho2 = rho2[frames[0]:frames[1], :] rho3 = rho3[frames[0]:frames[1], :] t = t[frames[0]:frames[1]] fig1 = plt.figure() axes = [plt] * 3 if subplots: axes = [ plt.subplot(3, 1, 1), plt.subplot(3, 1, 2), plt.subplot(3, 1, 3) ] lines = [ axes[0].plot([], [], 'r-', label=r'$\rho_1$'), axes[1].plot([], [], 'b-', label=r'$\rho_2$'), axes[2].plot([], [], 'g-', label=r'$\rho_3$') ] for axis in axes: axis.legend() xlim = [np.min(x), np.max(x)] if subplots: axes[0].set_title(title) for (axis, flow) in zip(axes, [rho1, rho2, rho3]): axis.set_xlim(*xlim) ylim = [np.min(flow), np.max(flow)] if ylim[0] - ylim[1] == 0: ylim = [ylim[0] - 1e-9, ylim[1] + 1e-9] axis.set_ylim(*ylim) axis.set_xlabel('$x$') else: plt.title(title) plt.xlim(*xlim) plt.ylim(np.min(np.hstack([rho1, rho2, rho3])), np.max(np.hstack([rho1, rho2, rho3]))) plt.xlabel('$x$') text = [0.95, 0.05, 't=0 s'] if subplots: text[1] = -2.35 time_label = axes[2].text(*text, horizontalalignment='right', verticalalignment='baseline', transform=fig1.axes[0].transAxes) line_ani = animation.FuncAnimation(fig1, update_plot, t.shape[0], fargs=(lines, time_label, rho1, rho2, rho3, t, x, time_p), interval=interval) if filename is not None: extension = filename.split('.')[-1] if extension == 'mp4': Writer = animation.writers['ffmpeg'] writer = Writer(fps=15, metadata={}, bitrate=1800) elif extension == 'gif': Writer = animation.writers['imagemagick'] writer = Writer(fps=15) elif extension == 'html': from JSAnimation import HTMLWriter writer = HTMLWriter() else: raise ValueError('"{}" is not a known file extension'.format( filename.split('.')[-1])) line_ani.save(filename, writer=writer) else: plt.show()