Python matplotlib.pyplot.colorbar() Examples

The following are 30 code examples of matplotlib.pyplot.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.pyplot , or try the search function .
Example #1
Source File: NavierStokes.py    From PINNs with MIT License 7 votes vote down vote up
def plot_solution(X_star, u_star, index):
    
    lb = X_star.min(0)
    ub = X_star.max(0)
    nn = 200
    x = np.linspace(lb[0], ub[0], nn)
    y = np.linspace(lb[1], ub[1], nn)
    X, Y = np.meshgrid(x,y)
    
    U_star = griddata(X_star, u_star.flatten(), (X, Y), method='cubic')
    
    plt.figure(index)
    plt.pcolor(X,Y,U_star, cmap = 'jet')
    plt.colorbar() 
Example #2
Source File: visualise_att_maps_epoch.py    From Attention-Gated-Networks with MIT License 7 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 #3
Source File: visualise_attention.py    From Attention-Gated-Networks with 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 #4
Source File: visualise_fmaps.py    From Attention-Gated-Networks with 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 #5
Source File: core.py    From prickle with 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 #6
Source File: visualise_attention.py    From Attention-Gated-Networks with 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 #7
Source File: test_mesh_io.py    From simnibs with GNU General Public License v3.0 6 votes vote down vote up
def test_interpolate_grid_elmdata_dicontinuous(self, sphere3_msh):
        data = sphere3_msh.elm.tag1
        f = mesh_io.ElementData(data, mesh=sphere3_msh)
        n = (200, 130, 1)
        affine = np.array([[1, 0, 0, -100.1],
                           [0,-1, 0, 65.1],
                           [0, 0, 1, 0],
                           [0, 0, 0, 1]], dtype=float)
        interp = f.interpolate_to_grid(n, affine, method='linear', continuous=False)
        '''
        import matplotlib.pyplot as plt
        plt.figure()
        plt.imshow(np.squeeze(interp))
        plt.colorbar()
        plt.show()
        '''
        assert np.allclose(interp[6:10, 65, 0], 5, atol=1e-1)
        assert np.allclose(interp[11:15, 65, 0], 4, atol=1e-1)
        assert np.allclose(interp[16:100, 65, 0], 3, atol=1e-1) 
Example #8
Source File: test_mesh_io.py    From simnibs with GNU General Public License v3.0 6 votes vote down vote up
def test_interpolate_grid_elmdata_linear(self, sphere3_msh):
        data = sphere3_msh.elements_baricenters().value[:, 0]
        f = mesh_io.ElementData(data, mesh=sphere3_msh)
        n = (130, 130, 1)
        affine = np.array([[1, 0, 0, -65],
                           [0, 1, 0, -65],
                           [0, 0, 1, 0],
                           [0, 0, 0, 1]], dtype=float)
        X, _ = np.meshgrid(np.arange(130), np.arange(130), indexing='ij')
        interp = f.interpolate_to_grid(n, affine, method='linear', continuous=True)
        '''
        import matplotlib.pyplot as plt
        plt.figure()
        plt.imshow(np.squeeze(interp))
        plt.colorbar()
        plt.show()
        '''
        assert np.allclose(interp[:, :, 0], X - 64.5, atol=1) 
Example #9
Source File: test_mesh_io.py    From simnibs with GNU General Public License v3.0 6 votes vote down vote up
def test_interpolate_grid_rotate_nodedata(self, sphere3_msh):
        data = np.zeros(sphere3_msh.nodes.nr)
        b = sphere3_msh.nodes.node_coord.copy()
        f = mesh_io.NodeData(data, mesh=sphere3_msh)
        # Assign quadrant numbers
        f.value[(b[:, 0] >= 0) * (b[:, 1] >= 0)] = 1.
        f.value[(b[:, 0] <= 0) * (b[:, 1] >= 0)] = 2.
        f.value[(b[:, 0] <= 0) * (b[:, 1] <= 0)] = 3.
        f.value[(b[:, 0] >= 0) * (b[:, 1] <= 0)] = 4.
        n = (200, 200, 1)
        affine = np.array([[np.cos(np.pi/4.), np.sin(np.pi/4.), 0, -141],
                           [-np.sin(np.pi/4.), np.cos(np.pi/4.), 0, 0],
                           [0, 0, 1, .5],
                           [0, 0, 0, 1]], dtype=float)
        interp = f.interpolate_to_grid(n, affine)
        '''
        import matplotlib.pyplot as plt
        plt.imshow(np.squeeze(interp), interpolation='nearest')
        plt.colorbar()
        plt.show()
        '''
        assert np.isclose(interp[190, 100, 0], 4)
        assert np.isclose(interp[100, 190, 0], 1)
        assert np.isclose(interp[10, 100, 0], 2)
        assert np.isclose(interp[100, 10, 0], 3) 
Example #10
Source File: test_mesh_io.py    From simnibs with GNU General Public License v3.0 6 votes vote down vote up
def test_interpolate_grid_rotate_nn(self, sphere3_msh):
        data = np.zeros(sphere3_msh.elm.nr)
        b = sphere3_msh.elements_baricenters().value
        f = mesh_io.ElementData(data, mesh=sphere3_msh)
        # Assign quadrant numbers
        f.value[(b[:, 0] > 0) * (b[:, 1] > 0)] = 1.
        f.value[(b[:, 0] < 0) * (b[:, 1] > 0)] = 2.
        f.value[(b[:, 0] < 0) * (b[:, 1] < 0)] = 3.
        f.value[(b[:, 0] > 0) * (b[:, 1] < 0)] = 4.
        n = (200, 200, 1)
        affine = np.array([[np.cos(np.pi/4.), np.sin(np.pi/4.), 0, -141],
                           [-np.sin(np.pi/4.), np.cos(np.pi/4.), 0, 0],
                           [0, 0, 1, .5],
                           [0, 0, 0, 1]], dtype=float)
        interp = f.interpolate_to_grid(n, affine, method='assign')
        '''
        import matplotlib.pyplot as plt
        plt.imshow(np.squeeze(interp))
        plt.colorbar()
        plt.show()
        '''
        assert np.isclose(interp[190, 100, 0], 4)
        assert np.isclose(interp[100, 190, 0], 1)
        assert np.isclose(interp[10, 100, 0], 2)
        assert np.isclose(interp[100, 10, 0], 3) 
Example #11
Source File: test_mesh_io.py    From simnibs with GNU General Public License v3.0 6 votes vote down vote up
def test_interpolate_grid_const_nn(self, sphere3_msh):
        data = sphere3_msh.elm.tag1
        f = mesh_io.ElementData(data, mesh=sphere3_msh)
        n = (200, 10, 1)
        affine = np.array([[1, 0, 0, -100.5],
                           [0, 1, 0, -5],
                           [0, 0, 1, 0],
                           [0, 0, 0, 1]], dtype=float)
        interp = f.interpolate_to_grid(n, affine, method='assign')
        '''
        import matplotlib.pyplot as plt
        plt.imshow(np.squeeze(interp))
        plt.colorbar()
        plt.show()
        assert False
        '''
        assert np.isclose(interp[100, 5, 0], 3)
        assert np.isclose(interp[187, 5, 0], 4)
        assert np.isclose(interp[193, 5, 0], 5)
        assert np.isclose(interp[198, 5, 0], 0) 
Example #12
Source File: pixel.py    From yatsm with MIT License 6 votes vote down vote up
def plot_DOY(dates, y, mpl_cmap):
    """ Create a DOY plot

    Args:
        dates (iterable): sequence of datetime
        y (np.ndarray): variable to plot
        mpl_cmap (colormap): matplotlib colormap
    """
    doy = np.array([d.timetuple().tm_yday for d in dates])
    year = np.array([d.year for d in dates])

    sp = plt.scatter(doy, y, c=year, cmap=mpl_cmap,
                     marker='o', edgecolors='none', s=35)
    plt.colorbar(sp)

    months = mpl.dates.MonthLocator()  # every month
    months_fmrt = mpl.dates.DateFormatter('%b')

    plt.tick_params(axis='x', which='minor', direction='in', pad=-10)
    plt.axes().xaxis.set_minor_locator(months)
    plt.axes().xaxis.set_minor_formatter(months_fmrt)

    plt.xlim(1, 366)
    plt.xlabel('Day of Year') 
Example #13
Source File: pixel.py    From yatsm with MIT License 6 votes vote down vote up
def plot_VAL(dates, y, mpl_cmap, reps=2):
    """ Create a "Valerie Pasquarella" plot (repeated DOY plot)

    Args:
        dates (iterable): sequence of datetime
        y (np.ndarray): variable to plot
        mpl_cmap (colormap): matplotlib colormap
        reps (int, optional): number of additional repetitions
    """
    doy = np.array([d.timetuple().tm_yday for d in dates])
    year = np.array([d.year for d in dates])

    # Replicate `reps` times
    _doy = doy.copy()
    for r in range(1, reps + 1):
        _doy = np.concatenate((_doy, doy + r * 366))
    _year = np.tile(year, reps + 1)
    _y = np.tile(y, reps + 1)

    sp = plt.scatter(_doy, _y, c=_year, cmap=mpl_cmap,
                     marker='o', edgecolors='none', s=35)
    plt.colorbar(sp)
    plt.xlabel('Day of Year') 
Example #14
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 #15
Source File: plotting.py    From qb with MIT License 6 votes vote down vote up
def plot_confusion(title, true_labels, predicted_labels, normalized=True):
    labels = list(set(true_labels) | set(predicted_labels))

    if normalized:
        cm = confusion_matrix(true_labels, predicted_labels, labels=labels)
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
    else:
        cm = confusion_matrix(true_labels, predicted_labels, labels=labels)

    fig, ax = plt.subplots(figsize=(10, 10))
    ax.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues)
    ax.set_title(title)
    # plt.colorbar()
    tick_marks = np.arange(len(labels))
    ax.set_xticks(tick_marks)
    ax.set_xticklabels(labels, rotation=90)
    ax.set_yticks(tick_marks)
    ax.set_yticklabels(labels)
    ax.set_ylabel('True Label')
    ax.set_xlabel('Predicted Label')
    ax.grid(False)
    return fig, ax 
Example #16
Source File: plot.py    From TaskBot with GNU General Public License v3.0 6 votes vote down vote up
def plot_attention(sentences, attentions, labels, **kwargs):
    fig, ax = plt.subplots(**kwargs)
    im = ax.imshow(attentions, interpolation='nearest',
                   vmin=attentions.min(), vmax=attentions.max())
    plt.colorbar(im, shrink=0.5, ticks=[0, 1])
    plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
             rotation_mode="anchor")
    ax.set_yticks(range(len(labels)))
    ax.set_yticklabels(labels, fontproperties=getChineseFont())
    # Loop over data dimensions and create text annotations.
    for i in range(attentions.shape[0]):
        for j in range(attentions.shape[1]):
            text = ax.text(j, i, sentences[i][j],
                           ha="center", va="center", color="b", size=10,
                           fontproperties=getChineseFont())

    ax.set_title("Attention Visual")
    fig.tight_layout()
    plt.show() 
Example #17
Source File: ephys_qc_raw.py    From ibllib with MIT License 6 votes vote down vote up
def _plot_rmsmap(outfil, typ, savefig=True):
    rmsmap = alf.io.load_object(outpath, '_iblqc_ephysTimeRms' + typ.upper())
    plt.figure(figsize=[12, 4.5])
    axim = plt.axes([0.2, 0.1, 0.7, 0.8])
    axrms = plt.axes([0.05, 0.1, 0.15, 0.8])
    axcb = plt.axes([0.92, 0.1, 0.02, 0.8])

    axrms.plot(np.median(rmsmap['rms'], axis=0)[:-1] * 1e6, np.arange(1, rmsmap['rms'].shape[1]))
    axrms.set_ylim(0, rmsmap['rms'].shape[1])

    im = axim.imshow(20 * np.log10(rmsmap['rms'].T + 1e-15), aspect='auto', origin='lower',
                     extent=[rmsmap['timestamps'][0], rmsmap['timestamps'][-1],
                             0, rmsmap['rms'].shape[1]])
    axim.set_xlabel(r'Time (s)')
    axim.set_ylabel(r'Channel Number')
    plt.colorbar(im, cax=axcb)
    if typ == 'ap':
        im.set_clim(-110, -90)
        axrms.set_xlim(100, 0)
    elif typ == 'lf':
        im.set_clim(-100, -60)
        axrms.set_xlim(500, 0)
    axim.set_xlim(0, 4000)
    if savefig:
        plt.savefig(outpath / (typ + '_rms.png'), dpi=150) 
Example #18
Source File: preprocessing.py    From Geocoding-with-Map-Vector with GNU General Public License v3.0 6 votes vote down vote up
def visualise_2D_grid(x, title, log=False):
    """
    Display 2D array data with a title. Optional: log for better visualisation of small values.
    :param x: 2D numpy array you want to visualise
    :param title: of the chart because it's nice to have one :-)
    :param log: True in order to log the values and make for better visualisation, False for raw numbers
    """
    if log:
        x = np.log10(x)
    cmap = colors.LinearSegmentedColormap.from_list('my_colormap', ['lightgrey', 'darkgrey', 'dimgrey', 'black'])
    cmap.set_bad(color='white')
    img = pyplot.imshow(x, cmap=cmap, interpolation='nearest')
    pyplot.colorbar(img, cmap=cmap)
    plt.title(title)
    # plt.savefig(title + u".png", dpi=200, transparent=True)  # Uncomment to save to file
    plt.show() 
Example #19
Source File: dataset.py    From neural-combinatorial-optimization-rl-tensorflow with MIT License 6 votes vote down vote up
def visualize_sampling(self, permutations):
        max_length = len(permutations[0])
        grid = np.zeros([max_length,max_length]) # initialize heatmap grid to 0

        transposed_permutations = np.transpose(permutations)
        for t, cities_t in enumerate(transposed_permutations): # step t, cities chosen at step t
            city_indices, counts = np.unique(cities_t,return_counts=True,axis=0)
            for u,v in zip(city_indices, counts):
                grid[t][u]+=v # update grid with counts from the batch of permutations

        # plot heatmap
        fig = plt.figure()
        rcParams.update({'font.size': 22})
        ax = fig.add_subplot(1,1,1)
        ax.set_aspect('equal')
        plt.imshow(grid, interpolation='nearest', cmap='gray')
        plt.colorbar()
        plt.title('Sampled permutations')
        plt.ylabel('Time t')
        plt.xlabel('City i')
        plt.show() 
Example #20
Source File: visualizer.py    From face_classification with MIT License 5 votes vote down vote up
def pretty_imshow(axis, data, vmin=None, vmax=None, cmap=None):
    if cmap is None:
        cmap = cm.jet
    if vmin is None:
        vmin = data.min()
    if vmax is None:
        vmax = data.max()
    cax = None
    divider = make_axes_locatable(axis)
    cax = divider.append_axes('right', size='5%', pad=0.05)
    image = axis.imshow(data, vmin=vmin, vmax=vmax,
                        interpolation='nearest', cmap=cmap)
    plt.colorbar(image, cax=cax) 
Example #21
Source File: NavierStokes.py    From DeepHPMs with MIT License 5 votes vote down vote up
def plot_solution(X_data, w_data, index):
    
    lb = X_data.min(0)
    ub = X_data.max(0)
    nn = 200
    x = np.linspace(lb[0], ub[0], nn)
    y = np.linspace(lb[1], ub[1], nn)
    X, Y = np.meshgrid(x,y)
    
    W_data = griddata(X_data, w_data.flatten(), (X, Y), method='cubic')
    
    plt.figure(index)
    plt.pcolor(X,Y,W_data, cmap = 'jet')
    plt.colorbar() 
Example #22
Source File: viz.py    From dgl with Apache License 2.0 5 votes vote down vote up
def att_animation(maps_array, mode, src, tgt, head_id):
    weights = [maps[mode2id[mode]][head_id] for maps in maps_array]
    fig, axes = plt.subplots(1, 2)

    def weight_animate(i):
        global colorbar
        if colorbar:
            colorbar.remove()
        plt.cla()
        axes[0].set_title('heatmap')
        axes[0].set_yticks(np.arange(len(src)))
        axes[0].set_xticks(np.arange(len(tgt)))
        axes[0].set_yticklabels(src)
        axes[0].set_xticklabels(tgt)
        plt.setp(axes[0].get_xticklabels(), rotation=45, ha="right",
                 rotation_mode="anchor")

        fig.suptitle('epoch {}'.format(i))
        weight = weights[i].transpose(-1, -2)
        heatmap = axes[0].pcolor(weight, vmin=0, vmax=1, cmap=plt.cm.Blues)
        colorbar = plt.colorbar(heatmap, ax=axes[0], fraction=0.046, pad=0.04)
        axes[0].set_aspect('equal')
        axes[1].axis("off")
        graph_att_head(src, tgt, weight, axes[1], 'graph')


    ani = animation.FuncAnimation(fig, weight_animate, frames=len(weights), interval=500, repeat_delay=2000)
    return ani 
Example #23
Source File: analyze.py    From Car-Recognition with MIT 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`.
    """
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        print("Normalized confusion matrix")
    else:
        print('Confusion matrix, without normalization')

    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 #24
Source File: heatmap.py    From python-wifi-survey-heatmap with GNU Affero General Public License v3.0 5 votes vote down vote up
def _plot(self, a, key, title, gx, gy, num_x, num_y):
        pp.rcParams['figure.figsize'] = (
            self._image_width / 300, self._image_height / 300
        )
        pp.title(title)
        # Interpolate the data
        rbf = Rbf(
            a['x'], a['y'], a[key], function='linear'
        )
        z = rbf(gx, gy)
        z = z.reshape((num_y, num_x))
        # Render the interpolated data to the plot
        pp.axis('off')
        # begin color mapping
        norm = matplotlib.colors.Normalize(
            vmin=min(a[key]), vmax=max(a[key]), clip=True
        )
        mapper = cm.ScalarMappable(norm=norm, cmap='RdYlBu_r')
        # end color mapping
        image = pp.imshow(
            z,
            extent=(0, self._image_width, self._image_height, 0),
            cmap='RdYlBu_r', alpha=0.5, zorder=100
        )
        pp.colorbar(image)
        pp.imshow(self._layout, interpolation='bicubic', zorder=1, alpha=1)
        # begin plotting points
        for idx in range(0, len(a['x'])):
            pp.plot(
                a['x'][idx], a['y'][idx],
                marker='o', markeredgecolor='black', markeredgewidth=1,
                markerfacecolor=mapper.to_rgba(a[key][idx]), markersize=6
            )
        # end plotting points
        fname = '%s_%s.png' % (key, self._title)
        logger.info('Writing plot to: %s', fname)
        pp.savefig(fname, dpi=300)
        pp.close('all') 
Example #25
Source File: PlottingRaster.py    From LSDMappingTools with MIT License 5 votes vote down vote up
def add_point_colourbar(self,ax_list,sc,cmap = "cubehelix",colorbarlabel = "Colourbar",
                            discrete=False, n_colours=10, cbar_type=float):
        """
        This adds a colourbar for any points that are on the DEM.

        Args:
            ax_list: The list of axes objects. Assumes colourbar is in axis_list[-1]
            sc: The scatterplot object. Generated by plt.scatter
            cmap (string or colourmap): The colourmap.
            colorbarlabel (string): The label of the colourbar

        Author: SMM
        """
        fig = matplotlib.pyplot.gcf()
        ax_list.append(fig.add_axes([0.1,0.8,0.2,0.5]))
        cbar = plt.colorbar(sc,cmap=cmap, orientation=self.colourbar_orientation,cax=ax_list[-1])

        if self.colourbar_location == 'top':
            ax_list[-1].set_xlabel(colorbarlabel, fontname='Liberation Sans',labelpad=5)
        elif self.colourbar_location == 'bottom':
            ax_list[-1].set_xlabel(colorbarlabel, fontname='Liberation Sans',labelpad=5)
        elif self.colourbar_location == 'left':
            ax_list[-1].set_ylabel(colorbarlabel, fontname='Liberation Sans',labelpad=-75,rotation=90)
        elif self.colourbar_location == 'right':
            ax_list[-1].set_ylabel(colorbarlabel, fontname='Liberation Sans',labelpad=10,rotation=270)
        return ax_list 
Example #26
Source File: colours.py    From LSDMappingTools with MIT License 5 votes vote down vote up
def colorbar_index(fig, cax, ncolors, cmap, drape_min_threshold, drape_max):
    """State-machine like function that creates a discrete colormap and plots
       it on a figure that is passed as an argument.

    Arguments:
       fig (matplotlib.Figure): Instance of a matplotlib figure object.
       cax (matplotlib.Axes): Axes instance to create the colourbar from.
           This must be the Axes containing the data that your colourbar will be
           mapped from.
       ncolors (int): The number of colours in the discrete colourbar map.
       cmap (str or Colormap object): Either the name of a matplotlib colormap, or
           an object instance of the colormap, e.g. cm.jet
       drape_min_threshold (float): Number setting the threshold level of the drape raster
           This should match any threshold you have set to mask the drape/overlay raster.
       drape_max (float): Similar to above, but for the upper threshold of your drape mask.
    """

    discrete_cmap = discrete_colourmap(ncolors, cmap)

    mappable = _cm.ScalarMappable(cmap=discrete_cmap)
    mappable.set_array([])
    #mappable.set_clim(-0.5, ncolors + 0.5)
    mappable.set_clim(drape_min_threshold, drape_max)

    print(type(fig))
    print(type(mappable))
    print(type(cax))
    print()
    cbar = _plt.colorbar(mappable, cax=cax) #switched from fig to plt to expose the labeling params
    print(type(cbar))
    #cbar.set_ticks(_np.linspace(0, ncolors, ncolors))
    pad = ((ncolors - 1) / ncolors) / 2  # Move labels to center of bars.
    cbar.set_ticks(_np.linspace(drape_min_threshold + pad, drape_max - pad,
                   ncolors))

    return cbar

# Generate random colormap 
Example #27
Source File: network.py    From psst with MIT License 5 votes vote down vote up
def plot_line_power(obj, results, hour, ax=None):
    '''
    obj: case or network
    '''

    if ax is None:
        fig, ax = plt.subplots(1, 1, figsize=(16, 10))
        ax.axis('off')

    case, network = _return_case_network(obj)

    network.draw_buses(ax=ax)
    network.draw_loads(ax=ax)
    network.draw_generators(ax=ax)
    network.draw_connections('gen_to_bus', ax=ax)
    network.draw_connections('load_to_bus', ax=ax)

    edgelist, edge_color, edge_width, edge_labels = _generate_edges(results, case, hour)
    branches = network.draw_branches(ax=ax, edgelist=edgelist, edge_color=edge_color, width=edge_width, edge_labels=edge_labels)

    divider = make_axes_locatable(ax)
    cax = divider.append_axes('right', size='5%', pad=0.05)
    cb = plt.colorbar(branches, cax=cax, orientation='vertical')
    cax.yaxis.set_label_position('left')
    cax.yaxis.set_ticks_position('left')
    cb.set_label('Loading Factor')

    return ax 
Example #28
Source File: c_tebd.py    From tenpy with GNU General Public License v3.0 5 votes vote down vote up
def example_TEBD_tf_ising_lightcone(L, g, tmax, dt):
    print("finite TEBD, real time evolution, transverse field Ising")
    print("L={L:d}, g={g:.2f}, tmax={tmax:.2f}, dt={dt:.3f}".format(L=L, g=g, tmax=tmax, dt=dt))
    # find ground state with TEBD or DMRG
    #  E, psi, M = example_TEBD_gs_tf_ising_finite(L, g)
    from d_dmrg import example_DMRG_tf_ising_finite
    E, psi, M = example_DMRG_tf_ising_finite(L, g)
    i0 = L // 2
    # apply sigmaz on site i0
    SzB = np.tensordot(M.sigmaz, psi.Bs[i0], axes=[1, 1])  # i [i*], vL [i] vR
    psi.Bs[i0] = np.transpose(SzB, [1, 0, 2])  # vL i vR
    U_bonds = calc_U_bonds(M.H_bonds, 1.j * dt)  # (imaginary dt -> realtime evolution)
    S = [psi.entanglement_entropy()]
    Nsteps = int(tmax / dt + 0.5)
    for n in range(Nsteps):
        if abs((n * dt + 0.1) % 0.2 - 0.1) < 1.e-10:
            print("t = {t:.2f}, chi =".format(t=n * dt), psi.get_chi())
        run_TEBD(psi, U_bonds, 1, chi_max=50, eps=1.e-10)
        S.append(psi.entanglement_entropy())
    import matplotlib.pyplot as plt
    plt.figure()
    plt.imshow(S[::-1],
               vmin=0.,
               aspect='auto',
               interpolation='nearest',
               extent=(0, L - 1., -0.5 * dt, (Nsteps + 0.5) * dt))
    plt.xlabel('site $i$')
    plt.ylabel('time $t/J$')
    plt.ylim(0., tmax)
    plt.colorbar().set_label('entropy $S$')
    filename = 'c_tebd_lightcone_{g:.2f}.pdf'.format(g=g)
    plt.savefig(filename)
    print("saved " + filename) 
Example #29
Source File: utils_image.py    From KAIR with MIT License 5 votes vote down vote up
def imshow(x, title=None, cbar=False, figsize=None):
    plt.figure(figsize=figsize)
    plt.imshow(np.squeeze(x), interpolation='nearest', cmap='gray')
    if title:
        plt.title(title)
    if cbar:
        plt.colorbar()
    plt.show() 
Example #30
Source File: utils.py    From sklearn-audio-transfer-learning with ISC License 5 votes vote down vote up
def matrix_visualization(matrix,title=None):
    """ Visualize 2D matrices like spectrograms or feature maps.
    """
    plt.figure()
    plt.imshow(np.flipud(matrix.T),interpolation=None)
    plt.colorbar()
    if title!=None:
        plt.title(title)
    plt.show()