Python matplotlib.pyplot.ion() Examples

The following are 30 code examples for showing how to use matplotlib.pyplot.ion(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module matplotlib.pyplot , or try the search function .

Example 1
Project: Attention-Gated-Networks   Author: ozan-oktay   File: visualise_att_maps_epoch.py    License: MIT License 6 votes vote down vote up
def plotNNFilter(units, figure_id, interp='bilinear', colormap=cm.jet, colormap_lim=None):
    plt.ion()
    filters = units.shape[2]
    n_columns = round(math.sqrt(filters))
    n_rows = math.ceil(filters / n_columns) + 1
    fig = plt.figure(figure_id, figsize=(n_rows*3,n_columns*3))
    fig.clf()

    for i in range(filters):
        ax1 = plt.subplot(n_rows, n_columns, i+1)
        plt.imshow(units[:,:,i].T, interpolation=interp, cmap=colormap)
        plt.axis('on')
        ax1.set_xticklabels([])
        ax1.set_yticklabels([])
        plt.colorbar()
        if colormap_lim:
            plt.clim(colormap_lim[0],colormap_lim[1])

    plt.subplots_adjust(wspace=0, hspace=0)
    plt.tight_layout()

# Epochs 
Example 2
Project: Attention-Gated-Networks   Author: ozan-oktay   File: visualise_fmaps.py    License: MIT License 6 votes vote down vote up
def plotNNFilter(units, figure_id, interp='bilinear', colormap=cm.jet, colormap_lim=None):
    plt.ion()
    filters = units.shape[2]
    n_columns = round(math.sqrt(filters))
    n_rows = math.ceil(filters / n_columns) + 1
    fig = plt.figure(figure_id, figsize=(n_rows*3,n_columns*3))
    fig.clf()

    for i in range(filters):
        ax1 = plt.subplot(n_rows, n_columns, i+1)
        plt.imshow(units[:,:,i].T, interpolation=interp, cmap=colormap)
        plt.axis('on')
        ax1.set_xticklabels([])
        ax1.set_yticklabels([])
        plt.colorbar()
        if colormap_lim:
            plt.clim(colormap_lim[0],colormap_lim[1])

    plt.subplots_adjust(wspace=0, hspace=0)
    plt.tight_layout()

# Load options 
Example 3
Project: Attention-Gated-Networks   Author: ozan-oktay   File: visualise_attention.py    License: MIT License 6 votes vote down vote up
def plotNNFilter(units, figure_id, interp='bilinear', colormap=cm.jet, colormap_lim=None, title=''):
    plt.ion()
    filters = units.shape[2]
    n_columns = round(math.sqrt(filters))
    n_rows = math.ceil(filters / n_columns) + 1
    fig = plt.figure(figure_id, figsize=(n_rows*3,n_columns*3))
    fig.clf()

    for i in range(filters):
        ax1 = plt.subplot(n_rows, n_columns, i+1)
        plt.imshow(units[:,:,i].T, interpolation=interp, cmap=colormap)
        plt.axis('on')
        ax1.set_xticklabels([])
        ax1.set_yticklabels([])
        plt.colorbar()
        if colormap_lim:
            plt.clim(colormap_lim[0],colormap_lim[1])

    plt.subplots_adjust(wspace=0, hspace=0)
    plt.tight_layout()
    plt.suptitle(title) 
Example 4
Project: Attention-Gated-Networks   Author: ozan-oktay   File: visualise_attention.py    License: MIT License 6 votes vote down vote up
def plotNNFilterOverlay(input_im, units, figure_id, interp='bilinear',
                        colormap=cm.jet, colormap_lim=None, title='', alpha=0.8):
    plt.ion()
    filters = units.shape[2]
    fig = plt.figure(figure_id, figsize=(5,5))
    fig.clf()

    for i in range(filters):
        plt.imshow(input_im[:,:,0], interpolation=interp, cmap='gray')
        plt.imshow(units[:,:,i], interpolation=interp, cmap=colormap, alpha=alpha)
        plt.axis('off')
        plt.colorbar()
        plt.title(title, fontsize='small')
        if colormap_lim:
            plt.clim(colormap_lim[0],colormap_lim[1])

    plt.subplots_adjust(wspace=0, hspace=0)
    plt.tight_layout()

    # plt.savefig('{}/{}.png'.format(dir_name,time.time()))




## Load options 
Example 5
def plot_durations(episode_durations):
    plt.ion()
    plt.figure(2)
    plt.clf()
    duration_t = torch.FloatTensor(episode_durations)
    plt.title('Training')
    plt.xlabel('Episodes')
    plt.ylabel('Duration')
    plt.plot(duration_t.numpy())

    if len(duration_t) >= 100:
        means = duration_t.unfold(0,100,1).mean(1).view(-1)
        means = torch.cat((torch.zeros(99), means))
        plt.plot(means.numpy())

    plt.pause(0.00001) 
Example 6
Project: firefly-monte-carlo   Author: HIPS   File: toy_dataset.py    License: MIT License 6 votes vote down vote up
def main():
    # Generate synthetic data
    x = 2 * npr.rand(N,D) - 1  # data features, an (N,D) array
    x[:, 0] = 1
    th_true = 10.0 * np.array([0, 1, 1])
    y = np.dot(x, th_true[:, None])[:, 0]
    t = npr.rand(N) > (1 / ( 1 + np.exp(y)))  # data targets, an (N) array of 0s and 1s

    # Obtain joint distributions over z and th
    model = ff.LogisticModel(x, t, th0=th0, y0=y0)

    # Set up step functions
    th = np.random.randn(D) * th0
    z = ff.BrightnessVars(N)
    th_stepper = ff.ThetaStepMH(model.log_p_joint, stepsize)
    z__stepper = ff.zStepMH(model.log_pseudo_lik, q)

    plt.ion()
    ax = plt.figure(figsize=(8, 6)).add_subplot(111)
    while True:
        th = th_stepper.step(th, z)  # Markov transition step for theta
        z  = z__stepper.step(th ,z)  # Markov transition step for z
        update_fig(ax, x, y, z, th, t)
        plt.draw()
        plt.pause(0.05) 
Example 7
Project: eht-imaging   Author: achael   File: clean.py    License: GNU General Public License v3.0 6 votes vote down vote up
def plot_i(Image, nit, chi2, fig=1, cmap='afmhot'):
    """Plot the total intensity image at each iteration
    """

    plt.ion()
    plt.figure(fig)
    plt.pause(0.00001)
    plt.clf()

    plt.imshow(Image.imvec.reshape(Image.ydim,Image.xdim), cmap=plt.get_cmap(cmap), interpolation='gaussian')
    xticks = ticks(Image.xdim, Image.psize/RADPERAS/1e-6)
    yticks = ticks(Image.ydim, Image.psize/RADPERAS/1e-6)
    plt.xticks(xticks[0], xticks[1])
    plt.yticks(yticks[0], yticks[1])
    plt.xlabel('Relative RA ($\mu$as)')
    plt.ylabel('Relative Dec ($\mu$as)')
    plt.title("step: %i  $\chi^2$: %f " % (nit, chi2), fontsize=20) 
Example 8
Project: viznet   Author: GiggleLiu   File: test_utils.py    License: MIT License 6 votes vote down vote up
def test_shapes():
    kwargs = {'ls':'--', 'lw':0.5, 'zorder':1, 'facecolor':'r', 'edgecolor': 'g'}
    plt.ion()
    ax = plt.subplot(111)
    shape_list = ['circle', 'golden', 'triangle', 'diamond', 'empty', 'dot', 'cross', 'measure', 'plus']
    for i, shape in enumerate(shape_list):
        func = eval('shapes.%s'%shape)
        for j in range(5):
            size_, angle_, roundness_, kwargs_ = 0.3, 0, 0, dict(kwargs)
            if j==1:
                size_ = 0.15
            if j==2:
                angle_ = np.pi/4.
            if j==3:
                angle_ = np.pi/4.
                roundness_ = 0.05
            if j==4:
                kwargs_['facecolor']='k'
            patches = func((i,-j), size_, angle_, roundness_, **kwargs_)
            for patch in patches:
                ax.add_patch(patch)
    plt.axis('equal')
    plt.axis('off')
    pdb.set_trace() 
Example 9
Project: pyhawkes   Author: slinderman   File: standard_sgd_demo.py    License: MIT License 6 votes vote down vote up
def sample_from_network_hawkes(C, K, T, dt, B):
    # Create a true model
    p = 0.8 * np.eye(C)
    v = 10.0 * np.eye(C) + 20.0 * (1-np.eye(C))
    c = (0.0 * (np.arange(K) < 10) + 1.0 * (np.arange(K)  >= 10)).astype(np.int)
    true_model = DiscreteTimeNetworkHawkesModelSpikeAndSlab(C=C, K=K, dt=dt, B=B, c=c, p=p, v=v)

    # Plot the true network
    plt.ion()
    plot_network(true_model.weight_model.A,
                 true_model.weight_model.W,
                 vmax=0.5)

    # Sample from the true model
    S,R = true_model.generate(T=T)

    # Return the spike count matrix
    return S, R, true_model 
Example 10
Project: tiny_gp   Author: moshesipper   File: tiny_gp_plus.py    License: GNU General Public License v3.0 6 votes vote down vote up
def prepare_plots():
    fig, axarr = plt.subplots(2, sharex=True)
    fig.canvas.set_window_title('EVOLUTIONARY PROGRESS')
    fig.subplots_adjust(hspace = 0.5)
    axarr[0].set_title('error', fontsize=14)
    axarr[1].set_title('mean size', fontsize=14)
    plt.xlabel('generation', fontsize=18)
    plt.ion() # interactive mode for plot
    axarr[0].set_xlim(0, GENERATIONS)
    axarr[0].set_ylim(0, 1) # fitness range
    xdata = []
    ydata = [ [], [] ]
    line = [None, None]
    line[0], = axarr[0].plot(xdata, ydata[0], 'b-') # 'b-' = blue line    
    line[1], = axarr[1].plot(xdata, ydata[1], 'r-') # 'r-' = red line
    return axarr, line, xdata, ydata 
Example 11
Project: srl-zoo   Author: araffin   File: interactive_plot.py    License: MIT License 6 votes vote down vote up
def plot2dRepresentation(states, rewards, images_path, name="Learned State Representation",
                         add_colorbar=True):
    plt.ion()
    fig = plt.figure(name)
    plt.clf()
    ax = fig.add_subplot(111)
    im = ax.scatter(states[:, 0], states[:, 1], s=7, c=np.clip(rewards, -1, 1), cmap='coolwarm', linewidths=0.1)
    ax.set_xlabel('State dimension 1')
    ax.set_ylabel('State dimension 2')
    ax.set_title(fill(name, TITLE_MAX_LENGTH))
    fig.tight_layout()
    if add_colorbar:
        fig.colorbar(im, label='Reward')

    createInteractivePlot(fig, ax, states, rewards, images_path)
    plt.show() 
Example 12
Project: srl-zoo   Author: araffin   File: interactive_plot.py    License: MIT License 6 votes vote down vote up
def plot3dRepresentation(states, rewards, images_path, name="Learned State Representation",
                         add_colorbar=True, multi_view=False):
    plt.ion()
    fig = plt.figure(name)
    plt.clf()
    ax = fig.add_subplot(111, projection='3d')
    im = ax.scatter(states[:, 0], states[:, 1], states[:, 2],
                    s=7, c=np.clip(rewards, -1, 1), cmap='coolwarm', linewidths=0.1)
    ax.set_xlabel('State dimension 1')
    ax.set_ylabel('State dimension 2')
    ax.set_zlabel('State dimension 3')
    ax.set_title(fill(name, TITLE_MAX_LENGTH))
    fig.tight_layout()
    if add_colorbar:
        fig.colorbar(im, label='Reward')

    if multi_view:
        createInteractivePlot(fig, ax, states, rewards, images_path, view=1)
        createInteractivePlot(plt.figure(name), ax, states, rewards, images_path, view=2)
    else:
        createInteractivePlot(fig, ax, states, rewards, images_path)

    plt.show() 
Example 13
Project: keras-utilities   Author: cbaziotis   File: callbacks.py    License: MIT License 6 votes vote down vote up
def on_train_begin(self, logs={}):
        sns.set_style("whitegrid")
        sns.set_style("whitegrid", {"grid.linewidth": 0.5,
                                    "lines.linewidth": 0.5,
                                    "axes.linewidth": 0.5})
        flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e",
                  "#2ecc71"]
        sns.set_palette(sns.color_palette(flatui))
        # flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e", "#2ecc71"]
        # sns.set_palette(sns.color_palette("Set2", 10))

        plt.ion()  # set plot to animated
        width = self.width * (1 + len(self.get_metrics(logs)))
        height = self.height
        self.fig = plt.figure(figsize=(width, height))

        # move it to the upper left corner
        move_figure(self.fig, 25, 25) 
Example 14
Project: keras-utilities   Author: cbaziotis   File: callbacks.py    License: MIT License 6 votes vote down vote up
def on_train_begin(self, logs={}):
        for layer in self.get_trainable_layers():
            for param in self.parameters:
                if any(w for w in layer.weights if param in w.name.split("_")):
                    name = layer.name + "_" + param
                    self.layers_stats[name]["values"] = numpy.asarray(
                        []).ravel()
                    for s in self.stats:
                        self.layers_stats[name][s] = []

        # plt.style.use('ggplot')
        plt.ion()  # set plot to animated
        width = 3 * (1 + len(self.stats))
        height = 2 * len(self.layers_stats)
        self.fig = plt.figure(figsize=(width, height))
        # sns.set_style("whitegrid")
        self.draw_plot() 
Example 15
Project: pylive   Author: makerportal   File: pylive.py    License: GNU General Public License v3.0 6 votes vote down vote up
def live_plotter(x_vec,y1_data,line1,identifier='',pause_time=0.1):
    if line1==[]:
        # this is the call to matplotlib that allows dynamic plotting
        plt.ion()
        fig = plt.figure(figsize=(13,6))
        ax = fig.add_subplot(111)
        # create a variable for the line so we can later update it
        line1, = ax.plot(x_vec,y1_data,'-o',alpha=0.8)        
        #update plot label/title
        plt.ylabel('Y Label')
        plt.title('Title: {}'.format(identifier))
        plt.show()
    
    # after the figure, axis, and line are created, we only need to update the y-data
    line1.set_ydata(y1_data)
    # adjust limits if new data goes beyond bounds
    if np.min(y1_data)<=line1.axes.get_ylim()[0] or np.max(y1_data)>=line1.axes.get_ylim()[1]:
        plt.ylim([np.min(y1_data)-np.std(y1_data),np.max(y1_data)+np.std(y1_data)])
    # this pauses the data so the figure/axis can catch up - the amount of pause can be altered above
    plt.pause(pause_time)
    
    # return line so we can update it again in the next iteration
    return line1

# the function below is for updating both x and y values (great for updating dates on the x-axis) 
Example 16
Project: pylive   Author: makerportal   File: pylive.py    License: GNU General Public License v3.0 6 votes vote down vote up
def live_plotter_xy(x_vec,y1_data,line1,identifier='',pause_time=0.01):
    if line1==[]:
        plt.ion()
        fig = plt.figure(figsize=(13,6))
        ax = fig.add_subplot(111)
        line1, = ax.plot(x_vec,y1_data,'r-o',alpha=0.8)
        plt.ylabel('Y Label')
        plt.title('Title: {}'.format(identifier))
        plt.show()
        
    line1.set_data(x_vec,y1_data)
    plt.xlim(np.min(x_vec),np.max(x_vec))
    if np.min(y1_data)<=line1.axes.get_ylim()[0] or np.max(y1_data)>=line1.axes.get_ylim()[1]:
        plt.ylim([np.min(y1_data)-np.std(y1_data),np.max(y1_data)+np.std(y1_data)])

    plt.pause(pause_time)
    
    return line1 
Example 17
Project: GraphicDesignPatternByPython   Author: Relph1119   File: pyplot.py    License: MIT License 6 votes vote down vote up
def draw():
    """Redraw the current figure.

    This is used to update a figure that has been altered, but not
    automatically re-drawn.  If interactive mode is on (:func:`.ion()`), this
    should be only rarely needed, but there may be ways to modify the state of
    a figure without marking it as `stale`.  Please report these cases as
    bugs.

    A more object-oriented alternative, given any
    :class:`~matplotlib.figure.Figure` instance, :attr:`fig`, that
    was created using a :mod:`~matplotlib.pyplot` function, is::

        fig.canvas.draw_idle()
    """
    get_current_fig_manager().canvas.draw_idle() 
Example 18
Project: VNect   Author: XinArkh   File: utils.py    License: Apache License 2.0 6 votes vote down vote up
def draw_limbs_3d(joints_3d, joint_parents):
    fig = plt.figure()
    ax_3d = plt.axes(projection='3d')
    ax_3d.clear()
    ax_3d.view_init(-90, -90)
    ax_3d.set_xlim(-500, 500)
    ax_3d.set_ylim(-500, 500)
    ax_3d.set_zlim(-500, 500)
    ax_3d.set_xticks([])
    ax_3d.set_yticks([])
    ax_3d.set_zticks([])
    white = (1.0, 1.0, 1.0, 0.0)
    ax_3d.w_xaxis.set_pane_color(white)
    ax_3d.w_yaxis.set_pane_color(white)
    ax_3d.w_xaxis.line.set_color(white)
    ax_3d.w_yaxis.line.set_color(white)
    ax_3d.w_zaxis.line.set_color(white)
    for i in range(joints_3d.shape[0]):
        x_pair = [joints_3d[i, 0], joints_3d[joint_parents[i], 0]]
        y_pair = [joints_3d[i, 1], joints_3d[joint_parents[i], 1]]
        z_pair = [joints_3d[i, 2], joints_3d[joint_parents[i], 2]]
        ax_3d.plot(x_pair, y_pair, zs=z_pair, linewidth=3)
    plt.ion()
    plt.show() 
Example 19
Project: fenics-topopt   Author: zfergus   File: gui.py    License: MIT License 5 votes vote down vote up
def __init__(self, nelx, nely, title=""):
        """Initialize plot and plot the initial design"""
        plt.ion()  # Ensure that redrawing is possible
        self.fig, self.ax = plt.subplots()
        self.im = self.ax.imshow(-np.zeros((nelx, nely)).T, cmap='gray',
            interpolation='none', norm=colors.Normalize(vmin=-1, vmax=0))
        plt.xlabel(title)
        # self.fig.tight_layout()
        self.fig.show()
        self.nelx, self.nely = nelx, nely 
Example 20
Project: fenics-topopt   Author: zfergus   File: gui.py    License: MIT License 5 votes vote down vote up
def __init__(self, nelx, nely, title=""):
        """Initialize plot and plot the initial design"""
        plt.ion()  # Ensure that redrawing is possible
        self.fig, self.ax = plt.subplots()
        self.im = self.ax.imshow(-np.zeros((nelx, nely)).T, cmap='gray',
            interpolation='none', norm=colors.Normalize(vmin=-1, vmax=0))
        plt.xlabel(title)
        # self.fig.tight_layout()
        self.fig.show()
        self.nelx, self.nely = nelx, nely 
Example 21
Project: neural-fingerprinting   Author: StephanZheng   File: utils.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def pair_visual(original, adversarial, figure=None):
    """
    This function displays two images: the original and the adversarial sample
    :param original: the original input
    :param adversarial: the input after perterbations have been applied
    :param figure: if we've already displayed images, use the same plot
    :return: the matplot figure to reuse for future samples
    """
    import matplotlib.pyplot as plt

    # Squeeze the image to remove single-dimensional entries from array shape
    original = np.squeeze(original)
    adversarial = np.squeeze(adversarial)

    # Ensure our inputs are of proper shape
    assert(len(original.shape) == 2 or len(original.shape) == 3)

    # To avoid creating figures per input sample, reuse the sample plot
    if figure is None:
        plt.ion()
        figure = plt.figure()
        figure.canvas.set_window_title('Cleverhans: Pair Visualization')

    # Add the images to the plot
    perterbations = adversarial - original
    for index, image in enumerate((original, perterbations, adversarial)):
        figure.add_subplot(1, 3, index + 1)
        plt.axis('off')

        # If the image is 2D, then we have 1 color channel
        if len(image.shape) == 2:
            plt.imshow(image, cmap='gray')
        else:
            plt.imshow(image)

        # Give the plot some time to update
        plt.pause(0.01)

    # Draw the plot and return
    plt.show()
    return figure 
Example 22
Project: poeai   Author: nicholastoddsmith   File: BotDebugger.py    License: MIT License 5 votes vote down vote up
def PlotMap(self):
        mm = self.B.mm
        cp = mm.GetPosition()
        if self.B.p is not None:
            ppx = [self.B.p[0], cp[0]]
            ppy = [self.B.p[1], cp[1]]
        else:
            ppx, ppy = [cp[0]], [cp[1]]
        pc = ['r', 'g']
        C, CC = [], []
        for qp in mm.GetCells():
            C.append(qp[0:2])
            CC.append(mm.GetCellType(qp))
        C = np.stack(C)
        if self.sct is None:
            mpl.ion()
            fig, self.ax  = mpl.subplots()
            fig.canvas.manager.window.setGeometry(840, 5, 640, 545)
            self.sct = 1
        else:
            self.ax.clear()
        self.ax.scatter(C[:, 0], C[:, 1], color = [CF(j) for j in CC])
        self.ax.scatter(ppx, ppy, c = pc, s = 64)
        self.ax.scatter([mm.hp[0]], [mm.hp[1]], color = 'm', s = 64)
        self.ax.set_title("At: " + str(cp))
        mpl.pause(0.1) 
Example 23
Project: VRPTW-ga   Author: shayan-ys   File: report.py    License: MIT License 5 votes vote down vote up
def __init__(self, run_name: str):
        if ga_params.draw_plot:
            plt.ion()
            self.fig, self.subplot = plt.subplots()
            self.fig_node_connector, self.subplot2 = plt.subplots()
        if ga_params.export_spreadsheet:
            self.init_spreadsheet(run_name=run_name) 
Example 24
Project: pysat   Author: pysat   File: test_ssnl_plot.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_scatterplot_w_ion(self):
        """Check if scatterplot generates and resets to interactive mode"""

        plt.ion()
        figs = plot.scatterplot(self.testInst, 'longitude', 'latitude',
                                'slt', [0.0, 24.0])

        axes = figs[0].get_axes()
        assert len(figs) == 1
        assert len(axes) == 3
        assert mpl.is_interactive() 
Example 25
Project: cgpm   Author: probcomp   File: state.py    License: Apache License 2.0 5 votes vote down vote up
def plot(self):
        """Plots observation histogram and posterior distirbution of Dims."""
        import matplotlib.pyplot as plt
        from cgpm.utils import plots as pu
        layout = pu.get_state_plot_layout(self.n_cols())
        fig = plt.figure(
            num=None,
            figsize=(layout['plot_inches_y'], layout['plot_inches_x']),
            dpi=75,
            facecolor='w',
            edgecolor='k',
            frameon=False,
            tight_layout=True
        )
        # Do not plot more than 6 by 4.
        if self.n_cols() > 24:
            return
        fig.clear()
        for i, dim in enumerate(self.dims()):
            index = dim.index
            ax = fig.add_subplot(layout['plots_x'], layout['plots_y'], i+1)
            dim.plot_dist(self.X[dim.index], ax=ax)
            ax.text(
                1,1, "K: %i " % len(dim.clusters),
                transform=ax.transAxes,
                fontsize=12,
                weight='bold',
                color='blue',
                horizontalalignment='right',
                verticalalignment='top'
            )
            ax.grid()
        # XXX TODO: Write png to disk rather than slow matplotlib animation.
        # plt.draw()
        # plt.ion()
        # plt.show()
        return fig

    # --------------------------------------------------------------------------
    # Internal CRP utils. 
Example 26
Project: Deep-reinforcement-learning-with-pytorch   Author: sweetice   File: DQN.py    License: MIT License 5 votes vote down vote up
def main():
    dqn = DQN()
    episodes = 400
    print("Collecting Experience....")
    reward_list = []
    plt.ion()
    fig, ax = plt.subplots()
    for i in range(episodes):
        state = env.reset()
        ep_reward = 0
        while True:
            env.render()
            action = dqn.choose_action(state)
            next_state, _ , done, info = env.step(action)
            x, x_dot, theta, theta_dot = next_state
            reward = reward_func(env, x, x_dot, theta, theta_dot)

            dqn.store_transition(state, action, reward, next_state)
            ep_reward += reward

            if dqn.memory_counter >= MEMORY_CAPACITY:
                dqn.learn()
                if done:
                    print("episode: {} , the episode reward is {}".format(i, round(ep_reward, 3)))
            if done:
                break
            state = next_state
        r = copy.copy(reward)
        reward_list.append(r)
        ax.set_xlim(0,300)
        #ax.cla()
        ax.plot(reward_list, 'g-', label='total_loss')
        plt.pause(0.001) 
Example 27
def plot(live_time):
    plt.ion()
    plt.grid()
    plt.plot(live_time, 'g-')
    plt.xlabel('running step')
    plt.ylabel('live time')
    plt.pause(0.000001) 
Example 28
Project: ibllib   Author: int-brain-lab   File: smooth.py    License: MIT License 5 votes vote down vote up
def smooth_demo():

    t = np.linspace(-4, 4, 100)
    x = np.sin(t)
    xn = x + np.random.randn(len(t)) * 0.1

    ws = 31

    plt.subplot(211)
    plt.plot(np.ones(ws))

    windows = ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']

    for w in windows[1:]:
        eval('plt.plot(np.' + w + '(ws) )')

    plt.axis([0, 30, 0, 1.1])

    plt.legend(windows)
    plt.title("The smoothing windows")
    plt.subplot(212)
    plt.plot(x)
    plt.plot(xn)
    for w in windows:
        plt.plot(rolling_window(xn, 10, w))
    lst = ['original signal', 'signal with noise']
    lst.extend(windows)

    plt.legend(lst)
    plt.title("Smoothing a noisy signal")
    plt.ion() 
Example 29
Project: ehtplot   Author: liamedeiros   File: figure.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __call__(self, **kwargs):
        """Figure realizer

        The Figure class only keeps track of a root panel.  It does
        not contain an actual matplotlib Figure instance.  Whenever a
        figure needs to be created, Figure creates a new matplotlib
        Figure in order to drew/rendered/realized the figure.

        Args:

            **kwargs (dict): Arbitrary Figure-specific keyworded
                arguments that are used to construct the matplotlib
                Figure.

        """
        kwprops = merge_dict(self.kwprops, kwargs)
        style   = kwprops.pop('style')

        with mpl.rc_context():
            mpl.rcdefaults()
            plt.style.use(style)

            imode = mpl.is_interactive()
            if imode:
                plt.ioff()

            fig = plt.figure(**kwprops)
            ax  = newaxes(fig)
            yield fig, ax

            if imode:
                plt.ion() 
Example 30
Project: grass_pytorch   Author: kevin-kaixu   File: dynamicplot.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, title, xdata, ydata):
        if len(xdata) == 0:
            return
        plt.ion()
        self.fig = plt.figure()
        self.ax = self.fig.add_subplot(111)
        self.ax.set_title(title, color='C0')
        self.ax.set_xlim(xdata[0], xdata[-1])
        self.yline = {}
        for label, data, idx in zip(ydata.keys(), ydata.values(), range(len(ydata))):
            if len(xdata) != len(data):
                print('DynamicPlot::Error: Dimensions of x- and y-data not the same (skipping).')
                continue
            self.yline[label], = self.ax.plot(xdata, data, 'C{}'.format((idx+1)%9), label=" ".join(label.split('_')))
        self.ax.legend()