Python matplotlib.pyplot.colorbar() Examples

The following are code examples for showing how to use matplotlib.pyplot.colorbar(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: aftershoq   Author: mfranckie   File: ndtestfunc.py    GNU Lesser General Public License v3.0 7 votes vote down vote up
def plt(self, x = None, y = None, cmin= None, cmax=None, cmap = 'hot'):

        if x is None:
            x = np.linspace(0,1)
        if y is None and self.ND > 1:
            y = np.linspace(0,1)

        z = []

        if self.ND > 1:
            coord = []
            for i in range(self.ND):
                coord.append(0.)
            for xx in x:
                row = []
                coord[1] = xx
                for yy in y:
                    coord[0] = yy
                    row.append(self.testfunc(coord))
                z.append(row)

        #pl.contour(x,y,z)
        pl.pcolormesh(x,y,z,vmin=cmin, vmax=cmax, cmap=cmap)
        cbar = pl.colorbar()
        return cbar 
Example 2
Project: neurips19-graph-protein-design   Author: jingraham   File: seq_only_train.py    MIT License 6 votes vote down vote up
def _plot_log_probs(log_probs, total_step):
    alphabet = 'ACDEFGHIKLMNPQRSTVWY'
    reorder = 'DEKRHQNSTPGAVILMCFWY'
    permute_ix = np.array([alphabet.index(c) for c in reorder])
    plt.close()
    fig = plt.figure(figsize=(8,3))
    ax = fig.add_subplot(111)
    P = np.exp(log_probs.cpu().data.numpy())[0].T
    plt.imshow(P[permute_ix])
    plt.clim(0,1)
    plt.colorbar()
    plt.yticks(np.arange(20), [a for a in reorder])
    ax.tick_params(
        axis=u'both', which=u'both',length=0, labelsize=5
    )
    plt.tight_layout()
    plt.savefig(base_folder + 'probs{}.pdf'.format(total_step))
    return 
Example 3
Project: neurips19-graph-protein-design   Author: jingraham   File: test_redesign.py    MIT License 6 votes vote down vote up
def _plot_log_probs(log_probs, total_step):
    alphabet = 'ACDEFGHIKLMNPQRSTVWY'
    reorder = 'DEKRHQNSTPGAVILMCFWY'
    permute_ix = np.array([alphabet.index(c) for c in reorder])
    plt.close()
    fig = plt.figure(figsize=(8,3))
    ax = fig.add_subplot(111)
    P = np.exp(log_probs.cpu().data.numpy())[0].T
    plt.imshow(P[permute_ix])
    plt.clim(0,1)
    plt.colorbar()
    plt.yticks(np.arange(20), [a for a in reorder])
    ax.tick_params(axis=u'both', which=u'both',length=0, labelsize=5)
    plt.tight_layout()
    plt.savefig(base_folder + 'probs{}.pdf'.format(total_step))
    return 
Example 4
Project: neurips19-graph-protein-design   Author: jingraham   File: utils.py    MIT License 6 votes vote down vote up
def plot_log_probs(log_probs, total_step, folder=''):
    alphabet = 'ACDEFGHIKLMNPQRSTVWY'
    reorder = 'DEKRHQNSTPGAVILMCFWY'
    permute_ix = np.array([alphabet.index(c) for c in reorder])
    plt.close()
    fig = plt.figure(figsize=(8,3))
    ax = fig.add_subplot(111)
    P = np.exp(log_probs.cpu().data.numpy())[0].T
    plt.imshow(P[permute_ix])
    plt.clim(0,1)
    plt.colorbar()
    plt.yticks(np.arange(20), [a for a in reorder])
    ax.tick_params(
        axis=u'both', which=u'both',length=0, labelsize=5
    )
    plt.tight_layout()
    plt.savefig(folder + 'probs{}.pdf'.format(total_step))
    return 
Example 5
Project: neurips19-graph-protein-design   Author: jingraham   File: seq_only_test.py    MIT License 6 votes vote down vote up
def _plot_log_probs(log_probs, total_step):
    alphabet = 'ACDEFGHIKLMNPQRSTVWY'
    reorder = 'DEKRHQNSTPGAVILMCFWY'
    permute_ix = np.array([alphabet.index(c) for c in reorder])
    plt.close()
    fig = plt.figure(figsize=(8,3))
    ax = fig.add_subplot(111)
    P = np.exp(log_probs.cpu().data.numpy())[0].T
    plt.imshow(P[permute_ix])
    plt.clim(0,1)
    plt.colorbar()
    plt.yticks(np.arange(20), [a for a in reorder])
    ax.tick_params(
        axis=u'both', which=u'both',length=0, labelsize=5
    )
    plt.tight_layout()
    plt.savefig(base_folder + 'probs{}.pdf'.format(total_step))
    return 
Example 6
Project: matplotlib_utilities   Author: dmccloskey   File: matplot.py    MIT License 6 votes vote down vote up
def heatPlot(self,title_I):
        #TODO:
        # Generate some test data
        x = np.random.randn(8873)
        y = np.random.randn(8873)

        heatmap, xedges, yedges = np.histogram2d(x, y, bins=(50,50))
        extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]

        cb = plt.colorbar()
        cb.set_label('mean value')

        plt.clf()
        #plt.imshow(heatmap, extent=extent) #inverts the image
        plt.imshow(heatmap.T, extent=extent, origin = 'lower')
        plt.show() 
Example 7
Project: cube_browser   Author: SciTools   File: __init__.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def legend(self, mappable):

        fig = plt.gcf()
        posn = self.axes.get_position()
        extent = self.axes.get_extent()
        aspect = (extent[1] - extent[0]) / (extent[3] - extent[2])

        self.cb_depth = 0.02
        self.cb_sep = 0.01
        if aspect < 1.2:
            self.cbar_ax = fig.add_axes([posn.x1 + self.cb_sep, posn.y0,
                                         self.cb_depth, posn.height])
            plt.colorbar(mappable, ax=self.axes, orientation='vertical',
                         cax=self.cbar_ax)

        else:
            self.cbar_ax = fig.add_axes([posn.x0, posn.y0 - 6*self.cb_sep,
                                         posn.width, 2*self.cb_depth])
            plt.colorbar(mappable, ax=self.axes, orientation='horizontal',
                         cax=self.cbar_ax)

        fig.canvas.mpl_connect('resize_event', self.resize_colourbar)
        self.resize_colourbar(None) 
Example 8
Project: zeus   Author: lucasvarela   File: song.py    MIT License 6 votes vote down vote up
def plot_melspectrogram(self):
        """Plots the melspectrogram."""

        # Mel-scaled power (energy-squared) spectrogram
        S = librosa.feature.melspectrogram(self.y, sr=self.sr, n_mels=128)

        # Convert to log scale (dB). We'll use the peak power (max) as reference.
        log_S = librosa.power_to_db(S, ref=np.max)

        # Make a new figure
        plt.figure(figsize=(12,4))

        # Display the spectrogram on a mel scale
        # sample rate and hop length parameters are used to render the time axis
        librosa.display.specshow(log_S, sr=self.sr, x_axis='time', y_axis='mel')

        # Plot params
        plt.colorbar(format='%+02.0f dB')
        plt.title('mel power spectrogram')
        plt.tight_layout()
        plt.show() 
Example 9
Project: zeus   Author: lucasvarela   File: song.py    MIT License 6 votes vote down vote up
def plot_beattracking(self):
        """Plots the song's beat."""

        S = librosa.feature.melspectrogram(self.y, sr=self.sr, n_mels=128)
        log_S = librosa.power_to_db(S, ref=np.max)

        # We'll use the percussive component for this part
        tempo, beats = librosa.beat.beat_track(y=self.y_percussive, sr=self.sr)

        # Let's re-draw the spectrogram, but this time, overlay the detected beats
        plt.figure(figsize=(12,4))
        librosa.display.specshow(log_S, sr=self.sr, x_axis='time', y_axis='mel')

        # Let's draw transparent lines over the beat frames
        plt.vlines(librosa.frames_to_time(beats),
                1, 0.5 * self.sr,
                colors='w', linestyles='-', linewidth=2, alpha=0.5)

        plt.axis('tight')
        plt.colorbar(format='%+02.0f dB')
        plt.tight_layout()
        plt.show() 
Example 10
Project: reinforcement-learning-exercises   Author: NickCellino   File: car_rentals.py    MIT License 6 votes vote down vote up
def plot_policies(self, policies, starting_fig=1):
        figure = starting_fig
        for i in range(len(policies)):
            fig = plt.figure(figure)
            figure += 1
            policy = policies[i]
            plt.imshow(policy, cmap='jet')
            plt.ylabel('# of Cars at Dealership A')
            plt.xlabel('# of Cars at Dealership B')
            plt.xticks(np.arange(0, policy.shape[0], 1))
            plt.yticks(np.arange(0, policy.shape[1], 1))
            plt.gca().invert_yaxis()
            if i == (len(policies) - 1):
                fig.suptitle('Optimal Policy')
            else:
                fig.suptitle(f'Policy {i}')

            # Annotate states
            for i in range(policy.shape[0]):
                for j in range(policy.shape[1]):
                    plt.text(j, i, '%d' % policy[i,j], horizontalalignment='center', verticalalignment='center')

            plt.colorbar() 
Example 11
Project: Attention-Gated-Networks   Author: ozan-oktay   File: visualise_att_maps_epoch.py    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 12
Project: Attention-Gated-Networks   Author: ozan-oktay   File: visualise_fmaps.py    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 13
Project: Attention-Gated-Networks   Author: ozan-oktay   File: visualise_attention.py    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 14
Project: Attention-Gated-Networks   Author: ozan-oktay   File: visualise_attention.py    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 15
Project: prickle   Author: cswaney   File: core.py    MIT License 6 votes vote down vote up
def imshow(data, which, levels):
    """
        Display order book data as an image, where order book data is either of
        `df_price` or `df_volume` returned by `load_hdf5` or `load_postgres`.
    """

    if which == 'prices':
        idx = ['askprc.' + str(i) for i in range(levels, 0, -1)]
        idx.extend(['bidprc.' + str(i) for i in range(1, levels + 1, 1)])
    elif which == 'volumes':
        idx = ['askvol.' + str(i) for i in range(levels, 0, -1)]
        idx.extend(['bidvol.' + str(i) for i in range(1, levels + 1, 1)])
    plt.imshow(data.loc[:, idx].T, interpolation='nearest', aspect='auto')
    plt.yticks(range(0, levels * 2, 1), idx)
    plt.colorbar()
    plt.tight_layout()
    plt.show() 
Example 16
Project: sleep-convolutions-tf   Author: cliffordlab   File: crossval.py    MIT License 6 votes vote down vote up
def plot_accuracy(cm, classes, cmap=plotting.colorscheme['accuracy'],
            normalize=False, colorbar=True, fontsize=12, vmin=None, vmax=None):
        tick_marks = np.arange(len(classes))
        if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, None]
        ax = plt.imshow(cm, interpolation='nearest', cmap=cmap, vmin=vmin,
                vmax=vmax)
        if colorbar: plt.colorbar()
        plt.xticks(tick_marks, classes, rotation=30, fontsize=fontsize)
        plt.yticks(tick_marks, classes, fontsize=fontsize)
        fmt = '.2f' if normalize else 'd'
        thresh = cm.max() / 2.
        for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
            plt.text(j, i, '{}%'.format(int(100.0*cm[i, j])),
                     ha="center", va='center', fontsize=fontsize,
                     color="white" if cm[i, j] > thresh else "black")
        plt.ylabel('True class', fontsize=fontsize)
        plt.xlabel('Predicted class', fontsize=fontsize)
        return ax 
Example 17
Project: imRICnn   Author: johanna-rock   File: plotting.py    The Unlicense 6 votes vote down vote up
def plot_rd_map(fft2, title, filename, is_log_mag=False):

    num_ramps = fft2.shape[1]

    v_vec_DFT_2 = v_vec_fft2(num_ramps)

    if not is_log_mag:
        fft2 = fft2 / np.amax(np.abs(fft2))
        fft2 = 10 * np.log10(np.abs(fft2))

    fig, ax = plt.subplots(1, 1, figsize=FIG_SIZE_SINGLE)
    fig.suptitle(title)
    imgplot = plt.imshow(fft2, extent=[v_vec_DFT_2[0], v_vec_DFT_2[-1], 0, d_max], origin='lower', vmin=color_scale_min, vmax=color_scale_max)
    ax.ticklabel_format(useOffset=False, style='plain')
    ax.set_aspect((v_vec_DFT_2[-1] - v_vec_DFT_2[0]) / d_max)
    plt.xlabel('velocity [m/s]')
    plt.ylabel('distance [m]')
    imgplot.set_cmap(STD_CMAP)
    plt.colorbar()
    save_or_show_plot(filename) 
Example 18
Project: imRICnn   Author: johanna-rock   File: plotting.py    The Unlicense 6 votes vote down vote up
def plot_aoa_noise_mask(noise_mask, title, filename):
    x_vec, y_vec = basis_vec_fft3()

    fig = plt.figure(figsize=FIG_SIZE)
    ax = fig.gca(projection='3d')

    fig.suptitle(title)
    surf = ax.plot_surface(x_vec, y_vec, noise_mask.astype(int), cmap=STD_CMAP, linewidth=0, vmin=0, vmax=1, rstride=1, cstride=1)

    plt.xlabel('cross range [m]')
    plt.ylabel('range [m]')
    fig.colorbar(surf, shrink=0.5, aspect=5)

    ax.view_init(87.5, -90)
    plt.draw()

    save_or_show_plot(filename) 
Example 19
Project: imRICnn   Author: johanna-rock   File: plotting.py    The Unlicense 6 votes vote down vote up
def plot_angle_of_arrival_map(fft3, title, filename):
    x_vec, y_vec = basis_vec_fft3()
    fft3_plot = 10 * np.log10(np.abs(fft3 / np.amax(np.abs(fft3))))

    fig = plt.figure(figsize=FIG_SIZE)
    ax = fig.gca(projection='3d')
    fig.suptitle(title)
    surf = ax.plot_surface(x_vec, y_vec, fft3_plot, cmap=STD_CMAP, linewidth=0, vmin=color_scale_min, vmax=color_scale_max, rstride=1, cstride=1)

    plt.xlabel('cross range [m]')
    plt.ylabel('range [m]')
    fig.colorbar(surf, shrink=0.5, aspect=5)

    ax.view_init(87.5, -90)
    plt.draw()

    save_or_show_plot(filename) 
Example 20
Project: reconstruction   Author: microelly2   File: elevationgrid.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def showHeightMap(x,y,z,zi):
	''' show height map in maptplotlib '''
	zi=zi.transpose()

	plt.imshow(zi, vmin=z.min(), vmax=z.max(), origin='lower',
			   extent=[ y.min(), y.max(),x.min(), x.max()])

	plt.colorbar()

	CS = plt.contour(zi,15,linewidths=0.5,colors='k',
			   extent=[ y.min(), y.max(),x.min(), x.max()])
	CS = plt.contourf(zi,15,cmap=plt.cm.rainbow, 
			   extent=[ y.min(), y.max(),x.min(), x.max()])

	z=z.transpose()
	plt.scatter(y, x, c=z)

	# achsen umkehren
	#plt.gca().invert_xaxis()
	#plt.gca().invert_yaxis()

	plt.show()
	return 
Example 21
Project: tectosaur   Author: tbenthompson   File: okada.py    MIT License 6 votes vote down vote up
def plot_interior_displacement(self, soln):
        nxy = 40
        nz = 40
        d = 0
        xs = np.linspace(-10, 10, nxy)
        zs = np.linspace(-0.1, -4.0, nz)
        X, Y, Z = np.meshgrid(xs, xs, zs)
        obs_pts = np.array([X.flatten(), Y.flatten(), Z.flatten()]).T.copy()
        t = Timer(output_fnc = logger.debug)
        interior_disp = -interior_integral(
            obs_pts, obs_pts, self.all_mesh, soln, 'elasticT3',
            3, 8, self.k_params, self.float_type,
            fmm_params = None#[100, 3.0, 3000, 25]
        ).reshape((nxy, nxy, nz, 3))
        t.report('eval %.2E interior pts' % obs_pts.shape[0])

        for i in range(nz):
            plt.figure()
            plt.pcolor(xs, xs, interior_disp[:,:,i,d])
            plt.colorbar()
            plt.title('at z = ' + ('%.3f' % zs[i]) + '    u' + ['x', 'y', 'z'][d])
            plt.show() 
Example 22
Project: fbpconv_tf   Author: panakino   File: util.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_prediction(x_test, y_test, prediction, save=False):
    import matplotlib
    import matplotlib.pyplot as plt
    
    test_size = x_test.shape[0]
    fig, ax = plt.subplots(test_size, 3, figsize=(12,12), sharey=True, sharex=True)
    
    x_test = crop_to_shape(x_test, prediction.shape)
    y_test = crop_to_shape(y_test, prediction.shape)
    
    ax = np.atleast_2d(ax)
    for i in range(test_size):
        cax = ax[i, 0].imshow(x_test[i])
        plt.colorbar(cax, ax=ax[i,0])
        cax = ax[i, 1].imshow(y_test[i, ..., 1])
        plt.colorbar(cax, ax=ax[i,1])
        pred = prediction[i, ..., 1]
        pred -= np.amin(pred)
        pred /= np.amax(pred)
        cax = ax[i, 2].imshow(pred)
        plt.colorbar(cax, ax=ax[i,2])
        if i==0:
            ax[i, 0].set_title("x")
            ax[i, 1].set_title("y")
            ax[i, 2].set_title("pred")
    fig.tight_layout()
    
    if save:
        fig.savefig(save)
    else:
        fig.show()
        plt.show() 
Example 23
Project: nmp_qc   Author: priba   File: Plotter.py    MIT License 5 votes vote down vote up
def plot_graph(self, am, position=None, cls=None, fig_name='graph.png'):

        with warnings.catch_warnings():
            warnings.filterwarnings("ignore")

            g = nx.from_numpy_matrix(am)

            if position is None:
                position=nx.drawing.circular_layout(g)

            fig = plt.figure()

            if cls is None:
                cls='r'
            else:
                # Make a user-defined colormap.
                cm1 = mcol.LinearSegmentedColormap.from_list("MyCmapName", ["r", "b"])

                # Make a normalizer that will map the time values from
                # [start_time,end_time+1] -> [0,1].
                cnorm = mcol.Normalize(vmin=0, vmax=1)

                # Turn these into an object that can be used to map time values to colors and
                # can be passed to plt.colorbar().
                cpick = cm.ScalarMappable(norm=cnorm, cmap=cm1)
                cpick.set_array([])
                cls = cpick.to_rgba(cls)
                plt.colorbar(cpick, ax=fig.add_subplot(111))


            nx.draw(g, pos=position, node_color=cls, ax=fig.add_subplot(111))

            fig.savefig(os.path.join(self.plotdir, fig_name)) 
Example 24
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: bdk_demo.py    Apache License 2.0 5 votes vote down vote up
def run_synthetic_SGLD():
    theta1 = 0
    theta2 = 1
    sigma1 = numpy.sqrt(10)
    sigma2 = 1
    sigmax = numpy.sqrt(2)
    X = load_synthetic(theta1=theta1, theta2=theta2, sigmax=sigmax, num=100)
    minibatch_size = 1
    total_iter_num = 1000000
    lr_scheduler = SGLDScheduler(begin_rate=0.01, end_rate=0.0001, total_iter_num=total_iter_num,
                                 factor=0.55)
    optimizer = mx.optimizer.create('sgld',
                                    learning_rate=None,
                                    rescale_grad=1.0,
                                    lr_scheduler=lr_scheduler,
                                    wd=0)
    updater = mx.optimizer.get_updater(optimizer)
    theta = mx.random.normal(0, 1, (2,), mx.cpu())
    grad = nd.empty((2,), mx.cpu())
    samples = numpy.zeros((2, total_iter_num))
    start = time.time()
    for i in xrange(total_iter_num):
        if (i + 1) % 100000 == 0:
            end = time.time()
            print("Iter:%d, Time spent: %f" % (i + 1, end - start))
            start = time.time()
        ind = numpy.random.randint(0, X.shape[0])
        synthetic_grad(X[ind], theta, sigma1, sigma2, sigmax, rescale_grad=
        X.shape[0] / float(minibatch_size), grad=grad)
        updater('theta', grad, theta)
        samples[:, i] = theta.asnumpy()
    plt.hist2d(samples[0, :], samples[1, :], (200, 200), cmap=plt.cm.jet)
    plt.colorbar()
    plt.show() 
Example 25
Project: DOTA_models   Author: ringringyi   File: plot_lfads.py    Apache License 2.0 5 votes vote down vote up
def _plot_item(W, name, full_name, nspaces):
  plt.figure()
  if W.shape == ():
    print(name, ": ", W)
  elif W.shape[0] == 1:
    plt.stem(W.T)
    plt.title(full_name)
  elif W.shape[1] == 1:
    plt.stem(W)
    plt.title(full_name)
  else:
    plt.imshow(np.abs(W), interpolation='nearest', cmap='jet');
    plt.colorbar()
    plt.title(full_name) 
Example 26
Project: DOTA_models   Author: ringringyi   File: plot_lfads.py    Apache License 2.0 5 votes vote down vote up
def plot_priors():
  g0s_prior_mean_bxn = train_modelvals['prior_g0_mean']
  g0s_prior_var_bxn = train_modelvals['prior_g0_var']
  g0s_post_mean_bxn = train_modelvals['posterior_g0_mean']
  g0s_post_var_bxn = train_modelvals['posterior_g0_var']

  plt.figure(figsize=(10,4), tight_layout=True);
  plt.subplot(1,2,1)
  plt.hist(g0s_post_mean_bxn.flatten(), bins=20, color='b');
  plt.hist(g0s_prior_mean_bxn.flatten(), bins=20, color='g');

  plt.title('Histogram of Prior/Posterior Mean Values')
  plt.subplot(1,2,2)
  plt.hist((g0s_post_var_bxn.flatten()), bins=20, color='b');
  plt.hist((g0s_prior_var_bxn.flatten()), bins=20, color='g');
  plt.title('Histogram of Prior/Posterior Log Variance Values')

  plt.figure(figsize=(10,10), tight_layout=True)
  plt.subplot(2,2,1)
  plt.imshow(g0s_prior_mean_bxn.T, interpolation='nearest', cmap='jet')
  plt.colorbar(fraction=0.025, pad=0.04)
  plt.title('Prior g0 means')

  plt.subplot(2,2,2)
  plt.imshow(g0s_post_mean_bxn.T, interpolation='nearest', cmap='jet')
  plt.colorbar(fraction=0.025, pad=0.04)
  plt.title('Posterior g0 means');

  plt.subplot(2,2,3)
  plt.imshow(g0s_prior_var_bxn.T, interpolation='nearest', cmap='jet')
  plt.colorbar(fraction=0.025, pad=0.04)
  plt.title('Prior g0 variance Values')

  plt.subplot(2,2,4)
  plt.imshow(g0s_post_var_bxn.T, interpolation='nearest', cmap='jet')
  plt.colorbar(fraction=0.025, pad=0.04)
  plt.title('Posterior g0 variance Values')

  plt.figure(figsize=(10,5))
  plt.stem(np.sort(np.log(g0s_post_mean_bxn.std(axis=0))));
  plt.title('Log standard deviation of h0 means'); 
Example 27
Project: smach_based_introspection_framework   Author: birlrobotics   File: collect_classification_statistics.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_confusion_matrix(cm, classes,
                          normalize=False,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues):
    """
    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    """
    try:
        if normalize:
            cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
            print("Normalized confusion matrix")
        else:
            print('Confusion matrix, without normalization')
    except FloatingPointError:
        print ('Error occurred: invalid value encountered in divide')
        sys.exit()
    
    print(cm)

    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)

    fmt = '.2f' if normalize else 'd'
    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, format(cm[i, j], fmt),
                 horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black")

    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label') 
Example 28
Project: ANN   Author: waynezv   File: ANN_large_v23.py    MIT License 5 votes vote down vote up
def nice_show(fig, data, vmin=None, vmax=None, cmap=None):
    '''
    data is 3D (nCH, nCol, nRow)
    '''
    assert data.ndim==3, 'Data dimension must be 3!'
    if cmap is None:
        cmap = cm.jet
    if vmin is None:
        vmin = data.min()
    if vmax is None:
        vmax = data.max()
    nCH,_,_= data.shape
    nr = int(np.ceil(np.sqrt(nCH)))
    assert nr<=10, 'Too many data channels (>10)!'
    grid = ImageGrid(fig, 111, \
            nrows_ncols=(nr, nr),\
            axes_pad=0.1,\
            add_all=True,\
            label_mode='L')
    for i in range(nCH):
        ax = grid[i]
        im = ax.imshow(data[i,:,:], vmin=vmin, vmax=vmax, \
                interpolation='nearest', cmap=cmap)
#    div = make_axes_locatable(ax)
#    cax = div.append_axes('right', size='5%', pad=0.05) # colorbar axis to the right
#    plt.colorbar(im, cax=cax) 
Example 29
Project: ANN   Author: waynezv   File: ANN_large_v22.py    MIT License 5 votes vote down vote up
def nice_show(fig, data, vmin=None, vmax=None, cmap=None):
    '''
    data is 3D (nCH, nCol, nRow)
    '''
    assert data.ndim==3, 'Data dimension must be 3!'
    if cmap is None:
        cmap = cm.jet
    if vmin is None:
        vmin = data.min()
    if vmax is None:
        vmax = data.max()
    nCH,_,_= data.shape
    nr = int(np.ceil(np.sqrt(nCH)))
    assert nr<=10, 'Too many data channels (>10)!'
    grid = ImageGrid(fig, 111, \
            nrows_ncols=(nr, nr),\
            axes_pad=0.1,\
            add_all=True,\
            label_mode='L')
    for i in range(nCH):
        ax = grid[i]
        im = ax.imshow(data[i,:,:], vmin=vmin, vmax=vmax, \
                interpolation='nearest', cmap=cmap)
#    div = make_axes_locatable(ax)
#    cax = div.append_axes('right', size='5%', pad=0.05) # colorbar axis to the right
#    plt.colorbar(im, cax=cax) 
Example 30
Project: ANN   Author: waynezv   File: ANN_large_v3.py    MIT License 5 votes vote down vote up
def nice_show(fig, data, vmin=None, vmax=None, cmap=None):
    '''
    data is 3D (nCH, nCol, nRow)
    '''
    assert data.ndim==3, 'Data dimension must be 3!'
    if cmap is None:
        cmap = cm.jet
    if vmin is None:
        vmin = data.min()
    if vmax is None:
        vmax = data.max()
    nCH,_,_= data.shape
    nr = int(np.ceil(np.sqrt(nCH)))
    assert nr<=10, 'Too many data channels (>10)!'
    grid = ImageGrid(fig, 111, \
            nrows_ncols=(nr, nr),\
            axes_pad=0.1,\
            add_all=True,\
            label_mode='L')
    for i in range(nCH):
        ax = grid[i]
        im = ax.imshow(data[i,:,:], vmin=vmin, vmax=vmax, \
                interpolation='nearest', cmap=cmap)
#    div = make_axes_locatable(ax)
#    cax = div.append_axes('right', size='5%', pad=0.05) # colorbar axis to the right
#    plt.colorbar(im, cax=cax) 
Example 31
Project: ANN   Author: waynezv   File: ANN_large_v24.py    MIT License 5 votes vote down vote up
def nice_show(fig, data, vmin=None, vmax=None, cmap=None):
    '''
    data is 3D (nCH, nCol, nRow)
    '''
    assert data.ndim==3, 'Data dimension must be 3!'
    if cmap is None:
        cmap = cm.jet
    if vmin is None:
        vmin = data.min()
    if vmax is None:
        vmax = data.max()
    nCH,_,_= data.shape
    nr = int(np.ceil(np.sqrt(nCH)))
    assert nr<=10, 'Too many data channels (>10)!'
    grid = ImageGrid(fig, 111, \
            nrows_ncols=(nr, nr),\
            axes_pad=0.1,\
            add_all=True,\
            label_mode='L')
    for i in range(nCH):
        ax = grid[i]
        im = ax.imshow(data[i,:,:], vmin=vmin, vmax=vmax, \
                interpolation='nearest', cmap=cmap)
#    div = make_axes_locatable(ax)
#    cax = div.append_axes('right', size='5%', pad=0.05) # colorbar axis to the right
#    plt.colorbar(im, cax=cax) 
Example 32
Project: ANN   Author: waynezv   File: ANN_large_v2.py    MIT License 5 votes vote down vote up
def nice_show(fig, data, vmin=None, vmax=None, cmap=None):
    '''
    data is 3D (nCH, nCol, nRow)
    '''
    assert data.ndim==3, 'Data dimension must be 3!'
    if cmap is None:
        cmap = cm.jet
    if vmin is None:
        vmin = data.min()
    if vmax is None:
        vmax = data.max()
    nCH,_,_= data.shape
    nr = int(np.ceil(np.sqrt(nCH)))
    assert nr<=10, 'Too many data channels (>10)!'
    grid = ImageGrid(fig, 111, \
            nrows_ncols=(nr, nr),\
            axes_pad=0.1,\
            add_all=True,\
            label_mode='L')
    for i in range(nCH):
        ax = grid[i]
        im = ax.imshow(data[i,:,:], vmin=vmin, vmax=vmax, \
                interpolation='nearest', cmap=cmap)
#    div = make_axes_locatable(ax)
#    cax = div.append_axes('right', size='5%', pad=0.05) # colorbar axis to the right
#    plt.colorbar(im, cax=cax) 
Example 33
Project: optics   Author: radiasoft   File: bending_magnet_srw1.py    Apache License 2.0 5 votes vote down vote up
def main():
    """test bending magnet and plot results"""
    res = test_bending_magnet_infrared()
    pkdc('Calling plots with array shape: {}...', res.intensity.shape)
    plt.pcolormesh(res.dim_x, res.dim_y, res.intensity.transpose())
    plt.title('Real space for infrared example')
    plt.colorbar()
    plt.show() 
Example 34
Project: optics   Author: radiasoft   File: bending_magnet_srw_param1.py    Apache License 2.0 5 votes vote down vote up
def main():
    wavefront = test_simulation()
    mesh = copy.deepcopy(wavefront.mesh)
    intensity = pkarray.new_float([0] * mesh.nx * mesh.ny)
    srw.srwl.CalcIntFromElecField(intensity, wavefront, 6, 1, 3, mesh.eStart, 0, 0)
    import matplotlib.pyplot as plt
    dim_x = np.linspace(mesh.xStart, mesh.xFin, mesh.nx)
    dim_y = np.linspace(mesh.yStart, mesh.yFin, mesh.ny)
    intensity = np.array(intensity).reshape((mesh.ny,mesh.nx))
    plt.pcolormesh(dim_x, dim_y, intensity)
    plt.title('Real space for infrared example')
    plt.colorbar()
    plt.show() 
Example 35
Project: optics   Author: radiasoft   File: bending_magnet_srw_native1.py    Apache License 2.0 5 votes vote down vote up
def main():
    wfr = test_simulation()
    mesh = copy.deepcopy(wfr.mesh)
    arI1s = pkarray.new_float([0] * mesh.nx * mesh.ny)
    srw.srwl.CalcIntFromElecField(arI1s, wfr, 6, 1, 3, mesh.eStart, 0, 0)
    import matplotlib.pyplot as plt
    dim_x = np.linspace(mesh.xStart, mesh.xFin, mesh.nx)
    dim_y = np.linspace(mesh.yStart, mesh.yFin, mesh.ny)
    intensity = np.array(arI1s).reshape((mesh.ny,mesh.nx))
    plt.pcolormesh(dim_x, dim_y, intensity)
    plt.title('Real space for infrared example')
    plt.colorbar()
    plt.show() 
Example 36
Project: bem   Author: soleneulmer   File: bem.py    MIT License 5 votes vote down vote up
def plot_dataset(dataset, predicted_radii=[], rv=False):

    if not rv:
        # Remove outlier planets
        dataset = dataset.drop(['Kepler-11 g'])
        dataset = dataset.drop(['K2-95 b'])
        dataset = dataset.drop(['HATS-12 b'])

        # Plot the original dataset
        fig = plt.figure()
        ax = fig.add_subplot(111)
        ax.set_xscale('log')
        ax.set_yscale('log')

        size = dataset.temp_eq
        plt.scatter(dataset.mass, dataset.radius, c=size,
                    cmap=cm.magma_r, s=4, label='Verification sample')
        plt.colorbar(label=r'Equilibrium temperature (K)')
        plt.xlabel(r'Mass ($M_\oplus$)')
        plt.ylabel(r'Radius ($R_\oplus$)')
        plt.legend(loc='lower right', markerscale=0,
                   handletextpad=0.0, handlelength=0)

    if rv:
        # Plot the radial velocity dataset
        fig = plt.figure()
        ax = fig.add_subplot(111)
        ax.set_xscale('log')
        ax.set_yscale('log')

        size = dataset.temp_eq
        plt.scatter(dataset.mass, predicted_radii, c=size,
                    cmap=cm.magma_r, s=4, label='RV sample')
        plt.colorbar(label=r'Equilibrium temperature (K)')
        plt.xlabel(r'Mass ($M_\oplus$)')
        plt.ylabel(r'Radius ($R_\oplus$)')
        plt.legend(loc='lower right', markerscale=0,
                   handletextpad=0.0, handlelength=0)

    return None 
Example 37
Project: xia2   Author: xia2   File: AimlessSurface.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def generate_map(abscor, png_filename):
    import matplotlib

    matplotlib.use("Agg")
    from matplotlib import pyplot

    pyplot.imshow(abscor)
    pyplot.colorbar()
    pyplot.savefig(png_filename) 
Example 38
Project: ml-eeg   Author: pbrusco   File: visualizations.py    GNU General Public License v3.0 5 votes vote down vote up
def topomap(values_by_time, montage_file, freq, cmap="Greys", fontsize=15, title=""):
    montage = data_import.read_montage(montage_file)

    vmin = values_by_time.feature_importances_folds_mean.min()
    vmax = values_by_time.feature_importances_folds_mean.max()
    # vmin, vmax = (0.0005, 0.0015)
    l = mne.channels.make_eeg_layout(mne.create_info(montage.ch_names, freq, ch_types="eeg", montage=montage))

    times = sorted(set(values_by_time.time))
    fig, axes = plt.subplots(1, len(times), figsize=(3 * len(times), 5))

    if not isinstance(axes, np.ndarray):
        axes = np.array([axes])

    [ax.axis('off') for ax in axes]
    for top_n, (time, ax) in enumerate(zip(times, axes)):
        time_data = values_by_time[values_by_time["time"] == time]

        t = list(time_data.time)[0]
        image, _ = mne.viz.plot_topomap(list(time_data["values"]), l.pos[:, 0:2], vmin=vmin, vmax=vmax, outlines="skirt", axes=ax, show_names=False, names=l.names, show=False, cmap=cmap)
        if top_n == len(axes) - 1:
            divider = make_axes_locatable(ax)
            ax_colorbar = divider.append_axes('right', size='5%', pad=0.05)
            plt.colorbar(image, cax=ax_colorbar)

        ax.set_title("{} ms".format(t), fontsize=fontsize)

    fig.suptitle(title, fontsize=16)
    plt.draw() 
Example 39
Project: ml-eeg   Author: pbrusco   File: visualizations.py    GNU General Public License v3.0 5 votes vote down vote up
def window_bars(features_table, title="", fontsize=20):
    features_table.sort_values(["window_size", "starting_time"], ascending=False, inplace=True)
    fig = plt.figure()
    ax = fig.add_subplot(111)

    cmap = matplotlib.cm.get_cmap('Greys')
    plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
    vmin, vmax = (features_table.feature_importances_folds_mean.min(), features_table.feature_importances_folds_mean.max())
    norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax)

    for idx, (_, row) in enumerate(features_table.iterrows()):
        val = row.feature_importances_folds_mean
        # plt.hlines(y=idx, lw=3, color=cmap(norm(val)), xmin=row.starting_time, xmax=row.end_time)
        p = patches.Rectangle(
            (row.starting_time, idx),  # (x, y)
            row.window_size,  # width
            1,  # height
            facecolor=cmap(norm(val)),
            # edgecolor="blue"
        )
        ax.add_patch(p)

    ax.set_title(title, fontsize=fontsize)
    plt.xlim([features_table.starting_time.min(), features_table.end_time.max()])
    plt.ylim([-1, len(features_table) + 2])

    divider = make_axes_locatable(ax)
    ax_colorbar = divider.append_axes('right', size='60%', pad=0.01)

    img = plt.imshow(np.array([[vmin, vmax]]), cmap=cmap)
    img.set_visible(False)
    plt.colorbar(img, cax=ax_colorbar, orientation="vertical")

    plt.draw() 
Example 40
Project: argus-freesound   Author: lRomul   File: audio.py    MIT License 5 votes vote down vote up
def show_melspectrogram(mels, title='Log-frequency power spectrogram'):
    import matplotlib.pyplot as plt

    librosa.display.specshow(mels, x_axis='time', y_axis='mel',
                             sr=config.sampling_rate, hop_length=config.hop_length,
                             fmin=config.fmin, fmax=config.fmax)
    plt.colorbar(format='%+2.0f dB')
    plt.title(title)
    plt.show() 
Example 41
Project: TopoMetricUncertainty   Author: UP-RS-ESP   File: surfaces.py    MIT License 5 votes vote down vote up
def main():
    from matplotlib import pyplot as pl

    xb, yb, z = gaussian_hill_dem(0.1)
    pl.pcolormesh(xb, yb, z)
    pl.colorbar()
    pl.show()

    xb, yb, z = sphere_dem(0.1)
    z = np.ma.masked_invalid(z)
    pl.pcolormesh(xb, yb, z)
    pl.colorbar()
    pl.show() 
Example 42
Project: OCDVAE_ContinualLearning   Author: MrtnMndt   File: visualization.py    MIT License 5 votes vote down vote up
def visualize_confusion(writer, step, matrix, class_dict, save_path):
    """
    Visualization of confusion matrix. Is saved to hard-drive and TensorBoard.

    Parameters:
        writer (tensorboard.SummaryWriter): TensorBoard SummaryWriter instance.
        step (int): Counter usually specifying steps/epochs/time.
        matrix (numpy.array): Square-shaped array of size class x class.
            Should specify cross-class accuracies/confusion in percent
            values (range 0-1).
        class_dict (dict): Dictionary specifying class names as keys and
            corresponding integer labels/targets as values.
        save_path (str): Path used for saving
    """

    all_categories = sorted(class_dict, key=class_dict.get)

    fig = plt.figure()
    ax = fig.add_subplot(111)
    cax = ax.matshow(matrix)
    fig.colorbar(cax, boundaries=[0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1])

    # Set up axes
    ax.set_xticklabels([''] + all_categories, rotation=90)
    ax.set_yticklabels([''] + all_categories)

    # Force label at every tick
    ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
    ax.yaxis.set_major_locator(ticker.MultipleLocator(1))

    # Turn off the grid for this plot
    ax.grid(False)
    plt.tight_layout()

    writer.add_figure("Training data", fig, global_step=str(step))
    plt.savefig(os.path.join(save_path, 'confusion_epoch_' + str(step) + '.png'), bbox_inches='tight') 
Example 43
Project: python-wavelet-transform   Author: bearicc   File: mycwt.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def cwt(x, scales, wname, bplot=False):
    coefs = sp.zeros((len(scales), len(x)))
    for i in range(0, len(scales)):
        if wname == 'bior2.6':
            length = min(13*scales[i], len(x))
            wavelet = bior2_6
        coefs[i-1, :] = convolve(x, wavelet(length, i), mode='same')
    
    if bplot:
        import matplotlib.pyplot as plt
        import matplotlib.gridspec as gridspec
        plt.ion()
        fig = plt.figure(num=None, figsize=(14,5), dpi=100, facecolor='w', edgecolor='k')
        plt.clf()
        gs = gridspec.GridSpec(3, 1)
        ax1 = fig.add_subplot(gs[0,0])
        ax1.plot(x,'b-')
    
        ax2 = fig.add_subplot(gs[1:,0])
        im = ax2.imshow(coefs[::-1,:], extent=[0, len(x), scales[0], scales[-1]], aspect='auto', cmap='jet')
        ax2.invert_yaxis()
        ax2.set_xlabel('t')
        ax2.set_ylabel('scale')
        l, b, w, h = ax2.get_position().bounds
        cax = fig.add_axes([l+w+0.01, b, 0.02, h])
        plt.colorbar(im, cax=cax)
        plt.suptitle('cwt by python')
        plt.draw()
        plt.show(block=True)
            
    return coefs 
Example 44
Project: DPC   Author: TengdaHan   File: utils.py    MIT License 5 votes vote down vote up
def plot_mat(self, path, dictionary=None, annotate=False):
        plt.figure(dpi=600)
        plt.imshow(self.mat,
            cmap=plt.cm.jet,
            interpolation=None,
            extent=(0.5, np.shape(self.mat)[0]+0.5, np.shape(self.mat)[1]+0.5, 0.5))
        width, height = self.mat.shape
        if annotate:
            for x in range(width):
                for y in range(height):
                    plt.annotate(str(int(self.mat[x][y])), xy=(y+1, x+1),
                                 horizontalalignment='center',
                                 verticalalignment='center',
                                 fontsize=8)

        if dictionary is not None:
            plt.xticks([i+1 for i in range(width)],
                       [dictionary[i] for i in range(width)],
                       rotation='vertical')
            plt.yticks([i+1 for i in range(height)],
                       [dictionary[i] for i in range(height)])
        plt.xlabel('Ground Truth')
        plt.ylabel('Prediction')
        plt.colorbar()
        plt.tight_layout()
        plt.savefig(path, format='svg')
        plt.clf()

        # for i in range(width):
        #     if np.sum(self.mat[i,:]) != 0:
        #         self.precision.append(self.mat[i,i] / np.sum(self.mat[i,:]))
        #     if np.sum(self.mat[:,i]) != 0:
        #         self.recall.append(self.mat[i,i] / np.sum(self.mat[:,i]))
        # print('Average Precision: %0.4f' % np.mean(self.precision))
        # print('Average Recall: %0.4f' % np.mean(self.recall)) 
Example 45
Project: score-informed-nmf   Author: matangover   File: score_informed_nmf.py    MIT License 5 votes vote down vote up
def show_activations(signal, h, component_labels=None, cmap=None):
    plt.figure(figsize=(14, 4))
    cmap = cmap or librosa.display.cmap(h)
    librosa.display.specshow(h, sr=signal.sr, x_axis='time', hop_length=signal.fft_hop_length, cmap=cmap)
    if component_labels:
        tick_locations = range(0, h.shape[0], 4)
        plt.yticks(tick_locations, numpy.array(component_labels)[tick_locations])
    plt.colorbar()
    plt.show() 
Example 46
Project: score-informed-nmf   Author: matangover   File: score_informed_nmf.py    MIT License 5 votes vote down vote up
def show_components(signal, w, spectrogram_ylim=2000):
    plt.figure(figsize=(14, 4))
    librosa.display.specshow(librosa.amplitude_to_db(w), sr=signal.sr, y_axis='linear')
    plt.colorbar()
    plt.ylim((0, spectrogram_ylim))
    plt.show() 
Example 47
Project: score-informed-nmf   Author: matangover   File: score_informed_nmf.py    MIT License 5 votes vote down vote up
def show_magnitudes(X, sr):
    db = librosa.amplitude_to_db(X)
    plt.figure(figsize=(14, 4))
    librosa.display.specshow(db, sr=sr, x_axis='time', y_axis='hz')
    plt.colorbar()
    plt.ylim((0, 2000)) 
Example 48
Project: StanShock   Author: IhmeGroup   File: stanShock.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def plotXTDiagram(self,XTDiagram,limits=None):
        '''
        Method: plotXTDiagram
        --------------------------------------------------------------------------
        This method creates a contour plot of the XTDiagram data
            inputs:
                XTDiagram=XTDiagram object; obtained from the XTDiagrams dictionary
                limits = tuple of maximum and minimum for the pcolor (vMin,vMax)
                
        '''
        plt.figure()
        t = [t*1000.0 for t in XTDiagram.t]
        X, T = np.meshgrid(XTDiagram.x,t)
        variableMatrix = np.zeros(X.shape)
        for k, variablek in enumerate(XTDiagram.variable): 
            variableMatrix[k,:]=variablek
        variable=XTDiagram.name
        if variable in ["density","r","rho"]:
            plt.title("$\\rho\ [\mathrm{kg/m^3}]$")
        elif variable in ["velocity","u"]:
            plt.title("$u\ [\mathrm{m/s}]$")
        elif variable in ["pressure","p"]:
            variableMatrix /= 1.0e5 #convert to bar
            plt.title("$p\ [\mathrm{bar}]$")
        elif variable in ["temperature","t"]:
            plt.title("$T\ [\mathrm{K}]$")
        elif variable in ["gamma","g","specific heat ratio", "heat capacity ratio"]:
            plt.title("$\gamma$")
        else: plt.title("$\mathrm{"+variable+"}$")
        if limits is None: plt.pcolormesh(X,T,variableMatrix,cmap='jet')
        else: plt.pcolormesh(X,T,variableMatrix,cmap='jet',vmin=limits[0],vmax=limits[1])
        plt.xlabel("$x\ [\mathrm{m}]$")
        plt.ylabel("$t\ [\mathrm{ms}]$")
        plt.axis([min(XTDiagram.x), max(XTDiagram.x), min(t), max(t)])
        plt.colorbar()
############################################################################## 
Example 49
Project: easydl   Author: thuml   File: visualization.py    MIT License 5 votes vote down vote up
def plot_confusion_matrix(cm, true_classes,pred_classes=None,
                          normalize=False,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues):
    import itertools
    pred_classes = pred_classes or true_classes
    if normalize:
        cm = cm.astype(np.float) / np.sum(cm, axis=1, keepdims=True)

    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar(fraction=0.046, pad=0.04)
    true_tick_marks = np.arange(len(true_classes))
    plt.yticks(true_tick_marks, true_classes)
    pred_tick_marks = np.arange(len(pred_classes))
    plt.xticks(pred_tick_marks, pred_classes, rotation=45)


    fmt = '.2f' if normalize else 'd'
    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, format(cm[i, j], fmt),
                 horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black")

    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')
    plt.show() 
Example 50
Project: adagan   Author: tolstikhin   File: metrics.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _make_plots_2d(self, opts, step, real_points,
                       fake_points, weights=None, prefix=''):

        max_val = opts['gmm_max_val'] * 2
        if real_points is None:
            real = np.zeros([0, 2])
        else:
            num_real_points = len(real_points)
            real = np.reshape(real_points, [num_real_points, 2])
        if fake_points is None:
            fake = np.zeros([0, 2])
        else:
            num_fake_points = len(fake_points)
            fake = np.reshape(fake_points, [num_fake_points, 2])

        # Plotting the sample
        plt.clf()
        plt.axis([-max_val, max_val, -max_val, max_val])
        plt.scatter(real[:, 0], real[:, 1], color='red', s=20, label='real')
        plt.scatter(fake[:, 0], fake[:, 1], color='blue', s=20, label='fake')
        plt.legend(loc='upper left')
        filename = prefix + 'mixture{:02d}.png'.format(step)
        utils.create_dir(opts['work_dir'])
        plt.savefig(utils.o_gfile((opts["work_dir"], filename), 'wb'),
                    format='png')

        # Plotting the weights, if provided
        if weights is not None:
            plt.clf()
            plt.axis([-max_val, max_val, -max_val, max_val])
            assert len(weights) == len(real)
            plt.scatter(real[:, 0], real[:, 1], c=weights, s=40,
                        edgecolors='face')
            plt.colorbar()
            filename = prefix + 'weights{:02d}.png'.format(step)
            utils.create_dir(opts['work_dir'])
            plt.savefig(utils.o_gfile((opts["work_dir"], filename), 'wb'),
                        format='png')