Python matplotlib.pyplot 模块,pause() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.pyplot.pause()

项目:torch_light    作者:ne7ermore    | 项目源码 | 文件源码
def imshow(tensor, imsize=512, title=None):
    image = tensor.clone().cpu()
    image = image.view(*tensor.size())
    image = transforms.ToPILImage()(image)
    plt.imshow(image)
    if title is not None:
        plt.title(title)
    plt.pause(5)
项目:a-nice-mc    作者:ermongroup    | 项目源码 | 文件源码
def visualize(self, zv, path):
        self.ax1.clear()
        self.ax2.clear()
        z, v = zv
        if path:
            np.save(path + '/trajectory.npy', z)

        z = np.reshape(z, [-1, 2])
        self.ax1.hist2d(z[:, 0], z[:, 1], bins=400)
        self.ax1.set(xlim=self.xlim(), ylim=self.ylim())

        v = np.reshape(v, [-1, 2])
        self.ax2.hist2d(v[:, 0], v[:, 1], bins=400)
        self.ax2.set(xlim=self.xlim(), ylim=self.ylim())

        if self.display:
            import matplotlib.pyplot as plt
            plt.show()
            plt.pause(0.1)
        elif path:
            self.fig.savefig(path + '/visualize.png')
项目:TickTickBacktest    作者:gavincyi    | 项目源码 | 文件源码
def plot_graph(cls, date_time, price, graph=None):
        """
        Plot the graph
        :param graph: MatPlotLibGraph
        :param date_time: Date time
        :param price: Price
        """
        date_time = (date_time - datetime.datetime(1970, 1, 1)).total_seconds()
        if graph is None:
            graph = plt.scatter([date_time], [price])
            plt.xlim([date_time, date_time + 60 * 60 * 24])
            # plt.ylim([float(price) * 0.95, float(price) * 1.05])
            plt.draw()
            plt.pause(0.1)
        else:
            array = graph.get_offsets()
            array = np.append(array, [date_time, price])
            graph.set_offsets(array)
            # plt.xlim([array[::2].min() - 0.5, array[::2].max() + 0.5])
            plt.ylim([float(array[1::2].min()) - 0.5, float(array[1::2].max()) + 0.5])
            plt.draw()
            plt.pause(0.1)

        return graph
项目:pyoptflow    作者:scivision    | 项目源码 | 文件源码
def compareGraphs(u,v,Inew,scale=3, quivstep=5):
    """
    makes quiver
    """
    if figure is None:
        return

    ax = figure().gca()
    ax.imshow(Inew,cmap = 'gray', origin='lower')
    # plt.scatter(POI[:,0,1],POI[:,0,0])
    for i in range(0,len(u), quivstep):
        for j in range(0,len(v), quivstep):
            ax.arrow(j,i, v[i,j]*scale, u[i,j]*scale, color='red',
                     head_width=0.5, head_length=1)

    # plt.arrow(POI[:,0,0],POI[:,0,1],0,-5)

    draw(); pause(0.01)
项目:probability_GAN    作者:MaureenZOU    | 项目源码 | 文件源码
def view(realDtb, fakeDtb, discriminator, outDir):
        plt.clf()

        axes = plt.gca()
        axes.set_xlim([-1,10])
        axes.set_ylim([0,0.6])
        axes.set_autoscale_on(False)

        plt.axhline(y = discriminator)
        plt.plot()

        real_mean = np.mean(realDtb)
        real_std = np.std(realDtb)
        real_pdf = norm.pdf(realDtb, real_mean, real_std)
        plt.plot(realDtb, real_pdf)

        fake_mean = np.mean(fakeDtb)
        fake_std = np.std(fakeDtb)
        fake_pdf = norm.pdf(fakeDtb, fake_mean, fake_std)
        plt.plot(fakeDtb, fake_pdf)

        plt.pause(0.00001)
项目:zhusuan    作者:thu-ml    | 项目源码 | 文件源码
def draw(vmean, vlogstd):
        from scipy import stats
        plt.cla()
        xlimits = [-2, 2]
        ylimits = [-4, 2]

        def log_prob(z):
            z1, z2 = z[:, 0], z[:, 1]
            return stats.norm.logpdf(z2, 0, 1.35) + \
                stats.norm.logpdf(z1, 0, np.exp(z2))

        plot_isocontours(ax, lambda z: np.exp(log_prob(z)), xlimits, ylimits)

        def variational_contour(z):
            return stats.multivariate_normal.pdf(
                z, vmean, np.diag(np.exp(vlogstd)))

        plot_isocontours(ax, variational_contour, xlimits, ylimits)
        plt.draw()
        plt.pause(1.0 / 30.0)
项目:DHP    作者:YuhangSong    | 项目源码 | 文件源码
def log_thread_step(self):
        '''log_scan_path'''
        if self.if_log_scan_path:
            plt.figure(str(self.env_id)+'_scan_path')
            plt.scatter(self.cur_lon, self.cur_lat, c='r')
            plt.scatter(-180, -90)
            plt.scatter(-180, 90)
            plt.scatter(180, -90)
            plt.scatter(180, 90)
            plt.pause(0.00001)

        if self.if_log_cc:
            if self.mode is 'off_line':
                self.agent_result_saver += [copy.deepcopy(fixation2salmap(fixation=[[self.cur_lon,self.cur_lon]],
                                                                          mapwidth=self.heatmap_width,
                                                                          mapheight=self.heatmap_height))]
            elif self.mode is 'on_line':
                print('not implement')
                import sys
                sys.exit(0)
项目:3D_Dense_Transformer_Networks    作者:JohnYC1995    | 项目源码 | 文件源码
def show_data(data,label):
    [d1,d2,d3,d4] = data.shape
    for slices in range(d1):
        for depth in range(d2):
            #gray()
            plt.figure(figsize=(8,7),dpi=98)
            p1 = plt.subplot(211)
            p1.imshow(data[slices,depth,:,:])
            title_data = 'data batch:' + str(slices+1) + 'th' + ' slices: ' + str(depth+1)
            plt.title(title_data)
            p2 = plt.subplot(212)
            p2.imshow(label[slices,depth,:,:])
            title_label =  'label batch:' + str(slices+1) + 'th' + ' slices: ' + str(depth+1)
            plt.title(title_label)
            plt.pause(0.000001)
            plt.close()
项目:pystudio    作者:satorchi    | 项目源码 | 文件源码
def plot_Vavg(self,Vavg,Vbias,offset=None,axes=None):
    Iavg=self.ADU2I(Vavg,offset)

    lbl=str('V$_{bias}$ = %.2fV' % Vbias)
    plt.cla()
    if isinstance(axes,list) or isinstance(axes,np.ndarray): plt.axis(axes)
    plt.xlabel('TES number')
    plt.ylabel('I  /  $\mu$A')
    # plot markers with no lines
    plt.plot(Iavg,marker='D',drawstyle='steps-mid',linestyle='none',color='green',label=lbl)
    # plot bars up to the markers
    tes_axis=np.arange(self.NPIXELS)-0.25
    plt.bar(tes_axis,height=Iavg,color='pink',width=0.5)
    plt.legend()
    plt.pause(0.01)
    return
项目:Deep-Learning-Plugin    作者:flowjo-lakes    | 项目源码 | 文件源码
def on_epoch_end(self, epoch, logs={}):
        monitor.on_epoch_end(self, epoch, logs=logs)
        #clear plot
        self.axFig3.cla()
        #plot MMD target embbeding
        MMDtargetEmbeddingHandle = self.axFig3.scatter(self.MMDtargetEmbedding[:,0], self.MMDtargetEmbedding[:,1],
                                                        alpha=0.25, s=10, cmap='rainbow',
                                                        label="MMD target embedding")

        #plot network output projected on target embedding
        plotPredictions = self.netMMDLayerPredict(self.inputData)
        projection = np.dot(plotPredictions,self.pca.components_[[0,1]].transpose())
        NetOuputHandle = self.axFig3.scatter(projection[:,0],projection[:,1], color='red', alpha=0.25, s=10,
                                              label='Net output projected on target embedding')
        self.axFig3.legend(handles = (MMDtargetEmbeddingHandle, NetOuputHandle))
        plt.draw()
        plt.pause(0.01)
项目:Deep-Learning-Plugin    作者:flowjo-lakes    | 项目源码 | 文件源码
def on_epoch_end(self, epoch, logs={}):
        Callback.on_epoch_end(self, epoch, logs=logs)
        #clear plot
        self.axFig.cla()
        #plot target embbeding
        targetEmbeddingHandle = self.axFig.scatter(self.targetEmbedding[:,0], self.targetEmbedding[:,1],
                                                        alpha=0.25, s=10, c=self.yTarget, cmap="rainbow",
                                                        label="MMD target embedding")

        #plot network output projected on target embedding
        plotPredictions = self.netAnchorLayerPredict(self.xInput)
        #print(plotPredictions)
        projection = np.dot(plotPredictions,self.pca.components_[[0,1]].transpose())
        NetOuputHandle = self.axFig.scatter(projection[:,0],projection[:,1], 
                                            c=self.yInput, cmap="rainbow",
                                            alpha=0.25, s=10,
                                              label='Net output projected on target embedding')
        self.axFig.legend(handles = (targetEmbeddingHandle, NetOuputHandle))
        plt.draw()
        plt.pause(0.01)
项目:tefla    作者:litan    | 项目源码 | 文件源码
def subplots2(ax, epoch_list, train_loss_list, validation_loss_list, validation_accuracy_list, validation_kappa_list,
              epoch, epoch_validation_accuracy, epoch_validation_kappa, epoch_training_loss, epoch_validation_loss):
    ax[0].scatter(epoch, epoch_training_loss, c='r', s=50)
    ax[0].plot(epoch_list, train_loss_list, 'red', label='Training loss')
    ax[0].scatter(epoch, epoch_validation_loss, c='g', s=50)
    ax[0].plot(epoch_list, validation_loss_list, 'green', label='Validation loss')
    ax[0].set_title('Epoch vs loss')
    plt.pause(.001)
    ax[1].scatter(epoch, epoch_validation_accuracy, c='b', s=50)
    ax[1].plot(epoch_list, validation_accuracy_list, 'blue')
    ax[1].set_title('Epoch vs Validation accuracy')
    plt.pause(.001)
    ax[2].scatter(epoch, epoch_validation_kappa, c='purple', s=50)
    ax[2].plot(epoch_list, validation_kappa_list, 'purple')
    ax[2].set_title('Epoch vs Validation Kappa')
    plt.pause(.001)
项目:crazyswarm    作者:USC-ACTLab    | 项目源码 | 文件源码
def update(self, t, crazyflies):
        xs = []
        ys = []
        zs = []
        for cf in crazyflies:
            x, y, z = cf.position()
            xs.append(x)
            ys.append(y)
            zs.append(z)

        if self.plot is None:
            self.plot = self.ax.scatter(xs, ys, zs)
        else:
            self.plot._offsets3d = (xs, ys, zs)

        self.timeAnnotation.set_text("{} s".format(t))
        plt.pause(0.0001)
项目:DeepLearning    作者:Wanwannodao    | 项目源码 | 文件源码
def visualize(generated_images, epoch):
    col, row = 8, 8
    fig, axes = plt.subplots(row, col, sharex=True, sharey=True)
    #images = np.squeeze(generated_images, axis=(-1,))*127.5
    images = generated_images*127.5 + 127.5
    #images = generated_images*255.0
    for i, array in enumerate(images):

        image = Image.fromarray(array.astype(np.uint8))

        ax = axes[int(i/col), int(i%col)]
        ax.axis("off")
        ax.imshow(image)

    plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0, hspace=0.2)
    #plt.pause(.01)    
    #plt.show()
    plt.savefig("image_{}.png".format(epoch))

# ====================
# Data Loader 
# ====================
项目:DeepLearning    作者:Wanwannodao    | 项目源码 | 文件源码
def visualize(generated_images, epoch):
    col, row = 8, 8
    fig, axes = plt.subplots(row, col, sharex=True, sharey=True)
    #images = np.squeeze(generated_images, axis=(-1,))*127.5
    images = generated_images*127.5 + 127.5
    #images = generated_images*255.0
    for i, array in enumerate(images):

        image = Image.fromarray(array.astype(np.uint8))

        ax = axes[int(i/col), int(i%col)]
        ax.axis("off")
        ax.imshow(image)

    plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0, hspace=0.2)
    #plt.pause(.01)    
    #plt.show()
    plt.savefig("image_{}.png".format(epoch))

# ====================
# Data Loader 
# ====================
项目:DeepLearning    作者:Wanwannodao    | 项目源码 | 文件源码
def visualize(generated_images, epoch):
    col, row = 8, 8
    fig, axes = plt.subplots(row, col, sharex=True, sharey=True)
    #images = np.squeeze(generated_images, axis=(-1,))*127.5
    images = generated_images*127.5 + 127.5
    #images = generated_images*255.0
    for i, array in enumerate(images):

        image = Image.fromarray(array.astype(np.uint8))

        ax = axes[int(i/col), int(i%col)]
        ax.axis("off")
        ax.imshow(image)

    plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0, hspace=0.2)
    #plt.pause(.01)    
    #plt.show()
    plt.savefig("image_{}.png".format(epoch))

# ====================
# Data Loader 
# ====================
项目:DeepLearning    作者:Wanwannodao    | 项目源码 | 文件源码
def visualize(generated_images, epoch):
    col, row = 8, 8
    fig, axes = plt.subplots(row, col, sharex=True, sharey=True)
    #images = np.squeeze(generated_images, axis=(-1,))*127.5
    images = generated_images*127.5 + 127.5
    #images = generated_images*255.0
    for i, array in enumerate(images):

        image = Image.fromarray(array.astype(np.uint8))

        ax = axes[int(i/col), int(i%col)]
        ax.axis("off")
        ax.imshow(image)

    plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0, hspace=0.2)
    #plt.pause(.01)    
    #plt.show()
    plt.savefig("image_{}.png".format(epoch))

# ====================
# Data Loader 
# ====================
项目:DeepLearning    作者:Wanwannodao    | 项目源码 | 文件源码
def visualize(generated_images, epoch):
    col, row = 8, 8
    fig, axes = plt.subplots(row, col, sharex=True, sharey=True)
    images = np.squeeze(generated_images, axis=(-1,))*255.5

    for i, array in enumerate(images):
        image = Image.fromarray(array)

        ax = axes[int(i/col), int(i%col)]
        ax.axis("off")
        ax.imshow(image)

    plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0, hspace=0.2)
    #plt.pause(.01)    
    #plt.show()
    plt.savefig("image_{}.png".format(epoch))

# Generator
项目:gym-kidney    作者:camoy    | 项目源码 | 文件源码
def _render(self, mode = "human", close = False):
        if close:
            return

        import matplotlib.pyplot as plt

        if self.tick == 0:
            plt.ion()

        G = self.G
        attrs = nx.get_node_attributes(G, "ndd")
        values = ["red" if attrs[v] else "blue" for v in G.nodes()]

        plt.clf()
        nx.draw(G,
            pos = nx.circular_layout(G),
            node_color = values)
        plt.pause(0.01)

        return []
项目:strategy    作者:kanghua309    | 项目源码 | 文件源码
def _render(self, mode='human', close=False):
        if self.inited == False: return
        if self.render_on == 0:
            # self.fig = plt.figure(figsize=(10, 4))
            self.fig = plt.figure(figsize=(12, 6))
            self.render_on = 1
            plt.ion()

        plt.clf()
        self._plot_trades()
        plt.suptitle("Code: " + self.src.symbol + ' ' + \
                     "Round:" + str(self.reset_count) + "-" + \
                     "Step:" + str(self.src.idx - self.src.orgin_idx) + "  (" + \
                     "from:" + self.src.reset_start_day + " " + \
                     "to:" + self.src.reset_end_day + ")")
        plt.pause(0.001)
        return self.fig
项目:raspberrypi_tempmon    作者:gavinlyonsrepo    | 项目源码 | 文件源码
def graph_live_data(self):
        """draw a live graph of pi GPU """
        tempg = []
        plt.ion()

        #pre-load dummy data
        for i in range(0, 26):
            tempg.append(0)

        while True:
            #GPU
            ostemp = os.popen('vcgencmd measure_temp').readline()
            temp = (ostemp.replace("temp=", "").replace("'C\n", ""))
            tempg.append(temp)
            tempg.pop(0)
            #plot graph pass function temp
            plot_now_func(tempg)
            plt.pause(1)
项目:tfnn    作者:MorvanZhou    | 项目源码 | 文件源码
def monitoring(self, xs, ys):
        if ys.shape[1] > 1:
            raise NotImplementedError('Can only support ys which have single value.')

        feed_dict = self.evaluator.get_feed_dict(xs, ys)
        y_predict = self._network.predictions.eval(feed_dict, self._network.sess)
        # scatter change data.
        self._scat.set_offsets(np.hstack((ys, y_predict)))
        # scatter change color:
        # self._scat_axes.set_array(...)
        y_real_max, y_real_min = ys.min(), ys.max()
        self._real_line.set_data([y_real_min, y_real_max], [y_real_min, y_real_max])
        offset = 0.1 * (y_real_max - y_real_min)
        self._ax.set_ylim([y_real_min - offset, y_real_max + offset])
        self._ax.set_xlim([y_real_min - offset, y_real_max + offset])
        self._fig.canvas.blit(self._ax.bbox)
        self._fig.canvas.draw()
        self._fig.canvas.flush_events()
        plt.pause(self._sleep)
项目:tfnn    作者:MorvanZhou    | 项目源码 | 文件源码
def monitoring(self, xs, ys):
        if ys.shape[1] > 1 or xs.shape[1] > 1:
            raise NotImplementedError('Can only support ys and xs which have single value.')

        feed_dict = self.evaluator.get_feed_dict(xs, ys)
        y_predict = self._network.predictions.eval(feed_dict, self._network.sess)
        predicted_data = np.hstack((xs, y_predict))
        if not hasattr(self, '_line'):
            sorted_predicted_data = predicted_data[np.argsort(predicted_data[:, 0])]
            self._ax.scatter(xs, ys,
                             c=self.color_train,   # red like
                             s=20, alpha=0.9, label=r'$Real\ data$')
            self._line, = self._ax.plot(sorted_predicted_data[:, 0], sorted_predicted_data[:, 1],
                                        c=self.color_test,   # blue like
                                        lw=3, alpha=0.5, label=r'$Prediction$')
            self._ax.set_xlabel(r'$Input$')
            self._ax.set_ylabel(r'$Output$')
            self._ax.legend(loc='best')
        else:
            sorted_predicted_data = predicted_data[np.argsort(predicted_data[:, 0])]
            self._line.set_data(sorted_predicted_data[:, 0], sorted_predicted_data[:, 1])
            self._fig.canvas.blit(self._ax.bbox)
            self._fig.canvas.draw()
            self._fig.canvas.flush_events()
            plt.pause(self._sleep)
项目:rl-rc-car    作者:harvitronix    | 项目源码 | 文件源码
def visualize_polar(state):
    plt.clf()

    sonar = state[0][-1:]
    readings = state[0][:-1]

    r = []
    t = []
    for i, s in enumerate(readings):
        r.append(math.radians(i * 6))
        t.append(s)

    ax = plt.subplot(111, polar=True)

    ax.set_theta_zero_location('W')
    ax.set_theta_direction(-1)
    ax.set_ylim(bottom=0, top=105)

    plt.plot(r, t)
    plt.scatter(math.radians(90), sonar, s=50)
    plt.draw()
    plt.pause(0.1)
项目:nuts-ml    作者:maet3608    | 项目源码 | 文件源码
def __call__(self, data):
        """Plot data"""
        if not self.__should_plot(data):
            return data

        self.cnt = 0  # reset counter
        self.time = time.clock()  # reset timer
        self._add_data(data)

        for i, ax in enumerate(self.axes):
            ax.clear()
            ax.plot(self.xdata[i], self.ydata[i], '-')
            ax.figure.canvas.draw()

        if self.filepath:
            self.figure.savefig(self.filepath, bbox_inches='tight')
        else:
            plt.pause(0.0001)  # Needed to draw
        return data
项目:Neural_Network    作者:Shoeboxam    | 项目源码 | 文件源码
def post_graph(self, error, prediction):
        self.plot_points.append((self.iteration, error))

        # Error plot
        plt.subplot(1, 2, 1)
        plt.cla()
        plt.title('Error')
        plt.plot(*zip(*self.plot_points), marker='.', color=(.9148, .604, .0945))

        # Environment plot
        plt.subplot(1, 2, 2)
        plt.cla()
        plt.title('Environment')
        self.environment.plot(plt, prediction)

        plt.pause(0.00001)
项目:Neural_Network    作者:Shoeboxam    | 项目源码 | 文件源码
def post_graph(self, error, prediction):
        self.plot_points.append((self.iteration, error))

        # Error plot
        plt.subplot(1, 2, 1)
        plt.cla()
        plt.title('Error')
        plt.plot(*zip(*self.plot_points), marker='.', color=(.9148, .604, .0945))

        # Environment plot
        plt.subplot(1, 2, 2)
        plt.cla()
        plt.title('Environment')
        self.environment.plot(plt, prediction)

        plt.pause(0.00001)
项目:Neural_Network    作者:Shoeboxam    | 项目源码 | 文件源码
def post_graph(self, error, prediction):
        self.plot_points.append((self.iteration, error))

        # Error plot
        plt.subplot(1, 2, 1)
        plt.cla()
        plt.title('Error')
        plt.plot(*zip(*self.plot_points), marker='.', color=(.9148, .604, .0945))

        # Environment plot
        plt.subplot(1, 2, 2)
        plt.cla()
        plt.title('Environment')
        self.environment.plot(plt, prediction)

        plt.pause(0.00001)
项目:python-study    作者:t2y    | 项目源码 | 文件源码
def main():
    args = parse_argument()
    log.debug(args)

    numbers = list(range(0, args.max_num + 1))
    notations = filter(lambda n: n.__name__ not in args.excludes, Notations)

    for notation in notations:
        notation().show(numbers)

    plt.title('Big-O Complexity')
    plt.xlabel('Growth of Input')
    plt.ylabel('Complexity')
    plt.legend(loc=2)

    plt.draw()
    plt.pause(1)
    handle_keyboard_interrupt()
项目:a3c    作者:siemanko    | 项目源码 | 文件源码
def main():
    session = tf.Session()

    env = gym.make('Pong-v0')
    last_observation = env.reset()
    preproc_f = preproc_graph(session, env.observation_space.shape)

    fig, ax = plt.subplots(figsize=(6,6))
    plt.ion()

    for _ in range(1000):
        observation, _, _, _ = env.step(env.action_space.sample())
        print("wtf?")
        pp = preproc_f(last_observation, observation)
        print("wtf!")

        ax.imshow(pp[:,:,0])
        plt.pause(0.05)

        print("Let the bodies hit the floor")

        last_observation = observation
项目:tensorflow-mnist-tutorial    作者:jaskru    | 项目源码 | 文件源码
def animate(self, compute_step, iterations, train_data_update_freq=20, test_data_update_freq=100, one_test_at_start=True, more_tests_at_start=False, save_movie=False):

        def animate_step(i):
            if (i == iterations // train_data_update_freq): #last iteration
                compute_step(iterations, True, True)
            else:
                for k in range(train_data_update_freq):
                    n = i * train_data_update_freq + k
                    request_data_update = (n % train_data_update_freq == 0)
                    request_test_data_update = (n % test_data_update_freq == 0) and (n > 0 or one_test_at_start)
                    if more_tests_at_start and n < test_data_update_freq: request_test_data_update = request_data_update
                    compute_step(n, request_test_data_update, request_data_update)
                    # makes the UI a little more responsive
                    plt.pause(0.001)
            if not self.is_paused():
                return self._mpl_update_func()

        self._animation = animation.FuncAnimation(self._mpl_figure, animate_step, int(iterations // train_data_update_freq + 1), init_func=self._mlp_init_func, interval=16, repeat=False, blit=False)

        if save_movie:
            mywriter = animation.FFMpegWriter(fps=24, codec='libx264', extra_args=['-pix_fmt', 'yuv420p', '-profile:v', 'high', '-tune', 'animation', '-crf', '18'])
            self._animation.save("./tensorflowvisu_video.mp4", writer=mywriter)
        else:
            plt.show(block=True)
项目:deep-learning-with-Keras    作者:decordoba    | 项目源码 | 文件源码
def update_epoch_plots(self, rescale_Y=False):
        for i in range(len(self.epoch_lines)):
            self.epoch_subfig[i].set_xlim(0, self.epoch_num)
            for j in range(len(self.epoch_lines[i])):
                self.epoch_lines[i][j].set_data(self.epoch_steps, self.epoch_metrics[i][j])
        if rescale_Y:  # Rescale ylim so plots fit in every subfigure
            for i in range(len(self.epoch_lines)):
                minY = float("inf")
                maxY = float("-inf")
                for j in range(len(self.epoch_lines[i])):
                    maxY = max(maxY, max(self.epoch_metrics[i][j]))
                    minY = min(minY, min(self.epoch_metrics[i][j]))
                maxY = math.ceil(maxY * 10) / 10
                minY = math.floor(minY * 10) / 10
                rangeY = (maxY - minY) * 0.05
                self.epoch_subfig[i].set_ylim(minY - rangeY, maxY + rangeY)
        if SHOW_PLOTS:
            plt.pause(0.001)
        else:
            self.epoch_fig.savefig(self.location + "loss-acc_epoch.png", bbox_inches="tight")
项目:deep-learning-with-Keras    作者:decordoba    | 项目源码 | 文件源码
def plot_images(images, labels=None, label_description="Label", labels2=None,
                label2_description="Label", show_errors_only=False, cmap="Greys"):
    """ Show all images in imgs list, waiting for an ENTER to show the next one """
    plt.ion()  # Allows plots to be non-blocking
    for i, img in enumerate(images):
        if cmap is None:
            plt.imshow(img)
        else:
            plt.imshow(img, cmap=cmap)
        if labels is not None:
            if labels2 is None:
                title = "{} = {}".format(label_description, labels[i])
            else:
                if show_errors_only and labels[i] == labels2[i]:
                    continue
                title = "{} = {} , {} = {}".format(label_description, labels[i],
                                                   label2_description, labels2[i])
            plt.title(title, fontsize="xx-large", fontweight="bold")
        plt.pause(0.001)
        s = input("Press ENTER to see the next image, or Q (q) to continue:  ")
        if len(s) > 0 and s[0].lower() == "q":
            break
    plt.close()  # Hide plotting window
    plt.ioff()  # Make plots blocking again
项目:cartpole-q-learning    作者:YuriyGuts    | 项目源码 | 文件源码
def update_plot(self, episode_index):
        plot_right_edge = episode_index
        plot_left_edge = max(0, plot_right_edge - self.plot_episode_count)

        # Update point plot.
        x = range(plot_left_edge, plot_right_edge)
        y = self.lengths[plot_left_edge:plot_right_edge]
        self.point_plot.set_xdata(x)
        self.point_plot.set_ydata(y)
        self.ax.set_xlim(plot_left_edge, plot_left_edge + self.plot_episode_count)

        # Update rolling mean plot.
        mean_kernel_size = 101
        rolling_mean_data = np.concatenate((np.zeros(mean_kernel_size), self.lengths[plot_left_edge:episode_index]))
        rolling_means = pd.rolling_mean(
            rolling_mean_data,
            window=mean_kernel_size,
            min_periods=0
        )[mean_kernel_size:]
        self.mean_plot.set_xdata(range(plot_left_edge, plot_left_edge + len(rolling_means)))
        self.mean_plot.set_ydata(rolling_means)

        # Repaint the surface.
        plt.draw()
        plt.pause(0.0001)
项目:PyFrac    作者:GeoEnergyLab-EPFL    | 项目源码 | 文件源码
def PrintDomain(Matrix, mesh, Elem = None):
    """
    3D plot of all elements given in the form of a list;
    Arguments:
        Elem(ndarray-int):          list of elements to be plotted
        Matrix(ndarray-float):      values to be plotted, should be equal in size to the first argument(Elem)
        mesh(CartesianMesh object): mesh object
    """
    if Elem == None:
        Elem = np.arange(mesh.NumberOfElts)

    # if len(Matrix.shape)==1:
    #     Matrix = np.reshape(Matrix, (mesh.ny, mesh.nx))

    tmp = np.zeros((mesh.NumberOfElts,))
    tmp[Elem] = Matrix
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    ax.plot_trisurf(mesh.CenterCoor[:, 0], mesh.CenterCoor[:, 1], tmp, cmap=cm.jet, linewidth=0.2)
    plt.show()
    plt.pause(0.01)


# ----------------------------------------------------------------------------------------------------------------------
项目:BatchEffectRemoval    作者:ushaham    | 项目源码 | 文件源码
def on_epoch_end(self, epoch, logs={}):
        monitor.on_epoch_end(self, epoch, logs=logs)
        #clear plot
        self.axFig3.cla()
        #plot MMD target embbeding
        MMDtargetEmbeddingHandle = self.axFig3.scatter(self.MMDtargetEmbedding[:,0], self.MMDtargetEmbedding[:,1],
                                                        alpha=0.25, s=10, cmap='rainbow',
                                                        label="MMD target embedding")

        #plot network output projected on target embedding
        plotPredictions = self.netMMDLayerPredict(self.inputData)
        projection = np.dot(plotPredictions,self.pca.components_[[0,1]].transpose())
        NetOuputHandle = self.axFig3.scatter(projection[:,0],projection[:,1], color='red', alpha=0.25, s=10,
                                              label='Net output projected on target embedding')
        self.axFig3.legend(handles = (MMDtargetEmbeddingHandle, NetOuputHandle))
        plt.draw()
        plt.pause(0.01)
项目:BatchEffectRemoval    作者:ushaham    | 项目源码 | 文件源码
def on_epoch_end(self, epoch, logs={}):
        Callback.on_epoch_end(self, epoch, logs=logs)
        #clear plot
        self.axFig.cla()
        #plot target embbeding
        targetEmbeddingHandle = self.axFig.scatter(self.targetEmbedding[:,0], self.targetEmbedding[:,1],
                                                        alpha=0.25, s=10, c=self.yTarget, cmap="rainbow",
                                                        label="MMD target embedding")

        #plot network output projected on target embedding
        plotPredictions = self.netAnchorLayerPredict(self.xInput)
        #print(plotPredictions)
        projection = np.dot(plotPredictions,self.pca.components_[[0,1]].transpose())
        NetOuputHandle = self.axFig.scatter(projection[:,0],projection[:,1], 
                                            c=self.yInput, cmap="rainbow",
                                            alpha=0.25, s=10,
                                              label='Net output projected on target embedding')
        self.axFig.legend(handles = (targetEmbeddingHandle, NetOuputHandle))
        plt.draw()
        plt.pause(0.01)
项目:Wifi-Signal-Plotter    作者:s7jones    | 项目源码 | 文件源码
def update_plot(fig, ax, times, avg, err, interfaceDict):
    ax.clear()
    ax.set_title('Wifi Signal over Time')
    plt.xlabel('Time [s]')
    if platform.system() == 'Linux':
        plt.ylabel('Signal Level [dBm]')
    elif platform.system() == 'Windows':
        plt.ylabel('Signal Level [%]')
    else:
        raise Exception('reached else of if statement')
    for key, value in interfaceDict.items():
        plt.errorbar(times[:], avg[value, :], yerr=err[value, :], label=key)
    plt.legend()
    print('\n\n')
    plt.pause(0.0001)
    plt.show()
项目:Reinforcement_Learning    作者:jcwleo    | 项目源码 | 文件源码
def plot_data(epoch, epoch_score, average_reward, epoch_Q, average_Q, mainDQN):
    plt.clf()
    epoch_score.append(np.mean(average_reward))
    epoch_Q.append(np.mean(average_Q))

    plt.subplot(211)
    plt.axis([0, epoch, 0, np.max(epoch_Q) * 6 / 5])
    plt.xlabel('Training Epochs')
    plt.ylabel('Average Action Value(Q)')
    plt.plot(epoch_Q)

    plt.subplot(212)
    plt.axis([0, epoch, 0, np.max(epoch_score) * 6 / 5])
    plt.xlabel('Training Epochs')
    plt.ylabel('Average Reward per Episode')
    plt.plot(epoch_score, "r")

    plt.pause(0.05)
    plt.savefig("graph/{} epoch".format(epoch - 1))

    save_path = mainDQN.saver.save(mainDQN.sess, model_path, global_step=(epoch - 1))
    print("Model(epoch :", epoch, ") saved in file: ", save_path, " Now time : ", datetime.datetime.now())


# DQN
项目:Reinforcement_Learning    作者:jcwleo    | 项目源码 | 文件源码
def plot_data(epoch, epoch_score, average_reward, epoch_Q, average_Q, mainDQN):
    plt.clf()
    epoch_score.append(np.mean(average_reward))
    epoch_Q.append(np.mean(average_Q))

    plt.subplot(211)
    plt.axis([0, epoch, 0, np.max(epoch_Q) * 6 / 5])
    plt.xlabel('Training Epochs')
    plt.ylabel('Average Action Value(Q)')
    plt.plot(epoch_Q)

    plt.subplot(212)
    plt.axis([0, epoch, 0, np.max(epoch_score) * 6 / 5])
    plt.xlabel('Training Epochs')
    plt.ylabel('Average Reward per Episode')
    plt.plot(epoch_score, "r")

    plt.pause(0.05)
    plt.savefig("graph/{} epoch".format(epoch - 1))

    save_path = mainDQN.saver.save(mainDQN.sess, model_path, global_step=(epoch - 1))
    print("Model(epoch :", epoch, ") saved in file: ", save_path, " Now time : ", datetime.datetime.now())


# DQN
项目:pyhiro    作者:wanweiwei07    | 项目源码 | 文件源码
def DrawGraph(self, rnd=None):
        u"""
        Draw Graph
        """
        import matplotlib.pyplot as plt
        plt.clf()
        if rnd is not None:
            plt.plot(rnd[0], rnd[1], "^k")
        for node in self.nodeList:
            if node.parent is not None:
                plt.plot([node.x, self.nodeList[node.parent].x], [
                         node.y, self.nodeList[node.parent].y], "-g")

        for (ox, oy, size) in obstacleList:
            plt.plot(ox, oy, "ok", ms=30 * size)

        plt.plot(self.start.x, self.start.y, "xr")
        plt.plot(self.end.x, self.end.y, "xr")
        plt.axis([-2, 15, -2, 15])
        plt.grid(True)
        plt.pause(0.01)
项目:pyhiro    作者:wanweiwei07    | 项目源码 | 文件源码
def drawwspace(planner, obstaclelist, randconfiguration=None, newconfiguration = None, newconfmark = '^r'):
    """
    Draw Graph
    """
    import matplotlib.pyplot as plt
    plt.clf()
    if randconfiguration is not None:
        plt.plot(randconfiguration[0], randconfiguration[1], "^k")
    if newconfiguration is not None:
        plt.plot(newconfiguration[0], newconfiguration[1], newconfmark)
    for node in planner.nodelist:
        if node.parent is not None:
            plt.plot([node.point[0], planner.nodelist[node.parent].point[0]],
                     [node.point[1], planner.nodelist[node.parent].point[1]], '-g')
    for (point, size) in obstaclelist:
        plt.plot([point[0]], [point[1]], "ok", ms=size*20)
    plt.plot(planner.start[0], planner.start[1], "xr")
    plt.plot(planner.end[0], planner.end[1], "xr")
    plt.axis([-2, 15, -2, 15])
    plt.grid(True)
    plt.pause(0.001)
项目:pyhiro    作者:wanweiwei07    | 项目源码 | 文件源码
def drawwspace(planner, obstaclelist, randconfiguration=None, newconfiguration = None, newconfmark = '^r'):
    """
    Draw Graph
    """
    import matplotlib.pyplot as plt
    plt.clf()
    if randconfiguration is not None:
        plt.plot(randconfiguration[0], randconfiguration[1], "^k")
    if newconfiguration is not None:
        plt.plot(newconfiguration[0], newconfiguration[1], newconfmark)
    for node in planner.nodelist:
        if node.parent is not None:
            plt.plot([node.point[0], planner.nodelist[node.parent].point[0]],
                     [node.point[1], planner.nodelist[node.parent].point[1]], '-g')
        if node.radius < float('inf'):
            plt.plot([node.point[0], planner.nodelist[node.parent].point[0]],
                     [node.point[1], planner.nodelist[node.parent].point[1]], '-r')
    for (point, size) in obstaclelist:
        plt.plot([point[0]], [point[1]], "ok", ms=size*20)
    plt.plot(planner.start[0], planner.start[1], "xr")
    plt.plot(planner.end[0], planner.end[1], "xr")
    plt.axis([-2, 15, -2, 15])
    plt.grid(True)
    plt.pause(0.001)
项目:pyhiro    作者:wanweiwei07    | 项目源码 | 文件源码
def drawwspace(planner, obstaclelist, randconfiguration=None, newconfiguration = None, newconfmark = '^r'):
    """
    Draw Graph
    """
    import matplotlib.pyplot as plt
    plt.clf()
    if randconfiguration is not None:
        plt.plot(randconfiguration[0], randconfiguration[1], "^k")
    if newconfiguration is not None:
        plt.plot(newconfiguration[0], newconfiguration[1], newconfmark)
    for node in planner.nodeliststart:
        if node.parent is not None:
            plt.plot([node.point[0], planner.nodeliststart[node.parent].point[0]],
                     [node.point[1], planner.nodeliststart[node.parent].point[1]], '-g')
    for node in planner.nodelistend:
        if node.parent is not None:
            plt.plot([node.point[0], planner.nodelistend[node.parent].point[0]],
                     [node.point[1], planner.nodelistend[node.parent].point[1]], '-b')
    for (point, size) in obstaclelist:
        plt.plot([point[0]], [point[1]], "ok", ms=size*20)
    plt.plot(planner.start[0], planner.start[1], "xr")
    plt.plot(planner.end[0], planner.end[1], "xr")
    plt.axis([-2, 15, -2, 15])
    plt.grid(True)
    plt.pause(0.001)
项目:gail-driver    作者:sisl    | 项目源码 | 文件源码
def render(self):
        if GRAPHICS:
            plt.ion()
            plt.show()

            xBottom = self.drawParams['xBottom']
            carlength = self.drawParams['carlength']
            ego = self.drawParams['ego']

            self.drawParams['txtDist'].set_text('distance: %f' % self.d)
            self.drawParams['txtS_ego'].set_text('ego speed: %f' % self.s_ego)
            self.drawParams['txtS_lead'].set_text(
                'lead speed: %f' % self.s_lead[self.tstep])

            self.ax.set_xlim(
                (min([-self.d - 2 * carlength, xBottom]), 2 * carlength))

            ego.set_xy((-self.d - carlength, 0))

            plt.draw()

            plt.pause(0.1)
项目:gail-driver    作者:sisl    | 项目源码 | 文件源码
def render(self):
        plt.ion()
        plt.show()

        self.ax.cla()

        img = self.j.render(self.simparams, np.zeros(
            (500, 500)).astype('uint32'))
        #img=self.j.retrieve_frame_data(500, 500, self.simparams)
        self.ax.imshow(img, cmap=plt.get_cmap('bwr'))
        #self.ax.imshow(img, cmap=plt.get_cmap('seismic'))

        plt.draw()

        plt.pause(1e-6)

        return
项目:gail-driver    作者:sisl    | 项目源码 | 文件源码
def render(self):
        # plt.ion()
        # plt.show()

        # self.ax.cla()

        # img = self.j.render(self.simparams, np.zeros((500,500)).astype('uint32'))
        # #img=self.j.retrieve_frame_data(500, 500, self.simparams)
        # self.ax.imshow(img, cmap=plt.get_cmap('bwr'))
        # #self.ax.imshow(img, cmap=plt.get_cmap('seismic'))

        # plt.draw()

        # plt.pause(1e-6)

        return
项目:Multiple-Vehicle-Routing    作者:cbao    | 项目源码 | 文件源码
def update(self):
        """
        Updates plot as trucks move and targets are reached
        """

        # Plot unreached targets
        targets_unreached_x_coordinates = [target.x for target in self.dispatch.targets if target.reached is False]
        targets_unreached_y_coordinates = [target.y for target in self.dispatch.targets if target.reached is False]
        self.points_targets_unreached.set_data(targets_unreached_x_coordinates, targets_unreached_y_coordinates)

        # Plot reached targets
        targets_reached_x_coordinates = [target.x for target in self.dispatch.targets if target.reached is True]
        targets_reached_y_coordinates = [target.y for target in self.dispatch.targets if target.reached is True]
        self.points_targets_reached.set_data(targets_reached_x_coordinates, targets_reached_y_coordinates)

        # Plot movement of trucks
        self.points_red.set_data(np.float(self.dispatch.trucks[0].x), np.float(self.dispatch.trucks[0].y))
        self.points_green.set_data(np.float(self.dispatch.trucks[1].x), np.float(self.dispatch.trucks[1].y))

        # Pause for capture animation
        plt.pause(0.01)
项目:ML-Collection    作者:cahya-wirawan    | 项目源码 | 文件源码
def animate(self, compute_step, iterations, train_data_update_freq=20, test_data_update_freq=100, one_test_at_start=True, more_tests_at_start=False, save_movie=False):

        def animate_step(i):
            if (i == iterations // train_data_update_freq): #last iteration
                compute_step(iterations, True, True)
            else:
                for k in range(train_data_update_freq):
                    n = i * train_data_update_freq + k
                    request_data_update = (n % train_data_update_freq == 0)
                    request_test_data_update = (n % test_data_update_freq == 0) and (n > 0 or one_test_at_start)
                    if more_tests_at_start and n < test_data_update_freq: request_test_data_update = request_data_update
                    compute_step(n, request_test_data_update, request_data_update)
                    # makes the UI a little more responsive
                    plt.pause(0.001)
            if not self.is_paused():
                return self._mpl_update_func()

        self._animation = animation.FuncAnimation(self._mpl_figure, animate_step, int(iterations // train_data_update_freq + 1), init_func=self._mlp_init_func, interval=16, repeat=False, blit=False)

        if save_movie:
            mywriter = animation.FFMpegWriter(fps=24, codec='libx264', extra_args=['-pix_fmt', 'yuv420p', '-profile:v', 'high', '-tune', 'animation', '-crf', '18'])
            self._animation.save("./tensorflowvisu_video.mp4", writer=mywriter)
        else:
            plt.show(block=True)
项目:baal    作者:braingineer    | 项目源码 | 文件源码
def update_graph(self, xy_dict, D="train"):
        fd_X = lambda d,l: self.line_data[d][l]['X']
        fd_Y = lambda d,l: self.line_data[d][l]['Y']
        f_update = lambda d,l: (self.lines[d][l].set_xdata(fd_X(d,l)), 
                                self.lines[d][l].set_ydata(fd_Y(d,l)))
        b_ind = self.line_data[D]['batch index']
        ax_i = {'train':0, 'val':1}[D]
        for L,new_y in xy_dict.items():
            fd_X(D,L).append(b_ind)
            fd_Y(D,L).append(new_y)
            f_update(D,L)
            self.mins[D][L] = mi = min(min(self.mins[D][L], new_y), 0)
            self.maxes[D][L] = mx = max(max(self.maxes[D][L], new_y), 0)
            ax_j = {'loss':0, 'tree accuracy':1, 'attach accuracy':2}[L]

            self.axes[ax_i, ax_j].set_xlim(0, b_ind)
            self.axes[ax_i, ax_j].set_ylim(mi, mx)

        self.line_data[D]['batch index'] += 1
        plt.tight_layout()
        plt.draw()
        plt.pause(0.01)