Python matplotlib.pylab.subplots() Examples

The following are 30 code examples of matplotlib.pylab.subplots(). 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 also want to check out all available functions/classes of the module matplotlib.pylab , or try the search function .
Example #1
Source File: viz.py    From ceviche with MIT License 6 votes vote down vote up
def abs(val, outline=None, ax=None, cbar=False, cmap='magma', outline_alpha=0.5, outline_val=None):
    """Plots the absolute value of 'val', optionally overlaying an outline of 'outline'
    """
    
    if ax is None:
        fig, ax = plt.subplots(1, 1, constrained_layout=True)      
    
    vmax = np.abs(val).max()
    h = ax.imshow(np.abs(val.T), cmap=cmap, origin='lower left', vmin=0, vmax=vmax)
    
    if outline_val is None and outline is not None: outline_val = 0.5*(outline.min()+outline.max())
    if outline is not None:
        ax.contour(outline.T, [outline_val], colors='w', alpha=outline_alpha)
    
    ax.set_ylabel('y')
    ax.set_xlabel('x')
    if cbar:
        plt.colorbar(h, ax=ax)
    
    return ax 
Example #2
Source File: resnet_wgan_gp_cifar10_train.py    From Hands-On-Generative-Adversarial-Networks-with-Keras with MIT License 6 votes vote down vote up
def plot_losses(losses_d, losses_g, filename):
    losses_d = np.array(losses_d)
    fig, axes = plt.subplots(3, 2, figsize=(8, 8))
    axes = axes.flatten()
    axes[0].plot(losses_d[:, 0])
    axes[1].plot(losses_d[:, 1])
    axes[2].plot(losses_d[:, 2])
    axes[3].plot(losses_d[:, 3])
    axes[4].plot(losses_g)
    axes[0].set_title("losses_d")
    axes[1].set_title("losses_d_real")
    axes[2].set_title("losses_d_fake")
    axes[3].set_title("losses_d_gp")
    axes[4].set_title("losses_g")
    plt.tight_layout()
    plt.savefig(filename)
    plt.close() 
Example #3
Source File: plotting_utils.py    From nonparaSeq2seqVC_code with MIT License 6 votes vote down vote up
def plot_alignment_to_numpy(alignment, info=None):
    fig, ax = plt.subplots(figsize=(6, 4))
    im = ax.imshow(alignment, aspect='auto', origin='lower',
                   interpolation='none')
    fig.colorbar(im, ax=ax)
    xlabel = 'Decoder timestep'
    if info is not None:
        xlabel += '\n\n' + info
    plt.xlabel(xlabel)
    plt.ylabel('Encoder timestep')
    plt.tight_layout()

    fig.canvas.draw()
    data = save_figure_to_numpy(fig)
    plt.close()
    return data 
Example #4
Source File: plot.py    From Tacotron2-PyTorch with MIT License 6 votes vote down vote up
def plot_alignment_to_numpy(alignment, info=None):
    fig, ax = plt.subplots(figsize=(6, 4))
    im = ax.imshow(alignment, aspect='auto', origin='lower',
                   interpolation='none')
    fig.colorbar(im, ax=ax)
    xlabel = 'Decoder timestep'
    if info is not None:
        xlabel += '\n\n' + info
    plt.xlabel(xlabel)
    plt.ylabel('Encoder timestep')
    plt.tight_layout()

    fig.canvas.draw()
    data = save_figure_to_numpy(fig)
    plt.close()
    return data 
Example #5
Source File: data_augmentation.py    From ConvNetQuake with MIT License 6 votes vote down vote up
def plot_true_and_augmented_data(sample,noised_sample,label,n_examples):
    output_dir = os.path.split(FLAGS.output)[0]
    # Save augmented data
    plt.clf()
    fig, ax = plt.subplots(3,1)
    for t in range(noised_sample.shape[1]):
        ax[t].plot(noised_sample[:,t])
        ax[t].set_xlabel('time (samples)')
        ax[t].set_ylabel('amplitude')
    ax[0].set_title('window {:03d}, cluster_id: {}'.format(n_examples,label))
    plt.savefig(os.path.join(output_dir, "augmented_data",
                            'augmented_{:03d}.pdf'.format(n_examples)))
    plt.close()

    # Save true data
    plt.clf()
    fig, ax = plt.subplots(3,1)
    for t in range(sample.shape[1]):
        ax[t].plot(sample[:,t])
        ax[t].set_xlabel('time (samples)')
        ax[t].set_ylabel('amplitude')
    ax[0].set_title('window {:03d}, cluster_id: {}'.format(n_examples,label))
    plt.savefig(os.path.join(output_dir, "true_data",
                            'true__{:03d}.pdf'.format(n_examples)))
    plt.close() 
Example #6
Source File: helpers.py    From NeMo with Apache License 2.0 6 votes vote down vote up
def plot_gate_outputs_to_numpy(gate_targets, gate_outputs):
    fig, ax = plt.subplots(figsize=(12, 3))
    ax.scatter(
        range(len(gate_targets)), gate_targets, alpha=0.5, color='green', marker='+', s=1, label='target',
    )
    ax.scatter(
        range(len(gate_outputs)), gate_outputs, alpha=0.5, color='red', marker='.', s=1, label='predicted',
    )

    plt.xlabel("Frames (Green target, Red predicted)")
    plt.ylabel("Gate State")
    plt.tight_layout()

    fig.canvas.draw()
    data = save_figure_to_numpy(fig)
    plt.close()
    return data 
Example #7
Source File: plotting_utils.py    From fac-via-ppg with Apache License 2.0 6 votes vote down vote up
def plot_alignment_to_numpy(alignment, info=None):
    fig, ax = plt.subplots(figsize=(6, 4))
    im = ax.imshow(alignment, aspect='auto', origin='lower',
                   interpolation='none')
    fig.colorbar(im, ax=ax)
    xlabel = 'Decoder timestep'
    if info is not None:
        xlabel += '\n\n' + info
    plt.xlabel(xlabel)
    plt.ylabel('Encoder timestep')
    plt.tight_layout()

    fig.canvas.draw()
    data = save_figure_to_numpy(fig)
    plt.close()
    return data 
Example #8
Source File: bitcoin_price.py    From deep_learning with MIT License 6 votes vote down vote up
def train(self):
        """
        训练
        """
        training_set,test_set, training_inputs, training_target, test_inputs, test_targets = self.getData()

        eth_model = self.buildModel(training_inputs, 1, 20)
        training_target = (training_set["eth_Close"][self.window_len:].values /
                           training_set['eth_Close'][:-self.window_len].values) - 1

        eth_history = eth_model.fit(training_inputs, training_target,
                                    epochs=self.epochs, batch_size=self.batch_size,
                                    verbose=self.verbose, shuffle=True)

        fig, ax1 = plt.subplots(1, 1)
        ax1.plot(eth_history.epoch, eth_history.history['loss'])
        ax1.set_title('Training Loss')
        ax1.set_ylabel('MAE',fontsize=12)
        ax1.set_xlabel('# Epochs',fontsize=12)
        plt.show() 
Example #9
Source File: menu.py    From trajectory_tracking with MIT License 6 votes vote down vote up
def plot_trajectory(name):
    STEPS = 600
    DELTA = 1 if name != 'linear' else 0.1
    trajectory = create_trajectory(name, STEPS)

    x = [trajectory.get_position_at(i * DELTA).x for i in range(STEPS)]
    y = [trajectory.get_position_at(i * DELTA).y for i in range(STEPS)]

    trajectory_fig, trajectory_plot = plt.subplots(1, 1)
    trajectory_plot.plot(x, y, label='trajectory', lw=3)
    trajectory_plot.set_title(name.title() + ' Trajectory', fontsize=20)
    trajectory_plot.set_xlabel(r'$x{\rm[m]}$', fontsize=18)
    trajectory_plot.set_ylabel(r'$y{\rm[m]}$', fontsize=18)
    trajectory_plot.legend(loc=0)
    trajectory_plot.grid()
    plt.show() 
Example #10
Source File: plotting_utils.py    From nonparaSeq2seqVC_code with MIT License 6 votes vote down vote up
def plot_alignment_to_numpy(alignment, info=None):
    fig, ax = plt.subplots(figsize=(6, 4))
    im = ax.imshow(alignment, aspect='auto', origin='lower',
                   interpolation='none')
    fig.colorbar(im, ax=ax)
    xlabel = 'Decoder timestep'
    if info is not None:
        xlabel += '\n\n' + info
    plt.xlabel(xlabel)
    plt.ylabel('Encoder timestep')
    plt.tight_layout()

    fig.canvas.draw()
    data = save_figure_to_numpy(fig)
    plt.close()
    return data 
Example #11
Source File: test_fields_fdtd.py    From ceviche with MIT License 6 votes vote down vote up
def test_fields_H(self):

        F = fdtd(self.eps_r, dL=self.dL, npml=self.pml)

        fig, ax = plt.subplots(figsize=(10, 10))
        im = ax.pcolormesh(np.zeros((self.Nx, self.Ny)), cmap='RdBu')

        for t_index in range(self.steps):

            fields = F.forward(Jx=self.gaussian(t_index))

            if t_index % self.skip_rate == 0:

                max_E = np.abs(fields['Hz']).max()
                im.set_array(fields['Hz'][:, :, 0].ravel())
                im.set_clim([-1, 1])
                plt.pause(0.001)
                ax.set_title('time = {}'.format(t_index)) 
Example #12
Source File: rock_paper_scissors.py    From evol with MIT License 6 votes vote down vote up
def plot(self):
        try:
            import pandas as pd
            import matplotlib.pylab as plt
            df = pd.DataFrame(self.history).set_index(['id', 'generation']).fillna(0)
            population_size = sum(df.iloc[0].values)
            n_populations = df.reset_index()['id'].nunique()
            fig, axes = plt.subplots(nrows=n_populations, figsize=(12, 2*n_populations),
                                     sharex='all', sharey='all', squeeze=False)
            for row, (_, pop) in zip(axes, df.groupby('id')):
                ax = row[0]
                pop.reset_index(level='id', drop=True).plot(ax=ax)
                ax.set_ylim([0, population_size])
                ax.set_xlabel('iteration')
                ax.set_ylabel('# w/ preference')
                if n_populations > 1:
                    for i in range(0, df.reset_index().generation.max(), 50):
                        ax.axvline(i)
            plt.show()
        except ImportError:
            print("If you install matplotlib and pandas you will get a pretty plot.") 
Example #13
Source File: drawing.py    From BIRL with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_figure(im_size, figsize_max=MAX_FIGURE_SIZE):
    """ create an empty figure of image size maximise maximal size

    :param tuple(int,int) im_size:
    :param float figsize_max:
    :return:

    >>> fig, ax = create_figure((100, 150))
    >>> isinstance(fig, plt.Figure)
    True
    """
    assert len(im_size) >= 2, 'not valid image size - %r' % im_size
    size = np.array(im_size[:2])
    fig_size = size[::-1] / float(size.max()) * figsize_max
    fig, ax = plt.subplots(figsize=fig_size)
    return fig, ax 
Example #14
Source File: viz.py    From ceviche with MIT License 6 votes vote down vote up
def real(val, outline=None, ax=None, cbar=False, cmap='RdBu', outline_alpha=0.5):
    """Plots the real part of 'val', optionally overlaying an outline of 'outline'
    """

    if ax is None:
        fig, ax = plt.subplots(1, 1, constrained_layout=True)
    
    vmax = np.abs(val).max()
    h = ax.imshow(np.real(val.T), cmap=cmap, origin='lower left', vmin=-vmax, vmax=vmax)
    
    if outline is not None:
        ax.contour(outline.T, 0, colors='k', alpha=outline_alpha)
    
    ax.set_ylabel('y')
    ax.set_xlabel('x')
    if cbar:
        plt.colorbar(h, ax=ax)
    
    return ax 
Example #15
Source File: run_lookup.py    From rasa_lookup_demo with Apache License 2.0 6 votes vote down vote up
def plot_metrics(metric_list, save_path=None):
    # runs through each test case and adds a set of bars to a plot.  Saves

    f, (ax1) = plt.subplots(1, 1)
    plt.grid(True)

    print_metrics(metric_list)

    bar_metrics(metric_list[0], ax1, index=0)
    bar_metrics(metric_list[1], ax1, index=1)
    bar_metrics(metric_list[2], ax1, index=2)

    if save_path is None:
        save_path = "img/bar_" + key + ".png"

    plt.savefig(save_path, dpi=400) 
Example #16
Source File: equality and segregation.py    From python-urbanPlanning with MIT License 6 votes vote down vote up
def showVector(df,columnName):
    # print(df.columns)
    #可以显示vecter(polygon,point)数据。show vector
    multi=2
    fig, ax = plt.subplots(figsize=(14*multi, 8*multi))
    df.plot(column=columnName,
            categorical=True,
            legend=True,
            scheme='QUANTILES',
            cmap='RdBu', #'OrRd'
            ax=ax)
    # df.plot()
    # adjust legend location
    leg = ax.get_legend()
    # leg.set_bbox_to_anchor((1.15,0.5))
    ax.set_axis_off()    
    plt.show()  
    
 # As provided in the answer by Divakar  https://stackoverflow.com/questions/41190852/most-efficient-way-to-forward-fill-nan-values-in-numpy-array 
Example #17
Source File: test_cca.py    From ibllib with MIT License 6 votes vote down vote up
def test_plotting(self):
        """
        This test is just to document current use in libraries in case of refactoring
        """
        corrs = np.array([.6, .2, .1, .001])
        errs = np.array([.1, .05, .04, .0005])
        fig, ax1 = plt.subplots(1, 1, figsize=(5, 5))
        cca.plot_correlations(corrs, errs, ax=ax1, color='blue')
        cca.plot_correlations(corrs * .1, errs, ax=ax1, color='orange')

    # Shuffle data
    # ...
    # fig, ax1 = plt.subplots(1,1,figsize(10,10))
    # plot_correlations(corrs, ... , ax=ax1, color='blue')
    # plot_correlations(shuffled_coors, ..., ax=ax1, color='red')
    # plt.show() 
Example #18
Source File: Exploratory Spatial Data Analysis in PySAL.py    From python-urbanPlanning with MIT License 6 votes vote down vote up
def showVector(df,columnName):
    # print(df.columns)
    #可以显示vecter(polygon,point)数据。show vector
    multi=2
    fig, ax = plt.subplots(figsize=(14*multi, 8*multi))
    df.plot(column=columnName,
            categorical=True,
            legend=True,
            scheme='QUANTILES',
            cmap='RdBu', #'OrRd'
            ax=ax)
    # df.plot()
    # adjust legend location
    leg = ax.get_legend()
    # leg.set_bbox_to_anchor((1.15,0.5))
    ax.set_axis_off()    
    plt.show()  


    
#Spatial_Autocorrelation_for_Areal_Unit_Data 
Example #19
Source File: GeospatIal Distribution DYnamics.py    From python-urbanPlanning with MIT License 6 votes vote down vote up
def showVector(df,columnName):
    # print(df.columns)
    #可以显示vecter(polygon,point)数据。show vector
    multi=2
    fig, ax = plt.subplots(figsize=(14*multi, 8*multi))
    df.plot(column=columnName,
            categorical=True,
            legend=True,
            scheme='QUANTILES',
            cmap='RdBu', #'OrRd'
            ax=ax)
    # df.plot()
    # adjust legend location
    leg = ax.get_legend()
    # leg.set_bbox_to_anchor((1.15,0.5))
    ax.set_axis_off()    
    plt.show()  


#absolute dynamics and relative dynamics 
Example #20
Source File: audio.py    From Self-Supervised-Speech-Pretraining-and-Representation-Learning with MIT License 6 votes vote down vote up
def plot_spectrogram_to_numpy(spectrogram):
    spectrogram = spectrogram.transpose(1, 0)
    fig, ax = plt.subplots(figsize=(12, 3))
    im = ax.imshow(spectrogram, aspect="auto", origin="lower",
                   interpolation='none')
    plt.colorbar(im, ax=ax)
    plt.xlabel("Frames")
    plt.ylabel("Channels")
    plt.tight_layout()

    fig.canvas.draw()
    data = _save_figure_to_numpy(fig)
    plt.close()
    return data


####################
# PLOT SPECTROGRAM #
#################### 
Example #21
Source File: show_leaned_filters.py    From nnabla-examples with Apache License 2.0 5 votes vote down vote up
def show():
    args = get_args()

    # Load model
    nn.load_parameters(args.model_load_path)
    params = nn.get_parameters()

    # Show heatmap
    for name, param in params.items():
        # SSL only on convolution weights
        if "conv/W" not in name:
            continue
        print(name)
        n, m, k0, k1 = param.d.shape
        w_matrix = param.d.reshape((n, m * k0 * k1))
        # Filter x Channel heatmap

        fig, ax = plt.subplots()
        ax.set_title("{} with shape {} \n Filter x (Channel x Heigh x Width)".format(
            name, (n, m, k0, k1)))
        heatmap = ax.pcolor(w_matrix)
        fig.colorbar(heatmap)

        plt.pause(0.5)
        raw_input("Press Key")
        plt.close() 
Example #22
Source File: vis_finetune.py    From omgh with MIT License 5 votes vote down vote up
def main(files):
    plt.style.use('ggplot')
    fig, ax1 = plt.subplots()
    ax2 = ax1.twinx()
    ax1.set_xlabel('iteration')
    ax1.set_ylabel('loss')
    ax2.set_ylabel('accuracy %')
    for i, log_file in enumerate(files):
        loss_iterations, losses, accuracy_iterations, accuracies, accuracies_iteration_checkpoints_ind = parse_log(log_file)
        disp_results(fig, ax1, ax2, loss_iterations, losses, accuracy_iterations, accuracies, accuracies_iteration_checkpoints_ind, color_ind=i)
    plt.show() 
Example #23
Source File: plot.py    From Tacotron2-PyTorch with MIT License 5 votes vote down vote up
def plot_spectrogram_to_numpy(spectrogram):
    fig, ax = plt.subplots(figsize=(12, 3))
    im = ax.imshow(spectrogram, aspect="auto", origin="lower",
                   interpolation='none')
    plt.colorbar(im, ax=ax)
    plt.xlabel("Frames")
    plt.ylabel("Channels")
    plt.tight_layout()

    fig.canvas.draw()
    data = save_figure_to_numpy(fig)
    plt.close()
    return data 
Example #24
Source File: speech_utils.py    From python-dlpy with Apache License 2.0 5 votes vote down vote up
def convert_one_audio_file_to_specgram(local_audio_file, converted_local_png_file):
    '''
    Convert a local audio file into a png format with spectrogram.

    Parameters
    ----------
    local_audio_file : string
        Local location to the audio file to be converted.

    converted_local_png_file : string
        Local location to store the converted audio file

    Returns
    -------
    None

    Raises
    ------
    DLPyError
        If anything goes wrong, it complains and prints the appropriate message.

    '''

    try:
        import soundfile as sf
        import matplotlib.pylab as plt
    except (ModuleNotFoundError, ImportError):
        raise DLPyError('cannot import soundfile')

    data, sampling_rate = sf.read(local_audio_file)

    fig, ax = plt.subplots(1)
    fig.subplots_adjust(left=0, right=1, bottom=0, top=1)
    ax.axis('off')
    ax.specgram(x=data, Fs=sampling_rate)
    ax.axis('off')
    fig.savefig(converted_local_png_file, dpi=300, frameon='false')
    # this is the key to avoid mem leaking in notebook
    plt.ioff()
    plt.close(fig) 
Example #25
Source File: optimize_mode_converter.py    From ceviche with MIT License 5 votes vote down vote up
def viz_sim(epsr):
    """Solve and visualize a simulation with permittivity 'epsr'
    """
    simulation = fdfd_ez(omega, dl, epsr, [Npml, Npml])
    Hx, Hy, Ez = simulation.solve(source)
    fig, ax = plt.subplots(1, 2, constrained_layout=True, figsize=(6,3))
    ceviche.viz.real(Ez, outline=epsr, ax=ax[0], cbar=False)
    ax[0].plot(input_slice.x*np.ones(len(input_slice.y)), input_slice.y, 'g-')
    ax[0].plot(output_slice.x*np.ones(len(output_slice.y)), output_slice.y, 'r-')
    ceviche.viz.abs(epsr, ax=ax[1], cmap='Greys');
    plt.show()
    return (simulation, ax) 
Example #26
Source File: helpers.py    From NeMo with Apache License 2.0 5 votes vote down vote up
def plot_spectrogram_to_numpy(spectrogram):
    fig, ax = plt.subplots(figsize=(12, 3))
    im = ax.imshow(spectrogram, aspect="auto", origin="lower", interpolation='none')
    plt.colorbar(im, ax=ax)
    plt.xlabel("Frames")
    plt.ylabel("Channels")
    plt.tight_layout()

    fig.canvas.draw()
    data = save_figure_to_numpy(fig)
    plt.close()
    return data 
Example #27
Source File: helpers.py    From NeMo with Apache License 2.0 5 votes vote down vote up
def plot_alignment_to_numpy(alignment, info=None):
    fig, ax = plt.subplots(figsize=(6, 4))
    im = ax.imshow(alignment, aspect='auto', origin='lower', interpolation='none')
    fig.colorbar(im, ax=ax)
    xlabel = 'Decoder timestep'
    if info is not None:
        xlabel += '\n\n' + info
    plt.xlabel(xlabel)
    plt.ylabel('Encoder timestep')
    plt.tight_layout()

    fig.canvas.draw()
    data = save_figure_to_numpy(fig)
    plt.close()
    return data 
Example #28
Source File: utils.py    From ceviche with MIT License 5 votes vote down vote up
def aniplot(F, source, steps, component='Ez', num_panels=10):
    """ Animate an FDTD (F) with `source` for `steps` time steps.
    display the `component` field components at `num_panels` equally spaced.
    """
    F.initialize_fields()

    # initialize the plot
    f, ax_list = plt.subplots(1, num_panels, figsize=(20*num_panels,20))
    Nx, Ny, _ = F.eps_r.shape
    ax_index = 0

    # fdtd time loop
    for t_index in range(steps):
        fields = F.forward(Jz=source(t_index))

        # if it's one of the num_panels panels
        if t_index % (steps // num_panels) == 0:

            if ax_index < num_panels:   # extra safety..sometimes tries to access num_panels-th elemet of ax_list, leading to error

                print('working on axis {}/{} for time step {}'.format(ax_index, num_panels, t_index))

                # grab the axis
                ax = ax_list[ax_index]

                # plot the fields
                im_t = ax.pcolormesh(np.zeros((Nx, Ny)), cmap='RdBu')
                max_E = np.abs(fields[component]).max()
                im_t.set_array(fields[component][:, :, 0].ravel().T)
                im_t.set_clim([-max_E / 2.0, max_E / 2.0])
                ax.set_title('time = {} seconds'.format(F.dt*t_index))

                # update the axis
                ax_index += 1
    plt.show() 
Example #29
Source File: optimize_1_3.py    From ceviche with MIT License 5 votes vote down vote up
def viz_sim(epsr):
    """Solve and visualize a simulation with permittivity 'epsr'
    """
    simulation = fdfd_ez(omega, dl, epsr, [Npml, Npml])
    Hx, Hy, Ez = simulation.solve(source)
    fig, ax = plt.subplots(1, 2, constrained_layout=True, figsize=(6,3))
    ceviche.viz.real(Ez, outline=epsr, ax=ax[0], cbar=False)
    ax[0].plot(input_slice.x*np.ones(len(input_slice.y)), input_slice.y, 'g-')
    for output_slice in output_slices:
        ax[0].plot(output_slice.x*np.ones(len(output_slice.y)), output_slice.y, 'r-')
    ceviche.viz.abs(epsr, ax=ax[1], cmap='Greys');
    plt.show()
    return (simulation, ax) 
Example #30
Source File: plotting.py    From melgan with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_waveform_to_numpy(waveform):
    fig, ax = plt.subplots(figsize=(12, 3))
    ax.plot()
    ax.plot(range(len(waveform)), waveform,
            linewidth=0.1, alpha=0.7, color='blue')

    plt.xlabel("Samples")
    plt.ylabel("Amplitude")
    plt.ylim(-1, 1)
    plt.tight_layout()

    fig.canvas.draw()
    data = save_figure_to_numpy(fig)
    plt.close()
    return data