def output(self, anim, plt, dataset, output): """ Generic output functions """ logger.info("Writing output...") filename = "covid_{}.{}".format(dataset.lower(), output) if output == "mp4": writer = FFMpegFileWriter(fps=10, bitrate=1800) anim.save(filename, writer=writer) elif output == "gif": writer = ImageMagickFileWriter() anim.save(filename, writer=writer) else: plt.show()
def test_gif(): """ GIF动态图:matplotlib只能对静态图进行绘制显示;动态图是由一帧一帧的画面组合的,由ImageMagick完成 动图绘制路线:初始化图像-> FuncAnimation() -> 不断改变原始曲线值 """ from matplotlib.animation import FuncAnimation from IPython.display import Image from matplotlib.animation import ImageMagickFileWriter writer = ImageMagickFileWriter() fig, ax = plt.subplots() xdata, ydata = [], [] ln, = ax.plot([], [], 'r-', animated=False) # 生成数据(用于传入update函数) def data_gen(): pass # 初始化图像 def init(): ax.set_xlim(0, 2 * np.pi) # 设置x轴范围 ax.set_ylim(-1.1, 1.1) return ln, # 将更新后的数据添加到图像中 def update(data): xdata.append(data) ydata.append(np.sin(data)) ln.set_data(xdata, ydata) # 重新设置曲线的值 return ln, # 核心方法入口 # 参数说明: ani = FuncAnimation( fig, # 画布 update, # 我们每个时刻要更新图形对象的函数 frames=np.linspace(0, 2 * np.pi, 50), # 相当于时刻t,要模拟多少帧图画,不同时刻的t相当于animat的参数 interval=50, # 刷新频率,毫秒 init_func=init, # 初始化函数,其返回值就是每次都要更新的对象 blit=True) # blit是一个非常重要的关键字,它告诉动画只重绘修改的部分,结合上面保存的时间,true会使动画显示得会非常非常快 # 需要安装ImageMagick # ani.save('ming.gif', writer='imagemagick') plt.show()
def init_writer(map_size): metadata = dict(title='Natural selection', artist='Matplotlib', comment='') writer = ImageMagickFileWriter(fps=7, metadata=metadata) fig = plt.figure(figsize=(8, 8)) ax = fig.gca() ax.set_xticks(np.arange(0, map_size[0] + 1, 1)) ax.set_yticks(np.arange(0, map_size[1] + 1, 1)) plt.grid() plt.xlim(0, map_size[0]) plt.ylim(0, map_size[1]) graph_c, = plt.plot([], [], color='firebrick', marker="o", linestyle="", markersize=20) graph_h, = plt.plot([], [], color='dodgerblue', marker="o", linestyle="", markersize=20) graph_p, = plt.plot([], [], color='green', marker="D", linestyle="", markersize=10) #a.set_color('red') #a.set_marker #a.set_label return writer, fig, graph_h, graph_p, graph_c
right = 0.98 # the right side hspace = 0.20 # height reserved for white space wspace = 0.05 # width reserved for blank space plt.subplots_adjust(left=left, bottom=bottom, right=right, top=top, wspace=wspace, hspace=hspace) tit = plt.title('1850') #showdate = ax.text(0.5, 0.95, '1850', fontweight = 'bold', color = cset[0], bbox=dict(facecolor='lightsteelblue', edgecolor='black', boxstyle='round,pad=1')) save = True if save: metadata = dict(title='Temperature anomaly (SPHINX lcb0 experiment)', artist='Federico Fabiano') writer = ImageMagickFileWriter( fps=10, metadata=metadata) #, frame_size = (1200, 900)) with writer.saving(fig, cart + "Temp_anomaly_animation_flat.gif", 150): for i, (year, col) in enumerate(zip(anni, cset)): print(year) animate(i) writer.grab_frame() else: line_ani = animation.FuncAnimation(fig, animate, len(anni), interval=100, blit=False)
def animate(self, outputType="screen", color="random", speed=10, outDir="out", type="line"): if not os.path.exists(outDir): os.mkdir(outDir) fname = os.path.join( outDir, "knightPath-{}-{}".format(self.kn.shape[0], self.kn.shape[1])) knightAnimation = FuncAnimation(self.fig, self._genLine, fargs=(speed, color, type), repeat=False, frames=range( -speed, len(self.kn.history), speed, ), blit=False, interval=10, cache_frame_data=False) if outputType == "screen": plt.show() elif outputType == "avi": knightAnimation.save( fname + ".avi", writer=FFMpegFileWriter(fps=1, bitrate=100000, extra_args=['-vcodec', 'libx264']), ) print("video file written to", fname + ".avi") elif outputType == "mp4": knightAnimation.save( fname + ".mp4", writer=FFMpegFileWriter(fps=1, bitrate=100000, extra_args=['-vcodec', 'libx264']), ) print("MP4 video file written to", fname + ".mp4") elif outputType == "gif": knightPathAnim = FuncAnimation(self.fig, self._genAllLines, repeat=False, frames=range(1), blit=False, interval=10, cache_frame_data=False) knightPathAnim.save(fname + '.gif', writer=ImageMagickFileWriter(fps=1)) print("Image written to", fname + ".gif") elif outputType == "animgif": knightAnimation.save(fname + '.anim.gif', writer=ImageMagickFileWriter(fps=1)) print("Animated gif written to", fname + ".anim.gif") elif outputType == "html": open(fname + ".html", "w").write( self._genHtmlFrame(knightAnimation.to_html5_video(50.0))) print("HTML file written to", fname + ".html") else: print("Unknown outputType '" + outputType + "'") return
ax.set_zlim(0, 1) ax.set_xlabel('Nodes Layer 1') ax.set_ylabel('Nodes Layer 2') ax.set_zlabel('Mean CV Score') plt.savefig(str(i) + ".png") plt.show() ############################################################################### dir_name = os.path.abspath(os.path.dirname(__file__)) data_file = 'processed_data.csv' file_path = os.path.join(dir_name, data_file) data = pandas.read_csv(file_path) encoder = preprocessing.LabelEncoder() encoder.fit(data.iloc[:, -1]) data.iloc[:, -1] = encoder.transform(data.iloc[:, -1]) #Prep the features and labels features = np.array(data.iloc[:, 1:78]) labels = np.array(data.iloc[:, -1]) min_max_scaler = preprocessing.MinMaxScaler() features = min_max_scaler.fit_transform(features) ############################################################################### anim = FuncAnimation(fig, update, frames=range(15), repeat=False) if len(sys.argv) > 1 and sys.argv[1] == 'save': anim.save('surf.gif', dpi=80, writer=ImageMagickFileWriter(fps=1)) else: plt.show()
# _____________ # _____________ r = RandomApproachAnimation(shubert, Settings, 10**5, 10**3) it = r.__iter__() def animate(i): try: return it.__next__() except: return # ___________ # SHOWING ANIMATION # ___________ if (__name__ != '__main__'): ani = FuncAnimation(r.fig, animate, repeat=False, interval=2) plt.show() # ___________ # SAVING TO GIF # ___________ else: ani = FuncAnimation(r.fig, animate, repeat=False, interval=10, frames=5) ani.save('line.gif', writer=ImageMagickFileWriter())
def generate_animation(file1, file2): df, file_x, file_y = animate_data(file1, file2) years = df['Year'].unique().tolist() fig, ax = plt.subplots(figsize=(8, 8)) ax.set_xlim(df[file_x].min() - .3, df[file_x].max() + .3) ax.set_ylim(df[file_y].min() - 2, df[file_y].max() + 2) # set the regions' colors colors = { 'Latin America & Caribbean': '#2CA02C', 'South Asia': '#8C564B', 'Sub-Saharan Africa': '#E377C2', 'Europe & Central Asia': '#FF7F0E', 'Middle East & North Africa': '#D62728', 'East Asia & Pacific': '#1F77B4', 'North America': '#9467BD' } # create one scatterplot per region # I need to do like this to have all the regions # showing up in the legend scats = [] groups = df.groupby('Region') for name, grp in groups: scat = ax.scatter([], [], marker='o', color=colors[name], label=name, edgecolor='silver', alpha=.6) scats.append(scat) # add the year in the middle of the scatter plot # for now, the text is empty (''). Il will be filled # in each frame year_label = ax.text(4.5, 50, '', va='baseline', ha='right', alpha=.3, size=12, fontdict={'weight': 'bold'}) # decorate the visualization ax.spines['bottom'].set_color('silver') ax.spines['top'].set_color('silver') ax.spines['right'].set_color('silver') ax.spines['left'].set_color('silver') ax.tick_params(labelcolor='silver', color='silver') ax.set_xlabel(file_x, color='silver') ax.set_ylabel(file_y, color='silver') ax.legend(loc=1, fontsize=7) # set the initial state def init(): for scat in scats: scat.set_offsets([]) return scats, # function that will update the figure with new data def update(year): # I need to update all scatterplots one by one # and return a list of updated plots for scat, (name, data) in zip(scats, groups): # get the data for the current year sample = data[data['Year'] == year] # set the x and y values scat.set_offsets(sample[[file_x, file_y]]) # update the size of the markers with the population # of the current year scat.set_sizes(np.sqrt(sample['Population'] / 10000) * 5) year_label.set_text(year) return scats, # generate the animation ani = animation.FuncAnimation(fig, update, init_func=init, frames=years, interval=50, repeat=False) writer = ImageMagickFileWriter() ani.save('predicted_images/analysis.gif', writer=writer) #animate_data('CO2.csv','gdp.csv') # plt.show() plt.close()
def makeMovie(data, ind): m = int(data[-1, 0]) start = np.searchsorted(data[:, 0], ind) if ind == m: end = data.shape[0] - 1 else: end = np.searchsorted(data[:, 0], ind + 1) - 1 # if data[start,-1]==1: return data = data[start:end + 1] # x_e=data[:,3]-data[0,3] x_e = data[:, 3] y_e = data[:, 2] # x_f=data[:,7]-data[0,3] x_f = data[:, 7] y_f = data[:, 6] # x_ft=data[:,11]-data[0,3] x_ft = data[:, 11] y_ft = data[:, 10] # x_rt=data[:,15]-data[0,3] x_rt = data[:, 15] y_rt = data[:, 14] x_rt1 = data[:, 20] y_rt1 = data[:, 19] xMin = min(x_e) xMax = max(x_e) # x_f_min=min(x_f[x_f!=0]) # if x_f[x_f!=0].shape[0]!=0: xMin=min(xMin, min(x_f[x_f!=0])) # if x_ft[x_ft!=0].shape[0]!=0: xMin=min(xMin, min(x_ft[x_ft!=0])) # if x_rt[x_rt!=0].shape[0]!=0: xMin=min(xMin, min(x_rt[x_rt!=0])) xMin = int( min(min(min(min(x_e), min(x_f)), min(min(x_ft), min(x_rt))), min(x_rt1))) - 5 xMax = int( max(max(max(max(x_e), max(x_f)), max(max(x_ft), max(x_rt))), max(x_rt1))) + 5 # x_e-=xMin # x_f-=xMin # x_ft-=xMin # x_rt-=xMin # xMax=int(xMax-xMin+5) # xMin=-5 # laneLowerBound=(int(max(y_e)/widthLane)+1)*widthLane laneLowerBound = widthLane # laneUpperBound=int(min(y_e)/widthLane)*widthLane laneUpperBound = -widthLane # if laneLowerBound>=widthLane*7: # laneUpperBound=widthLane*5 # laneLowerBound=widthLane*7 # for ramp laneDivision = laneUpperBound + widthLane print('ub', laneUpperBound, 'lb', laneLowerBound, 'ld', laneDivision) fig = plt.figure() plt.axis('scaled') ax = fig.add_subplot(111) ax.set_xlim(xMin, xMax) ax.set_ylim(laneUpperBound - 2, laneLowerBound + 2) plt.gca().invert_yaxis() # (x,y) bottom and left corner coordinates patch_e = patches.Rectangle( (x_e[0] - lengthCar / 2., y_e[0] - widthCar / 2.), lengthCar, widthCar, fc='r') patch_f = patches.Rectangle( (x_f[0] - lengthCar / 2., y_f[0] - widthCar / 2.), lengthCar, widthCar, fc='b') patch_ft = patches.Rectangle( (x_ft[0] - lengthCar / 2., y_ft[0] - widthCar / 2.), lengthCar, widthCar, fc='b') patch_rt = patches.Rectangle( (x_rt[0] - lengthCar / 2., y_rt[0] - widthCar / 2.), lengthCar, widthCar, fc='b') patch_rt1 = patches.Rectangle( (x_rt1[0] - lengthCar / 2., y_rt1[0] - widthCar / 2.), lengthCar, widthCar, fc='b') def init(): ax.add_patch(patch_e) ax.plot(np.arange(xMin, xMax, 1), laneLowerBound * np.ones(xMax - xMin)) ax.plot(np.arange(xMin, xMax, 1), laneUpperBound * np.ones(xMax - xMin)) ax.plot(np.arange(xMin, xMax, 1), laneDivision * np.ones(xMax - xMin), linestyle='--') return patch_e, def animate(i): patch_e.set_xy([x_e[i] - lengthCar / 2., y_e[i] - widthCar / 2.]) if y_f[i] == 0.: # front obstacle does not exist, -100 to remove it out the animation y limit patch_f.set_xy( [x_f[i] - lengthCar / 2., y_f[i] - widthCar / 2. - 100.]) else: patch_f.set_xy( [x_f[i] - lengthCar / 2., y_f[i] - widthCar / 2.]) ax.add_patch(patch_f) if y_ft[i] == 0.: patch_ft.set_xy( [x_ft[i] - lengthCar / 2., y_ft[i] - widthCar / 2. - 100.]) else: patch_ft.set_xy( [x_ft[i] - lengthCar / 2., y_ft[i] - widthCar / 2.]) ax.add_patch(patch_ft) if y_rt[i] == 0.: patch_rt.set_xy( [x_rt[i] - lengthCar / 2., y_rt[i] - widthCar / 2. - 100.]) else: patch_rt.set_xy( [x_rt[i] - lengthCar / 2., y_rt[i] - widthCar / 2.]) ax.add_patch(patch_rt) if y_rt1[i] == 0.: patch_rt1.set_xy([ x_rt1[i] - lengthCar / 2., y_rt1[i] - widthCar / 2. - 100. ]) else: patch_rt1.set_xy( [x_rt1[i] - lengthCar / 2., y_rt1[i] - widthCar / 2.]) ax.add_patch(patch_rt1) return patch_e, patch_f, patch_ft, patch_rt, patch_rt1 anim = animation.FuncAnimation(fig, animate, init_func=init, frames=x_e.shape[0], interval=100, blit=True) writer = ImageMagickFileWriter(fps=15, bitrate=3000) anim.save('lc_id' + str(ind) + '.gif', writer=writer)
def makeMovie(data, ind, dir): start = np.searchsorted(data[:, 0], ind) end = np.searchsorted(data[:, 0], ind + 1) - 1 # if data[start,-1]==1: return data = data[start:end + 1] x_e = data[:, 3] y_e = data[:, 2] x_f = data[:, 7] y_f = data[:, 6] x_ft = data[:, 11] y_ft = data[:, 10] x_rt = data[:, 15] y_rt = data[:, 14] xMin = min(x_e) xMax = max(x_e) xMin = int(min(min(min(x_e), min(x_f)), min(min(x_ft), min(x_rt)))) - 5 xMax = int(max(max(max(x_e), max(x_f)), max(max(x_ft), max(x_rt)))) + 5 laneLowerBound = widthLane laneUpperBound = -widthLane # for ramp laneDivision = laneUpperBound + widthLane fig = plt.figure() plt.axis('scaled') ax = fig.add_subplot(111) ax.set_xlim(xMin, xMax) ax.set_ylim(laneUpperBound - 2, laneLowerBound + 2) plt.gca().invert_yaxis() # (x,y) bottom and left corner coordinates patch_e = patches.Rectangle( (x_e[0] - lengthCar / 2., y_e[0] - widthCar / 2.), lengthCar, widthCar, fc='r') patch_f = patches.Rectangle( (x_f[0] - lengthCar / 2., y_f[0] - widthCar / 2.), lengthCar, widthCar, fc='b') patch_ft = patches.Rectangle( (x_ft[0] - lengthCar / 2., y_ft[0] - widthCar / 2.), lengthCar, widthCar, fc='b') patch_rt = patches.Rectangle( (x_rt[0] - lengthCar / 2., y_rt[0] - widthCar / 2.), lengthCar, widthCar, fc='b') def init(): ax.add_patch(patch_e) ax.plot(np.arange(xMin, xMax, 1), laneLowerBound * np.ones(xMax - xMin)) ax.plot(np.arange(xMin, xMax, 1), laneUpperBound * np.ones(xMax - xMin)) ax.plot(np.arange(xMin, xMax, 1), laneDivision * np.ones(xMax - xMin), linestyle='--') return patch_e, def animate(i): patch_e.set_xy([x_e[i] - lengthCar / 2., y_e[i] - widthCar / 2.]) if y_f[i] == 0.: # front obstacle does not exist, -100 to remove it out the animation y limit patch_f.set_xy( [x_f[i] - lengthCar / 2., y_f[i] - widthCar / 2. - 100.]) else: patch_f.set_xy( [x_f[i] - lengthCar / 2., y_f[i] - widthCar / 2.]) ax.add_patch(patch_f) if y_ft[i] == 0.: patch_ft.set_xy( [x_ft[i] - lengthCar / 2., y_ft[i] - widthCar / 2. - 100.]) else: patch_ft.set_xy( [x_ft[i] - lengthCar / 2., y_ft[i] - widthCar / 2.]) ax.add_patch(patch_ft) if y_rt[i] == 0.: patch_rt.set_xy( [x_rt[i] - lengthCar / 2., y_rt[i] - widthCar / 2. - 100.]) else: patch_rt.set_xy( [x_rt[i] - lengthCar / 2., y_rt[i] - widthCar / 2.]) ax.add_patch(patch_rt) return patch_e, patch_f, patch_ft, patch_rt anim = animation.FuncAnimation(fig, animate, init_func=init, frames=x_e.shape[0], interval=100, blit=True) writer = ImageMagickFileWriter(fps=15, bitrate=3000) anim.save(dir + 'lc_id' + str(ind) + '.gif', writer=writer)