Python matplotlib.pylab.colorbar() Examples

The following are 30 code examples of matplotlib.pylab.colorbar(). 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: utils.py    From Building-Machine-Learning-Systems-With-Python-Second-Edition with MIT License 6 votes vote down vote up
def plot_confusion_matrix(cm, genre_list, name, title):
    pylab.clf()
    pylab.matshow(cm, fignum=False, cmap='Blues', vmin=0, vmax=1.0)
    ax = pylab.axes()
    ax.set_xticks(range(len(genre_list)))
    ax.set_xticklabels(genre_list)
    ax.xaxis.set_ticks_position("bottom")
    ax.set_yticks(range(len(genre_list)))
    ax.set_yticklabels(genre_list)
    pylab.title(title)
    pylab.colorbar()
    pylab.grid(False)
    pylab.show()
    pylab.xlabel('Predicted class')
    pylab.ylabel('True class')
    pylab.grid(False)
    pylab.savefig(
        os.path.join(CHART_DIR, "confusion_matrix_%s.png" % name), bbox_inches="tight") 
Example #2
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 #3
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 #4
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 #5
Source File: graph-bot.py    From discord-bots with MIT License 6 votes vote down vote up
def matrix(msg, mobj):
    """
    Interpret a user string, convert it to a list and graph it as a matrix
    Uses ast.literal_eval to parse input into a list
    """
    fname = bot_data("{}.png".format(mobj.author.id))
    try:
        list_input = literal_eval(msg)
        if not isinstance(list_input, list):
            raise ValueError("Not a list")
        m = np_matrix(list_input)
        fig = plt.figure()
        ax = fig.add_subplot(1,1,1)
        ax.set_aspect('equal')
        plt.imshow(m, interpolation='nearest', cmap=plt.cm.ocean)
        plt.colorbar()
        plt.savefig(fname)
        await client.send_file(mobj.channel, fname)
        f_remove(fname)
        return
    except Exception as ex:
        logger("!matrix: {}".format(ex))
    return await client.send_message(mobj.channel, "Failed to render graph") 
Example #6
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 #7
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 #8
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 #9
Source File: prod_basis.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def generate_png_chess_dp_vertex(self):
    """Produces pictures of the dominant product vertex a chessboard convention"""
    import matplotlib.pylab as plt
    plt.ioff()
    dab2v = self.get_dp_vertex_doubly_sparse()
    for i, ab in enumerate(dab2v): 
        fname = "chess-v-{:06d}.png".format(i)
        print('Matrix No.#{}, Size: {}, Type: {}'.format(i+1, ab.shape, type(ab)), fname)
        if type(ab) != 'numpy.ndarray': ab = ab.toarray()
        fig = plt.figure()
        ax = fig.add_subplot(1,1,1)
        ax.set_aspect('equal')
        plt.imshow(ab, interpolation='nearest', cmap=plt.cm.ocean)
        plt.colorbar()
        plt.savefig(fname)
        plt.close(fig) 
Example #10
Source File: precipfields.py    From pysteps with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _dynamic_formatting_floats(floatArray, colorscale="pysteps"):
    """
    Function to format the floats defining the class limits of the colorbar.
    """
    floatArray = np.array(floatArray, dtype=float)

    labels = []
    for label in floatArray:
        if label >= 0.1 and label < 1:
            if colorscale == "pysteps":
                formatting = ",.2f"
            else:
                formatting = ",.1f"
        elif label >= 0.01 and label < 0.1:
            formatting = ",.2f"
        elif label >= 0.001 and label < 0.01:
            formatting = ",.3f"
        elif label >= 0.0001 and label < 0.001:
            formatting = ",.4f"
        elif label >= 1 and label.is_integer():
            formatting = "i"
        else:
            formatting = ",.1f"

        if formatting != "i":
            labels.append(format(label, formatting))
        else:
            labels.append(str(int(label)))

    return labels 
Example #11
Source File: plotting_utils.py    From fac-via-ppg with Apache License 2.0 5 votes vote down vote up
def plot_ppg_to_numpy(ppg):
    fig, ax = plt.subplots(figsize=(12, 3))
    im = ax.imshow(ppg, aspect="auto", origin="lower",
                   interpolation='none')
    plt.colorbar(im, ax=ax)
    plt.xlabel("Phonemes")
    plt.ylabel("Time")
    plt.tight_layout()

    fig.canvas.draw()
    data = save_figure_to_numpy(fig)
    plt.close()
    return data 
Example #12
Source File: plotting_utils.py    From fac-via-ppg 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 #13
Source File: audio.py    From Self-Supervised-Speech-Pretraining-and-Representation-Learning with MIT License 5 votes vote down vote up
def plot_spectrogram(spec, path):
    spec = spec.transpose(1, 0) # (seq_len, feature_dim) -> (feature_dim, seq_len)
    plt.gcf().clear()
    plt.figure(figsize=(12, 3))
    plt.imshow(spec, aspect="auto", origin="lower")
    plt.colorbar()
    plt.tight_layout()
    plt.savefig(path, dpi=300, format="png")
    plt.close() 


####################
# PLOT EMBEDDING #
#################### 
Example #14
Source File: device_saver.py    From angler with MIT License 5 votes vote down vote up
def _calc_trans_ortho(self):
        # input power
        self.W_in = self.simulation.W_in
        print("        -> W_in = {}".format(self.W_in))

        # linear powers
        self.W_right_lin = self.simulation.flux_probe('x', [-self.NPML[0]-int(self.l/2/self.dl), self.ny], int(self.H/2/self.dl))
        self.W_top_lin  = self.simulation.flux_probe('y', [self.nx, -self.NPML[1]-int(self.l/2/self.dl)], int(self.H/2/self.dl))

        # nonlinear powers
        self.W_right_nl = self.simulation.flux_probe('x', [-self.NPML[0]-int(self.l/2/self.dl), self.ny], int(self.H/2/self.dl), nl=True)
        self.W_top_nl  = self.simulation.flux_probe('y', [self.nx, -self.NPML[1]-int(self.l/2/self.dl)], int(self.H/2/self.dl), nl=True)


        print('        -> linear transmission (right)      = {:.4f}'.format(self.W_right_lin / self.W_in))
        print('        -> linear transmission (top)        = {:.4f}'.format(self.W_top_lin / self.W_in))
        print('        -> nonlinear transmission (right)   = {:.4f}'.format(self.W_right_nl / self.W_in))
        print('        -> nonlinear transmission (top)     = {:.4f}'.format(self.W_top_nl / self.W_in))

        self.S = [[self.W_top_lin / self.W_in, self.W_right_lin / self.W_in],
                  [self.W_top_nl / self.W_in,  self.W_right_nl / self.W_in]]

        plt.imshow(self.S, cmap='magma')
        plt.colorbar()
        plt.title('power matrix')
        plt.show() 
Example #15
Source File: audio.py    From Self-Supervised-Speech-Pretraining-and-Representation-Learning with MIT License 5 votes vote down vote up
def plot_embedding(spec, path):
    spec = spec.transpose(1, 0) # (seq_len, feature_dim) -> (feature_dim, seq_len)
    plt.gcf().clear()
    plt.figure(figsize=(12, 3))
    plt.pcolormesh(spec, norm=SymLogNorm(linthresh=1e-3))
    plt.colorbar()
    plt.tight_layout()
    plt.savefig(path, dpi=300, format="png")
    plt.close() 
Example #16
Source File: device_saver.py    From angler with MIT License 5 votes vote down vote up
def _calc_trans_three(self):
        # input power
        self.W_in = self.simulation.W_in
        print("        -> W_in = {}".format(self.W_in))

        # linear powers
        self.W_top_lin = self.simulation.flux_probe('x', [-self.NPML[0]-int(self.l/2/self.dl), self.ny+int(self.d/2/self.dl)], int(self.H/2/self.dl))
        self.W_bot_lin = self.simulation.flux_probe('x', [-self.NPML[0]-int(self.l/2/self.dl), self.ny-int(self.d/2/self.dl)], int(self.H/2/self.dl))

        # nonlinear powers
        self.W_top_nl = self.simulation.flux_probe('x', [-self.NPML[0]-int(self.l/2/self.dl), self.ny+int(self.d/2/self.dl)], int(self.H/2/self.dl), nl=True)
        self.W_bot_nl = self.simulation.flux_probe('x', [-self.NPML[0]-int(self.l/2/self.dl), self.ny-int(self.d/2/self.dl)], int(self.H/2/self.dl), nl=True)


        print('        -> linear transmission (top)        = {:.4f}'.format(self.W_top_lin / self.W_in))
        print('        -> linear transmission (bottom)     = {:.4f}'.format(self.W_bot_lin / self.W_in))
        print('        -> nonlinear transmission (top)     = {:.4f}'.format(self.W_top_nl / self.W_in))
        print('        -> nonlinear transmission (bottom)  = {:.4f}'.format(self.W_bot_nl / self.W_in))

        self.S = [[self.W_top_lin / self.W_in, self.W_top_nl / self.W_in],
                  [self.W_bot_lin / self.W_in, self.W_bot_nl / self.W_in]]

        plt.imshow(self.S, cmap='magma')
        plt.colorbar()
        plt.title('power matrix')
        plt.show() 
Example #17
Source File: filter.py    From angler with MIT License 5 votes vote down vote up
def colorbar(mappable):
        ax = mappable.axes
        fig = ax.figure
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", size="5%", pad=0.05)
        return fig.colorbar(mappable, cax=cax) 
Example #18
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 #19
Source File: model_background.py    From dials with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _save_plot(
        self, name, filename, extractor_fn, bounded=True, colorbar=True, vmax=None
    ):
        """
        Save the image
        """
        from matplotlib import pylab

        for i, model in enumerate(self.model):
            image = extractor_fn(model)
            pylab.figure(figsize=(6, 4))
            if bounded and vmax is None:
                boundaries = {
                    "vmin": 0,
                    "vmax": sorted(list(image))[int(0.99 * len(image))],
                }
            elif bounded:
                boundaries = {"vmin": 0, "vmax": vmax}
            else:
                boundaries = {}
            pylab.imshow(image.as_numpy_array(), interpolation="none", **boundaries)
            ax1 = pylab.gca()
            ax1.get_xaxis().set_visible(False)
            ax1.get_yaxis().set_visible(False)
            if colorbar:
                cb = pylab.colorbar()
                cb.ax.tick_params(labelsize=8)
            logger.info(
                "Saving %s image for panel %d to %s_%d.png" % (name, i, filename, i)
            )
            pylab.savefig("%s_%d.png" % (filename, i), dpi=600, bbox_inches="tight") 
Example #20
Source File: model_background.py    From dials with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def save_mask(self, filename):
        """
        Save the dispersion image
        """
        self._save_plot(
            "mask", filename, lambda m: m.mask, bounded=False, colorbar=False
        ) 
Example #21
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 #22
Source File: utils.py    From cnn_vocoder 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

# from https://github.com/NVIDIA/vid2vid/blob/951a52bb38c2aa227533b3731b73f40cbd3843c4/models/networks.py#L17 
Example #23
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 #24
Source File: comparison_smooth_xor.py    From widedeepnetworks with Apache License 2.0 5 votes vote down vote up
def plot_smooth_xor_data_2d(ax):
    ngrid = 1000
    xA = get_base_grid(ngrid)
    xB = get_base_grid(ngrid)
    
    #xAv, yBv = np.meshgrid(xA, xB)
    
    xComb = np.array( [elem for elem in itertools.product(xA, xB)] )
    y = smooth_xor(xComb)
    
    mappable = ax.imshow(-y.reshape(ngrid,ngrid), extent = [-3.,3.,-3.,3.])
    plt.colorbar(mappable)

    
    x,not_used = make_smooth_xor_data() 
    ax.scatter(x[:,0],x[:,1], color='r', marker='+')    
    
    testA,testB, not_used = get_test_points()
    ax.plot(testA[:250],testB[:250], 'k--')
    ax.plot(testA[250:],testB[250:], 'k--')
    ax.text(-2.8,0.75,'Cross-section 1', fontsize=12)
    ax.text(-2.25,-2.5,'Cross-section 2', fontsize=12)
    
    
    #zv = y.reshape(xA.shape[0],xB.shape[0])
    
    #fig = plt.figure()
    #ax = fig.add_subplot(111, projection='3d')
    #ax.plot_wireframe(xAv, yBv, zv) 
Example #25
Source File: comparison_smooth_xor.py    From widedeepnetworks with Apache License 2.0 5 votes vote down vote up
def reshape_and_plot(fig, ax, input_array, vmin, vmax, colorbar=True ):
    assert( (input_array>=vmin).all() )
    assert( (input_array<=vmax).all() )
    reshaped_array = np.reshape( input_array, (defaults.points_per_dim,defaults.points_per_dim) ) 
    im = ax.imshow( reshaped_array, extent = [defaults.upper_lim,defaults.lower_lim,defaults.upper_lim,defaults.lower_lim], vmin=vmin, vmax=vmax )
    if colorbar:
        fig.colorbar( im, ax= ax)
    return im 
Example #26
Source File: plotting_utils.py    From nonparaSeq2seqVC_code with MIT License 5 votes vote down vote up
def plot_alignment(alignment, fn):
    # [4, encoder_step, decoder_step] 
    fig, axes = plt.subplots(2, 2)
    for i in range(2):
        for j in range(2):
            g = axes[i][j].imshow(alignment[i*2+j,:,:].T,
                aspect='auto', origin='lower',
                interpolation='none')
            plt.colorbar(g, ax=axes[i][j])
    
    plt.savefig(fn)
    plt.close()
    return fn 
Example #27
Source File: plotting_utils.py    From nonparaSeq2seqVC_code 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 #28
Source File: inference_utils.py    From nonparaSeq2seqVC_code with MIT License 5 votes vote down vote up
def plot_data(data, fn, figsize=(12, 4)):
    fig, axes = plt.subplots(1, len(data), figsize=figsize)
    for i in range(len(data)):
        if len(data) == 1:
            ax = axes
        else:
            ax = axes[i]
        g = ax.imshow(data[i], aspect='auto', origin='bottom', 
                       interpolation='none')
        plt.colorbar(g, ax=ax)
    plt.savefig(fn) 
Example #29
Source File: plotting_utils.py    From nonparaSeq2seqVC_code 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 #30
Source File: plotting_utils.py    From nonparaSeq2seqVC_code with MIT License 5 votes vote down vote up
def plot_alignment(alignment, fn):
    # [4, encoder_step, decoder_step] 
    fig, axes = plt.subplots(1, 2)

    for j in range(2):
        g = axes[j].imshow(alignment[j,:,:].T,
            aspect='auto', origin='lower',
            interpolation='none')
        plt.colorbar(g, ax=axes[j])
    
    plt.savefig(fn)
    plt.close()
    return fn