Python matplotlib.pyplot 模块,get_cmap() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.pyplot.get_cmap()

项目:KATE    作者:hugochan    | 项目源码 | 文件源码
def word_cloud(word_embedding_matrix, vocab, s, save_file='scatter.png'):
    words = [(i, vocab[i]) for i in s]
    model = TSNE(n_components=2, random_state=0)
    #Note that the following line might use a good chunk of RAM
    tsne_embedding = model.fit_transform(word_embedding_matrix)
    words_vectors = tsne_embedding[np.array([item[1] for item in words])]

    plt.subplots_adjust(bottom = 0.1)
    plt.scatter(
        words_vectors[:, 0], words_vectors[:, 1], marker='o', cmap=plt.get_cmap('Spectral'))

    for label, x, y in zip(s, words_vectors[:, 0], words_vectors[:, 1]):
        plt.annotate(
            label,
            xy=(x, y), xytext=(-20, 20),
            textcoords='offset points', ha='right', va='bottom',
            fontsize=20,
            # bbox=dict(boxstyle='round,pad=1.', fc='yellow', alpha=0.5),
            arrowprops=dict(arrowstyle = '<-', connectionstyle='arc3,rad=0')
            )
    plt.show()
    # plt.savefig(save_file)
项目:q2-coordinates    作者:nbokulich    | 项目源码 | 文件源码
def get_map_params(image='StamenTerrain', color_palette=None):
    # set color palette
    if color_palette:
        cmap = plt.get_cmap(color_palette)
    else:
        cmap = None

    # set background image
    if image == 'StamenTerrain':
        tiler = StamenTerrain()
    elif image == 'GoogleTiles':
        tiler = GoogleTiles()
    elif image == 'OSM':
        tiler = OSM()

    return cmap, tiler
项目:bark    作者:kylerbrown    | 项目源码 | 文件源码
def initialize_minimap(self):
        times, values = labels_to_scatter_coords(self.opstack.events)
        self.map_ax.set_axis_bgcolor('k')
        self.map_ax.scatter(times,
                            values,
                            c=values,
                            vmin=0,
                            vmax=37,
                            cmap=plt.get_cmap('hsv'),
                            edgecolors='none')
        self.map_ax.vlines(self.opstack.events[self.i]['start'],
                           -1,
                           38,
                           zorder=0.5,
                           color='w',
                           linewidth=1)
        self.map_ax.tick_params(axis='y',
                                which='both',
                                left='off',
                                right='off',
                                labelleft='off')
        self.map_ax.set_ylim(-1, 38)
项目:IDNNs    作者:ravidziv    | 项目源码 | 文件源码
def plot_by_training_samples(I_XT_array, I_TY_array, axes, epochsInds, f, index_i, index_j, size_ind, font_size, y_ticks, x_ticks, colorbar_axis, title_str, axis_font, bar_font, save_name, samples_labels):
    """Print the final epoch of all the diffrenet training samples size """
    max_index = size_ind if size_ind!=-1 else I_XT_array.shape[2]-1
    cmap = plt.get_cmap('gnuplot')
    colors = [cmap(i) for i in np.linspace(0, 1, max_index+1)]
    #Print the final epoch
    nums_epoch= -1
    #Go over all the samples size and plot them with the right color
    for index_in_range in range(0, max_index):
        XT, TY = [], []
        for layer_index in range(0, I_XT_array.shape[4]):
                XT.append(np.mean(I_XT_array[:, -1, index_in_range, nums_epoch, layer_index], axis=0))
                TY.append(np.mean(I_TY_array[:, -1, index_in_range,nums_epoch, layer_index], axis=0))
        axes[index_i, index_j].plot(XT, TY, marker='o', linestyle='-', markersize=12, markeredgewidth=0.2, linewidth=0.5,
                         color=colors[index_in_range])
    utils.adjustAxes(axes[index_i, index_j], axis_font=axis_font, title_str=title_str, x_ticks=x_ticks, y_ticks=y_ticks,
                     x_lim=None, y_lim=None,
                     set_xlabel=index_i == axes.shape[0] - 1, set_ylabel=index_j == 0, x_label='$I(X;T)$',
                     y_label='$I(T;Y)$', set_xlim=True,
                     set_ylim=True, set_ticks=True, label_size=font_size)
    #Create color bar and save it
    if index_i == axes.shape[0] - 1 and index_j == axes.shape[1] - 1:
        utils.create_color_bar(f, cmap, colorbar_axis, bar_font, epochsInds, title='Training Data')
        f.savefig(save_name + '.jpg', dpi=150, format='jpg')
项目:Fluid2d    作者:pvthinker    | 项目源码 | 文件源码
def create_fig(self):
        fig  = plt.figure(figsize=(16,6))
        ax1 = fig.add_subplot(1, 1, 1)
        ax1.cla()
        ax1.hold(True)

        self.time_str = 'time = %-6.2f'
        ax1.set_title( '' )
        ax1.set_xlabel('X')
        ax1.set_ylabel('Y')

        self.ax1 = ax1

        plt.ion()

        self.im=ax1.imshow( self.z2d, 
                       vmin=self.cax[0],vmax=self.cax[1],
                       cmap=plt.get_cmap('jet'),origin='lower',
                       interpolation='nearest')

        cb = plt.colorbar(self.im)

        fig.show()
        fig.canvas.draw()
        self.fig = fig
项目:pyprob    作者:probprog    | 项目源码 | 文件源码
def weights_to_image(w):
    if not isinstance(w, np.ndarray):
        w = w.data.cpu().numpy()
    if w.ndim == 1:
        w = np.expand_dims(w, 1)
    if w.ndim > 2:
        c = w.shape[0]
        w = np.reshape(w, (c,-1))
    w_min = w.min()
    w_max = w.max()
    w -= w_min
    w *= (1/(w_max - w_min + epsilon))
    cmap = plt.get_cmap('jet')
    rgba_img = cmap(w)
    rgb_img = np.delete(rgba_img, 3,2)
    rgb_img = np.transpose(rgb_img,(2,0,1))
    return rgb_img
项目:lddmm-ot    作者:jeanfeydy    | 项目源码 | 文件源码
def plot(self, ax, color = 'rainbow', linewidth = 3) :
        "Simple display using a per-id color scheme."
        segs = self.segments()

        if color == 'rainbow' :   # rainbow color scheme to see pointwise displacements
            ncycles    = 5
            cNorm      = colors.Normalize(vmin=0, vmax=(len(segs)-1)/ncycles)
            scalarMap  = cm.ScalarMappable(norm=cNorm, cmap=plt.get_cmap('hsv') )
            seg_colors = [ scalarMap.to_rgba( i % ((len(segs)-1)/ncycles) ) 
                           for i in range(len(segs)) ]
        else :                    # uniform color
            seg_colors = [ color for i in range(len(segs)) ] 

        line_segments = LineCollection(segs, linewidths=(linewidth,), 
                                       colors=seg_colors, linestyle='solid')
        ax.add_collection(line_segments)
项目:lddmm-ot    作者:jeanfeydy    | 项目源码 | 文件源码
def plot(self, ax, color = 'rainbow', linewidth = 3) :
        "Simple display using a per-id color scheme."
        segs = self.segments()

        if color == 'rainbow' :   # rainbow color scheme to see pointwise displacements
            ncycles    = 5
            cNorm      = colors.Normalize(vmin=0, vmax=(len(segs)-1)/ncycles)
            scalarMap  = cm.ScalarMappable(norm=cNorm, cmap=plt.get_cmap('hsv') )
            seg_colors = [ scalarMap.to_rgba( i % ((len(segs)-1)/ncycles) ) 
                           for i in range(len(segs)) ]
        else :                    # uniform color
            seg_colors = [ color for i in range(len(segs)) ] 

        line_segments = LineCollection(segs, linewidths=(linewidth,), 
                                       colors=seg_colors, linestyle='solid')
        ax.add_collection(line_segments)
项目:lddmm-ot    作者:jeanfeydy    | 项目源码 | 文件源码
def plot(self, ax, color = 'rainbow', linewidth = 3) :
        "Simple display using a per-id color scheme."
        segs = self.segments()

        if color == 'rainbow' :   # rainbow color scheme to see pointwise displacements
            ncycles    = 5
            cNorm      = colors.Normalize(vmin=0, vmax=(len(segs)-1)/ncycles)
            scalarMap  = cm.ScalarMappable(norm=cNorm, cmap=plt.get_cmap('hsv') )
            seg_colors = [ scalarMap.to_rgba( i % ((len(segs)-1)/ncycles) ) 
                           for i in range(len(segs)) ]
        else :                    # uniform color
            seg_colors = [ color for i in range(len(segs)) ] 

        line_segments = LineCollection(segs, linewidths=(linewidth,), 
                                       colors=seg_colors, linestyle='solid')
        ax.add_collection(line_segments)
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def plot_sSFR_Fyoung(fig, sSFR, Fyoung):

    x, y, z = getDensityKernel(np.log10(sSFR),100*Fyoung)

    DL14_sSFR, DL14_Fyoung = np.loadtxt("/Users/saviaene/Documents/Research/M31/SKIRT/paperFigures/DeLooze2014sSFRHeating.dat", usecols=(0,1), unpack=True)

    fig.set_ylabel('$F_\mathrm{unev.} [\%]$',fontsize=18)
    fig.set_xlabel('$\log(\mathrm{sSFR}/\mathrm{yr}^{-1})$',fontsize=18)
    fig.scatter(x,y, c=z, s=10,cmap=plt.get_cmap('autumn') ,edgecolor='')
    # Plot De Looze 2014 relation between F'young and sSFR
    fig.plot(DL14_sSFR,100.*10**DL14_Fyoung,'g+')
    xrange = np.linspace(-14,-8,100)
    fig.plot(xrange,100.*10**(0.415*xrange+4.045), 'k-')
    fig.set_xlim(-13.5,-8.5)
    fig.set_ylim(-10,90)
    # Plot first order polynomial fit
    #solution = FitPolynomial(fig,x,y,1)
    #solution = FitPolynomialLog(fig,x,y,1)

    #print solution
    #fig3.errorbar(6.8,-5.5, [[mean_MdMs16],[mean_MdMs84]],[[mean_Mskpc216],[mean_Mskpc284]], 'k.')
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def plot_sSFR_FWarmYoung(fig, sSFR, FWarmYoung):

    x, y, z = getDensityKernel(np.log10(sSFR),100*FWarmYoung)

    fig.set_ylabel('$F^\prime_\mathrm{young}^\mathrm{w} [\%]$',fontsize=18)
    fig.set_xlabel('$\log(\mathrm{sSFR}/\mathrm{yr}^{-1})$',fontsize=18)
    fig.scatter(x,y, c=z, s=10,cmap=plt.get_cmap('autumn') ,edgecolor='')
    # Plot De Looze 2014 relation between F'young and sSFR
    xrange = np.linspace(-14,-8,100)
    fig.plot(xrange,100.*10**(0.42*xrange+4.14), 'g--')
    fig.set_xlim(-13.5,-8.5)
    fig.set_ylim(-10,90)
    # Plot first order polynomial fit
    solution = FitPolynomial(fig,x,y,1)
    #solution = FitPolynomialLog(fig,x,y,1)

    print solution
    #fig3.errorbar(6.8,-5.5, [[mean_MdMs16],[mean_MdMs84]],[[mean_Mskpc216],[mean_Mskpc284]], 'k.')
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def plot_sSFR_FColdYoung(fig, sSFR, FColdYoung):

    x, y, z = getDensityKernel(np.log10(sSFR),100*FColdYoung)

    fig.set_ylabel('$F^\prime_\mathrm{young}^\mathrm{c} [\%]$',fontsize=18)
    fig.set_xlabel('$\log(\mathrm{sSFR}/\mathrm{yr}^{-1})$',fontsize=18)
    fig.scatter(x,y, c=z, s=10,cmap=plt.get_cmap('autumn') ,edgecolor='')
    # Plot De Looze 2014 relation between F'young and sSFR
    xrange = np.linspace(-14,-8,100)
    fig.plot(xrange,100.*10**(0.42*xrange+4.14), 'g--')
    fig.set_xlim(-13.5,-8.5)
    fig.set_ylim(-10,90)
    # Plot first order polynomial fit
    solution = FitPolynomial(fig,x,y,1)
    #solution = FitPolynomialLog(fig,x,y,1)

    print solution
#fig3.errorbar(6.8,-5.5, [[mean_MdMs16],[mean_MdMs84]],[[mean_Mskpc216],[mean_Mskpc284]], 'k.')
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def plot_FNUV_r_Fyoung(fig, nuv, r, Fyoung, radiusCut):

    x_r = np.log10(nuv[~radiusCut]/r[~radiusCut])
    y_r = 100*Fyoung[~radiusCut]

    x_r2 = np.log10(nuv[radiusCut]/r[radiusCut])
    y_r2 = 100*Fyoung[radiusCut]

    x, y, z = getDensityKernel(np.log10(nuv[radiusCut]/r[radiusCut]),100*Fyoung[radiusCut])

    fig.set_ylabel('$F_\mathrm{unev.} [\%]$',fontsize=18)
    fig.set_xlabel('$NUV-r$',fontsize=18)
    fig.scatter(x_r,y_r, c='black',s=1 , alpha=0.1)
    #fig.scatter(x_r2,y_r2, c='red',s=1 , alpha=0.1)
    fig.scatter(x,y, c=z, s=10,cmap=plt.get_cmap('autumn') ,edgecolor='')
    fig.set_xlim(-2.7,-0.51)
    fig.set_ylim(-10,110)
    #solution = FitPolynomial(fig,x,y,1)
    #print solution
项目:tritonize    作者:minimaxir    | 项目源码 | 文件源码
def make_gradient(img_size, palette_name):
    background = Image.new('RGBA', img_size, (0, 0, 0, 0))
    palette = makeMappingArray(img_size[0], get_cmap(palette_name))

    rgb_sequence = []
    for x in range(img_size[0]):
        color = palette[x]

        # matplotlib color maps are from range of (0,1). Convert to RGB.
        r = int(color[0] * 255)
        g = int(color[1] * 255)
        b = int(color[2] * 255)

        rgb_sequence.append((r, g, b))

    background.putdata(rgb_sequence * img_size[1])

    return background
项目:smp_base    作者:x75    | 项目源码 | 文件源码
def rp_timeseries_embedding(ax, data, **kwargs):
        """recurrence plot using pyunicorn
        """
        emb_del = 1
        emb_dim = 10
        # logger.log(loglevel_debug, "rp_timeseries_embedding data", data)
        # make data "strictly" one-dimensional
        data = data.reshape((-1, ))
        rp = RecurrencePlot(time_series = data, tau = emb_del, dim = emb_dim, threshold_std = 1.5)

        plotdata = rp.recurrence_matrix()
        length = plotdata.shape[0]

        xs = np.linspace(0, length, length)
        ys = np.linspace(0, length, length)
        ax.pcolormesh(xs, ys, plotdata, cmap=plt.get_cmap("Oranges"))
        ax.set_xlabel("$n$")
        ax.set_ylabel("$n$")
项目:Deep-Learning-with-TensorFlow    作者:PacktPublishing    | 项目源码 | 文件源码
def plotresult(org_vec,noisy_vec,out_vec):
    plt.matshow(np.reshape(org_vec, (28, 28)), cmap=plt.get_cmap('gray'))
    plt.title("Original Image")
    plt.colorbar()

    plt.matshow(np.reshape(noisy_vec, (28, 28)), cmap=plt.get_cmap('gray'))
    plt.title("Input Image")
    plt.colorbar()

    outimg = np.reshape(out_vec, (28, 28))
    plt.matshow(outimg, cmap=plt.get_cmap('gray'))
    plt.title("Reconstructed Image")
    plt.colorbar()
    plt.show()

# NETOWRK PARAMETERS
项目:Deep-Learning-with-TensorFlow    作者:PacktPublishing    | 项目源码 | 文件源码
def plotresult(org_vec,noisy_vec,out_vec):
    plt.matshow(np.reshape(org_vec, (28, 28)), cmap=plt.get_cmap('gray'))
    plt.title("Original Image")
    plt.colorbar()

    plt.matshow(np.reshape(noisy_vec, (28, 28)), cmap=plt.get_cmap('gray'))
    plt.title("Input Image")
    plt.colorbar()

    outimg = np.reshape(out_vec, (28, 28))
    plt.matshow(outimg, cmap=plt.get_cmap('gray'))
    plt.title("Reconstructed Image")
    plt.colorbar()
    plt.show()

# NETOWORK PARAMETERS
项目:Deep-Learning-with-TensorFlow    作者:PacktPublishing    | 项目源码 | 文件源码
def plotresult(org_vec,noisy_vec,out_vec):
    plt.matshow(np.reshape(org_vec, (28, 28)),\
                cmap=plt.get_cmap('gray'))
    plt.title("Original Image")
    plt.colorbar()

    plt.matshow(np.reshape(noisy_vec, (28, 28)),\
                cmap=plt.get_cmap('gray'))
    plt.title("Input Image")
    plt.colorbar()

    outimg   = np.reshape(out_vec, (28, 28))
    plt.matshow(outimg, cmap=plt.get_cmap('gray'))
    plt.title("Reconstructed Image")
    plt.colorbar()
    plt.show()

# NETOWRK PARAMETERS
项目:Deep-Learning-with-TensorFlow    作者:PacktPublishing    | 项目源码 | 文件源码
def plotresult(org_vec,noisy_vec,out_vec):
    plt.matshow(np.reshape(org_vec, (28, 28)),\
                cmap=plt.get_cmap('gray'))
    plt.title("Original Image")
    plt.colorbar()

    plt.matshow(np.reshape(noisy_vec, (28, 28)),\
                cmap=plt.get_cmap('gray'))
    plt.title("Input Image")
    plt.colorbar()

    outimg   = np.reshape(out_vec, (28, 28))
    plt.matshow(outimg, cmap=plt.get_cmap('gray'))
    plt.title("Reconstructed Image")
    plt.colorbar()
    plt.show()

# NETOWORK PARAMETERS
项目:adversarial-variational-bayes    作者:gdikov    | 项目源码 | 文件源码
def _cmap_discretize(cmap, N):
    """Return a discrete colormap from the continuous colormap cmap.

        cmap: colormap instance, eg. cm.jet.
        N: number of colors.

    Example
        x = resize(arange(100), (5,100))
        djet = cmap_discretize(cm.jet, 5)
        imshow(x, cmap=djet)
    """

    if type(cmap) == str:
        cmap = plt.get_cmap(cmap)
    colors_i = np.concatenate((np.linspace(0, 1., N), (0.,0.,0.,0.)))
    colors_rgba = cmap(colors_i)
    indices = np.linspace(0, 1., N+1)
    cdict = {}
    for ki, key in enumerate(('red','green','blue')):
        cdict[key] = [(indices[i], colors_rgba[i-1,ki], colors_rgba[i,ki])
                      for i in range(N+1)]
    # Return colormap object.
    return mcolors.LinearSegmentedColormap(cmap.name + "_%d"%N, cdict, 1024)
项目:convolutional-vqa    作者:paarthneekhara    | 项目源码 | 文件源码
def get_blend_map(img, att_map, blur=True, overlap=True):
    # att_map -= att_map.min()
    # if att_map.max() > 0:
    #     att_map /= att_map.max()
    att_map = 1.0 - att_map
    att_map = transform.resize(att_map, (img.shape[:2]), order = 3, mode='edge')
    # print att_map.shape
    if blur:
        att_map = filters.gaussian(att_map, 0.02*max(img.shape[:2]))
        att_map -= att_map.min()
        att_map /= att_map.max()
    cmap = plt.get_cmap('jet')
    att_map_v = cmap(att_map)
    att_map_v = np.delete(att_map_v, 3, 2)
    if overlap:
        att_map = 1*(1-att_map**0.7).reshape(att_map.shape + (1,))*img + (att_map**0.7).reshape(att_map.shape+(1,)) * att_map_v
    return att_map
项目:mrflow    作者:jswulff    | 项目源码 | 文件源码
def structure2image(structure, rigidity_refined,cmap='hot', structure_min=None, structure_max=None):
    if structure_min is None:
        structure_min = np.percentile(structure[rigidity_refined==1].ravel(), 2)
    if structure_max is None:
        structure_max = np.percentile(structure[rigidity_refined==1].ravel(), 98)
    Istructure = (structure - structure_min) / (structure_max-structure_min)
    Istructure = np.clip(Istructure,0,1)

    cm = plt.get_cmap(cmap)
    Istructure = cm(Istructure)[:,:,:3]*255.0
    Istructure[:,:,0][rigidity_refined==0] = 128
    Istructure[:,:,1][rigidity_refined==0] = 0
    Istructure[:,:,2][rigidity_refined==0] = 128
    return Istructure.astype('uint8')



# Teaser
项目:self-driving-truck    作者:aleju    | 项目源码 | 文件源码
def draw_heatmap_overlay(img, heatmap, alpha=0.5):
    #assert img.shape[0:2] == heatmap.shape[0:2]
    assert len(heatmap.shape) == 2 or (heatmap.ndim == 3 and heatmap.shape[2] == 1)
    assert img.dtype in [np.uint8, np.int32, np.int64]
    assert heatmap.dtype in [np.float32, np.float64]

    if heatmap.ndim == 3 and heatmap.shape[2] == 1:
        heatmap = np.squeeze(heatmap)

    if img.shape[0:2] != heatmap.shape[0:2]:
        heatmap_rs = np.clip(heatmap * 255, 0, 255).astype(np.uint8)
        heatmap_rs = ia.imresize_single_image(heatmap_rs[..., np.newaxis], img.shape[0:2], interpolation="nearest")
        heatmap = np.squeeze(heatmap_rs) / 255.0

    cmap = plt.get_cmap('jet')
    heatmap_cmapped = cmap(heatmap)
    #img_heatmaps_cmapped = img_heatmaps_cmapped[:, :, 0:3]
    heatmap_cmapped = np.delete(heatmap_cmapped, 3, 2)
    #heatmap_cmapped = np.clip(heatmap_cmapped * 255, 0, 255).astype(np.uint8)
    heatmap_cmapped = heatmap_cmapped * 255
    mix = (1-alpha) * img + alpha * heatmap_cmapped
    mix = np.clip(mix, 0, 255).astype(np.uint8)
    return mix
项目:picasso    作者:jungmannlab    | 项目源码 | 文件源码
def histtoImage(self, image):
        cmap = np.uint8(np.round(255 * plt.get_cmap('magma')(np.arange(256))))
        image /= image.max()
        image = np.minimum(image, 1.0)
        image = np.round(255 * image).astype('uint8')
        Y, X = image.shape
        self._bgra = np.zeros((Y, X, 4), dtype=np.uint8, order='C')
        self._bgra[..., 0] = cmap[:, 2][image]
        self._bgra[..., 1] = cmap[:, 1][image]
        self._bgra[..., 2] = cmap[:, 0][image]
        qimage = QtGui.QImage(self._bgra.data, X, Y, QtGui.QImage.Format_RGB32)

        qimage = qimage.scaled(self.viewxy.width(), np.round(self.viewxy.height()*Y/X), QtCore.Qt.KeepAspectRatioByExpanding)
        pixmap = QtGui.QPixmap.fromImage(qimage)

        return pixmap
项目:picasso    作者:jungmannlab    | 项目源码 | 文件源码
def render_single_channel(self, kwargs, autoscale=False, use_cache=False, cache=True):
        locs = self.locs[0]
        if hasattr(locs, 'group'):
            locs = [locs[self.group_color == _] for _ in range(N_GROUP_COLORS)]
            return self.render_multi_channel(kwargs, autoscale=autoscale, locs=locs, use_cache=use_cache)
        if use_cache:
            n_locs = self.n_locs
            image = self.image
        else:
            n_locs, image = render.render(locs, **kwargs)
        if cache:
            self.n_locs = n_locs
            self.image = image
        image = self.scale_contrast(image, autoscale=autoscale)
        image = self.to_8bit(image)
        Y, X = image.shape
        #cmap = self.window.display_settings_dialog.colormap.currentText() TODO: selection of colormap?
        cmap = 'hot'
        cmap = np.uint8(np.round(255 * plt.get_cmap(cmap)(np.arange(256))))
        self._bgra = np.zeros((Y, X, 4), dtype=np.uint8, order='C')
        self._bgra[..., 0] = cmap[:, 2][image]
        self._bgra[..., 1] = cmap[:, 1][image]
        self._bgra[..., 2] = cmap[:, 0][image]
        return self._bgra
项目:textcatvis    作者:cod3licious    | 项目源码 | 文件源码
def test_distinctive_computations(distinctive_fun=distinctive_fun_diff, fun_name='Rate difference'):
    """
    given a function to compute the "distinctive score" of a word given its true and false positive rate,
    plot the distribution of scores (2D) corresponding to the different tpr and fpr
    """
    # make a grid of possible tpr and fpr combinations
    import matplotlib.pyplot as plt
    x, y = np.linspace(0, 1, 101), np.linspace(1, 0, 101)
    fpr, tpr = np.meshgrid(x, y)
    score = distinctive_fun(tpr, fpr)
    plt.figure()
    plt.imshow(score, cmap=plt.get_cmap('viridis'))
    plt.xlabel('FPR$_c(t_i)$')
    plt.ylabel('TPR$_c(t_i)$')
    plt.xticks(np.linspace(0, 101, 11), np.linspace(0, 1, 11))
    plt.yticks(np.linspace(0, 101, 11), np.linspace(1, 0, 11))
    plt.title('Score using %s' % fun_name)
    plt.colorbar()
项目:BlueLines    作者:JacksYou    | 项目源码 | 文件源码
def show_hexbin(self, query):
        """shows hexbin plot over map

        Args: 
            query: name of sql
        """
        self.load()
        data = pd.read_sql_query(con=self.con, sql=query)
        points = self.gen_points(data, self.data_map)
        hx = self.base_map.hexbin(
            np.array([geom.x for geom in points]),
            np.array([geom.y for geom in points]),
            gridsize=275,
            bins='log',
            mincnt=1,
            edgecolor='none',
            alpha=1.,
            lw=0.2,
            cmap=plt.get_cmap('afmhot'))
        plt.tight_layout()
        plt.show()
项目:BlueLines    作者:JacksYou    | 项目源码 | 文件源码
def split_colormap(self, colormap, n):
        """splits map by colour

        Args:
            colormap: chloropleth map
            n: colours
        Returns:
            portion of split map
        """
        if type(colormap) == str:
            colormap = cm.get_cmap(colormap)
        colors = np.concatenate((np.linspace(0, 1., n), (0., 0., 0., 0.)))
        rgb_alpha = colormap(colors)
        indices = np.linspace(0, 1., n + 1)
        color_dict = {}
        for color, key in enumerate(('red', 'green', 'blue')):
            color_dict[key] = [(indices[i], rgb_alpha[i - 1, color], rgb_alpha[i, color]) for i in range(n + 1)]
        return LinearSegmentedColormap(colormap.name + "_%d" % n, color_dict, 1024)
项目:Captcha-recognition-TF    作者:dukn    | 项目源码 | 文件源码
def view_(_pred,_lable):

    fname = ['Captcha/lv3/%i.jpg' %i for i in range(20)]
    img = []
    for fn in fname:
        img.append(Image.open(open(fn)))
        #img.append(misc.imread(fn).astype(np.float))
    for i in range(len(img)):
        pylab.subplot(4,5,i+1); pylab.axis('off')

        pylab.imshow(img[i])
        #pylab.imshow( np.dot(np.array(img[i])[...,:3],[0.299,0.587,0.114]) , cmap=plt.get_cmap("gray"))
        #pylab.text(40,60,_pred[i],color = 'b')
        if ( _pred[i] == _lable[i] ):
            pylab.text(40,65,_pred[i],color = 'b',size = 15)
        else:
            pylab.text(40,65,_pred[i],color = 'r',size = 15)

        pylab.text(40,92,_lable[i],color = 'g',size = 15)

    pylab.show()
项目:ATLeS    作者:liffiton    | 项目源码 | 文件源码
def plot_heatmap(ax, xpoints, ypoints, nbins, title=None, maxcount=None):
    ''' Plot a heatmap of the given data on on the given axes. '''
    # imshow expects y,x for the image, but x,y for the extents,
    # so we have to manage that here...
    bins = np.concatenate( (np.arange(0,1.0,1.0/nbins), [1.0]) )
    heatmap, yedges, xedges = np.histogram2d(ypoints, xpoints, bins=bins)
    extent = [xedges[0],xedges[-1], yedges[0], yedges[-1]]
    # make sure we always show the full extent of the tank and the full extent of the data,
    # whichever is wider.
    ax.set_xlim(min(0, xedges[0]), max(1, xedges[-1]))
    ax.set_ylim(min(0, yedges[0]), max(1, yedges[-1]))
    if title:
        ax.set_title(title)
    if maxcount is not None:
        norm = Normalize(0, maxcount)
    else:
        norm = None
    return ax.imshow(heatmap, extent=extent, cmap=plt.get_cmap('hot'), origin='lower', interpolation='nearest', norm=norm)
项目:nodeembedding-to-communityembedding    作者:andompesta    | 项目源码 | 文件源码
def _pos_coloring(G, norm_pos):
    '''
    Coloring function based on the position of the nodes
    :param G: Graph
    :param norm_pos: diict -> node_id: 2d node position
    :return: Color for each node
    '''
    nodes_order = []
    for node_id, value in zip(G.nodes(), norm_pos):
        nodes_order.append((node_id, value))

    nodes_order = sorted(nodes_order, key=lambda x: x[1])


    color_map = list(plt.get_cmap(CAMP)(np.linspace(0.0, 1, G.number_of_nodes())))
    nodes_color = np.zeros((G.number_of_nodes(), 4))

    for color_index, (node_id, norm_value) in enumerate(nodes_order):
        nodes_color[node_id - 1] = color_map[color_index]
    return nodes_color
项目:nodeembedding-to-communityembedding    作者:andompesta    | 项目源码 | 文件源码
def _binary_commonity(G, label):
    '''
    Coloring function based on the label
    NB. label have to be binary
    :param G: Graph
    :param label: list of nodes length. for each node represent its label
    :return: list of the color for each node
    '''
    color_map = list(plt.get_cmap(CAMP)(np.linspace(0.0, 1, 4)))
    nodes_color = np.zeros((G.number_of_nodes(), 4))

    for index, node_id in enumerate(sorted(list(G.nodes()))):
        if label[index] == 1:
            nodes_color[index] = color_map[0]
        elif label[index] == 2:
            nodes_color[index] = color_map[-1]
        else:
            ValueError("Label is not binary")
    return nodes_color
项目:kaggle-dstl-satellite-imagery-feature-detection    作者:alno    | 项目源码 | 文件源码
def plot_prediction(image_id, pred_id, cls=0):
    image = np.load('cache/images/%s.npy' % image_id)
    pred = np.load('cache/preds/%s.npy' % image_id)

    xymax = (grid_sizes.loc[image_id, 'xmax'], grid_sizes.loc[image_id, 'ymin'])

    plt.figure()

    ax1 = plt.subplot(131)
    ax1.set_title('image_id:%s' % image_id)
    ax1.imshow(image[1, :, :], cmap=plt.get_cmap('gray'))
    ax2 = plt.subplot(132)
    ax2.set_title('predict bldg pixels')
    ax2.imshow(pred[cls], cmap=plt.get_cmap('hot'))
    ax3 = plt.subplot(133)
    ax3.set_title('predict bldg polygones')
    ax3.imshow(poly_to_mask(mask_to_poly(pred[cls], xymax), image.shape[1:], xymax), cmap=plt.get_cmap('hot'))

    plt.title("%s - class %d" % (pred_id, cls))
    plt.show()
项目:gail-driver    作者:sisl    | 项目源码 | 文件源码
def render(self):
        plt.ion()
        plt.show()

        self.ax.cla()

        img = self.j.render(self.simparams, np.zeros(
            (500, 500)).astype('uint32'))
        #img=self.j.retrieve_frame_data(500, 500, self.simparams)
        self.ax.imshow(img, cmap=plt.get_cmap('bwr'))
        #self.ax.imshow(img, cmap=plt.get_cmap('seismic'))

        plt.draw()

        plt.pause(1e-6)

        return
项目:gail-driver    作者:sisl    | 项目源码 | 文件源码
def render(self):
        # plt.ion()
        # plt.show()

        # self.ax.cla()

        # img = self.j.render(self.simparams, np.zeros((500,500)).astype('uint32'))
        # #img=self.j.retrieve_frame_data(500, 500, self.simparams)
        # self.ax.imshow(img, cmap=plt.get_cmap('bwr'))
        # #self.ax.imshow(img, cmap=plt.get_cmap('seismic'))

        # plt.draw()

        # plt.pause(1e-6)

        return
项目:DLDisambiguation    作者:Labyrinth108    | 项目源码 | 文件源码
def plot_conv(sess, t_vars, name):
    var_conv = [v for v in t_vars if name in v.name]
    W = var_conv[0]  # [2, 2, 1, 8]
    W = sess.run(W)

    length = W.shape[-1]

    row_n = 2 if length == 8 else 4
    col_n = length / row_n
    plt.subplots(row_n, col_n)

    for i in range(length):
        axes = plt.subplot(row_n, col_n, i + 1)
        map = W[:, :, 0, i]
        plt.imshow(map,cmap=plt.cm.magma)
        # plt.imshow(map, cmap=plt.get_cmap('gray'))
        # plt.xlabel(i)
        axes.set_xticks([])
        axes.set_yticks([])
    # plt.colorbar(fraction=0.046, pad=0.04)
    plt.savefig(dir_ + "map" + name + ".jpg")
项目:storygraph    作者:hurrycane    | 项目源码 | 文件源码
def draw_graph(edges):
    G = nx.DiGraph()
    G.add_edges_from(edges)

    values = [1.0 for node in G.nodes()]

    # Specify the edges you want here
    edge_colours = ['black' for edge in G.edges()]
    black_edges = [edge for edge in G.edges()]

    # Need to create a layout when doing
    # separate calls to draw nodes and edges
    pos = nx.spring_layout(G)
    nx.draw_networkx_nodes(G, pos, cmap=plt.get_cmap('Reds'), node_color = values, node_size=4800)
    nx.draw_networkx_edges(G, pos, edgelist=black_edges, arrows=True)
    nx.draw_networkx_labels(G,pos,font_size=12,font_family='sans-serif')

    plt.axis('off')
    plt.show()


# In[183]:
项目:parametrix    作者:vincentchoqueuse    | 项目源码 | 文件源码
def plot_cost_function(self,Y,ranges,coef_display=1):
        x0,fval,grid,Jout=brute(self.cost_function,ranges, args=(Y,),full_output=True)
        Ndim,N1,N2=grid.shape
        if Ndim==1:
            print("plot")

        if Ndim==2:
            fig = plt.figure()
            ax = fig.gca(projection='3d')
            surf = ax.plot_surface(coef_display*grid[0],coef_display*grid[1],Jout,cmap=plt.get_cmap("hot"))
            plt.xlabel("Parameter1")
            plt.ylabel("Parameter2")

        if Ndim >2:
            raise ValueError("Too much dimensions (this method can only plot <=2 dimensions)")

        return x0
项目:TikZ    作者:ellisk42    | 项目源码 | 文件源码
def animateMatrices(matrices,outputFilename = None):
    fig = plot.figure() # make figure
    im = plot.imshow(matrices[0], cmap=plot.get_cmap('bone'), vmin=0.0, vmax=1.0)

    # function to update figure
    def updatefig(j):
        # set the data in the axesimage object
        im.set_array(matrices[j])
        # return the artists set
        return im,
    # kick off the animation
    ani = animation.FuncAnimation(fig, updatefig, frames=range(len(matrices)), 
                              interval=50, blit=True)
    if outputFilename != None:
        ani.save(outputFilename, dpi = 80,writer = 'imagemagick')
    plot.show()
项目:crime_prediction    作者:livenb    | 项目源码 | 文件源码
def cmap_discretize(cmap, N):
    """
    Return a discrete colormap from the continuous colormap cmap.

        cmap: colormap instance, eg. cm.jet.
        N: number of colors.

    Example
        x = resize(arange(100), (5,100))
        djet = cmap_discretize(cm.jet, 5)
        imshow(x, cmap=djet)

    """
    if type(cmap) == str:
        cmap = get_cmap(cmap)
    colors_i = np.concatenate((np.linspace(0, 1., N), (0., 0., 0., 0.)))
    colors_rgba = cmap(colors_i)
    indices = np.linspace(0, 1., N + 1)
    cdict = {}
    for ki, key in enumerate(('red', 'green', 'blue')):
        cdict[key] = [(indices[i], colors_rgba[i - 1, ki], colors_rgba[i, ki]) for i in xrange(N + 1)]
    return LinearSegmentedColormap(cmap.name + "_%d" % N, cdict, 1024)
项目:Handwriting-Recognition    作者:samkit-jain    | 项目源码 | 文件源码
def recognise_letter():
    letter_loc = get_image_src()

    for loc in letter_loc:
        letter_image = mpimg.imread(loc)

        gray_letter = np.dot(letter_image[...,:3], [0.299, 0.587, 0.114])
        letter_display = gray_letter

        gray_letter = gray_letter.flatten()


        for i in range(len(gray_letter)):
            gray_letter[i] = gray_letter[i]
            gray_letter[i] = round(gray_letter[i], 8)

        f = open('classifier_knn165.pickle', 'rb')
        clf = pickle.load(f)
        f.close()

        plt.figure()
        plt.imshow(letter_display, cmap=plt.get_cmap('gray'))
        plt.title('letter is ' + clf.predict([gray_letter])[0])

    plt.show()
项目:alchemy    作者:voidrank    | 项目源码 | 文件源码
def draw_attention(img, *masks):
    cmap = plt.get_cmap('jet')
    imgs = []
    for mask in masks:
        # convert to heat map
        rgba_img = cmap(mask)
        rgb_img = np.delete(rgba_img, 3, 2)
        rgb_img = (rgb_img * 255)
        # mean
        mean_img = ((rgb_img + img) / 2).astype(np.uint8)
        # convert to PIL.Image
        mean_img = Image.fromarray(mean_img, "RGB")
        imgs.append(mean_img)

    return imgs
项目:GraphTime    作者:GlooperLabs    | 项目源码 | 文件源码
def draw(self, layout='circular', figsize=None):
        """Draw all graphs that describe the DGM in a common figure

        Parameters
        ----------
        layout : str
            possible are 'circular', 'shell', 'spring'
        figsize : tuple(int)
            tuple of two integers denoting the mpl figsize

        Returns
        -------
        fig : figure
        """
        layouts = {
            'circular': nx.circular_layout,
            'shell': nx.shell_layout,
            'spring': nx.spring_layout
        }
        figsize = (10, 10) if figsize is None else figsize
        fig = plt.figure(figsize=figsize)
        rocls = np.ceil(np.sqrt(len(self.graphs)))
        for i, graph in enumerate(self.graphs):
            ax = fig.add_subplot(rocls, rocls, i+1)
            ax.set_title('Graph ' + str(i+1))
            ax.axis('off')
            ax.set_frame_on(False)
            g = graph.nxGraph
            weights = [abs(g.edge[i][j]['weight']) * 5 for i, j in g.edges()]
            nx.draw_networkx(g, pos=layouts[layout](g), ax=ax, edge_cmap=plt.get_cmap('Reds'),
                             width=2, edge_color=weights)
        return fig
项目:GraphTime    作者:GlooperLabs    | 项目源码 | 文件源码
def draw(self, layout='circular', figsize=None):
        """Draw graph in a matplotlib environment

        Parameters
        ----------
        layout : str
            possible are 'circular', 'shell', 'spring'
        figsize : tuple(int)
            tuple of two integers denoting the mpl figsize

        Returns
        -------
        fig : figure
        """
        layouts = {
            'circular': nx.circular_layout,
            'shell': nx.shell_layout,
            'spring': nx.spring_layout
        }
        figsize = (10, 10) if figsize is None else figsize
        fig = plt.figure(figsize=figsize)
        ax = fig.add_subplot(1, 1, 1)
        ax.axis('off')
        ax.set_frame_on(False)
        g = self.nxGraph
        weights = [abs(g.edge[i][j]['weight']) * 5 for i, j in g.edges()]
        nx.draw_networkx(g, pos=layouts[layout](g), ax=ax, edge_cmap=plt.get_cmap('Reds'),
                         width=2, edge_color=weights)
        return fig
项目:structured-output-ae    作者:sbelharbi    | 项目源码 | 文件源码
def plot_ae_tracker(self, tracker, path):
        '''Plot the loss, lr of each auto-encoder.

        tracker: list of tuple (loss, lr)
        '''
        nbr = len(tracker)
        f, (loss, lr) = plt.subplots(2, sharex=True, sharey = False)
        # plotting
        cmap = plt.get_cmap('gnuplot')
        colors = [cmap(i) for i in np.linspace(0,1, nbr)]
        floating = 3
        prec = "%." + str(floating) + "f"

        for i, color in enumerate(colors, start=1):
            loss_ = np.asarray(tracker[i-1][0])
            end_loss =  prec % np.float(loss_[-1])
            lr_ = np.asarray(tracker[i-1][1])
            end_lr = prec % np.float(lr_[-1])
            loss.plot(loss_, color = color, label='loss ae_' + str(i) + ':' + str(end_loss))
            lr.plot(lr_, color = color, label='lr ae_'+ str(i) + ':' + str(end_lr))

        loss.legend(fancybox=True, shadow=True, prop={'size':6})
        lr.legend(fancybox=True, shadow=True, prop={'size':6})
        loss.set_title('loss and learing rate during the auo-encoders pre-training.')
        lr.set_xlabel(u'n° epoch')
        lr.set_ylabel('lambda')
        loss.set_ylabel('loss')
        f.savefig(path, bbox_inches='tight')
项目:robograph    作者:csparpa    | 项目源码 | 文件源码
def prepare_plot(graph):
    """
    Prepares a Matplotlib plot for further handling
    :param graph: datamodel.base.Graph instance
    :return: None
    """
    G = graph.nxgraph

    # Color map for nodes: color is proportional to depth level
    # http://matplotlib.org/examples/color/colormaps_reference.html
    depth_levels_from_root = nx.shortest_path_length(G, graph.root_node)
    vmax = 1.
    colormap = plt.get_cmap('BuGn')
    step = 1./len(graph)
    node_colors = [vmax - step * depth_levels_from_root[n] for n in G.nodes()]

    # Draw!
    # https://networkx.github.io/documentation/networkx-1.10/reference/drawing.html
    pos = nx.spectral_layout(G)
    nx.draw_networkx_labels(G, pos,
                            labels=dict([(n, n.name) for n in G.nodes()]),
                            font_weight='bold',
                            font_color='orangered')
    nx.draw_networkx_nodes(G, pos,
                           node_size=2000,
                           cmap=colormap,
                           vmin=0.,
                           vmax=vmax,
                           node_color=node_colors)
    nx.draw_networkx_edge_labels(G, pos,
                                 edge_labels=dict([((u, v,), d['name']) for u, v, d in G.edges(data=True)]))
    nx.draw_networkx_edges(G, pos,
                           edgelist=[edge for edge in G.edges()],
                           arrows=True)
项目:prysm    作者:brandondube    | 项目源码 | 文件源码
def colorline(x, y, z=None, cmap=plt.get_cmap('Spectral_r'), cmin=None, cmax=None, lw=3):
    '''
    Plot a colored line with coordinates x and y
    Optionally specify colors in the array z
    Optionally specify a colormap, a norm function and a line width
    '''

    cmap = copy(cmap)
    cmap.set_over('k')
    cmap.set_under('k')

    # Default colors equally spaced on [0,1]:
    if z is None:
        z = np.linspace(0.0, 1.0, len(x))

    # Special case if a single number:
    if not hasattr(z, "__iter__"):  # to check for numerical input -- this is a hack
        z = np.array([z])

    z = np.asarray(z)

    segments = make_segments(x, y)
    return LineCollection(segments, array=z, cmap=cmap, norm=plt.Normalize(vmin=cmin, vmax=cmax), linewidth=lw)
项目:discretize    作者:simpeg    | 项目源码 | 文件源码
def plotImage(self, I, ax=None, showIt=False, grid=False, clim=None):
        if self.dim == 3: raise Exception('Use plot slice?')


        import matplotlib.pyplot as plt
        import matplotlib
        from mpl_toolkits.mplot3d import Axes3D
        import matplotlib.colors as colors
        import matplotlib.cm as cmx

        if ax is None: ax = plt.subplot(111)
        jet = cm = plt.get_cmap('jet')
        cNorm  = colors.Normalize(
            vmin=I.min() if clim is None else clim[0],
            vmax=I.max() if clim is None else clim[1])

        scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)
        ax.set_xlim((self.x0[0], self.h[0].sum()))
        ax.set_ylim((self.x0[1], self.h[1].sum()))
        for ii, node in enumerate(self._sortedCells):
            x0, sz = self._cellN(node), self._cellH(node)
            ax.add_patch(plt.Rectangle((x0[0], x0[1]), sz[0], sz[1], facecolor=scalarMap.to_rgba(I[ii]), edgecolor='k' if grid else 'none'))
            # if text: ax.text(self.center[0],self.center[1],self.num)
        scalarMap._A = []  # http://stackoverflow.com/questions/8342549/matplotlib-add-colorbar-to-a-sequence-of-line-plots
        ax.set_xlabel('x')
        ax.set_ylabel('y')
        if showIt: plt.show()
        return [scalarMap]
项目:discretize    作者:simpeg    | 项目源码 | 文件源码
def plotImage(
        self, I, ax=None, showIt=False, grid=False, clim=None
    ):
        if self.dim == 3:
            raise NotImplementedError('This is not yet done!')

        import matplotlib.pyplot as plt
        import matplotlib
        from mpl_toolkits.mplot3d import Axes3D
        import matplotlib.colors as colors
        import matplotlib.cm as cmx

        if ax is None:
            ax = plt.subplot(111)

        jet = cm = plt.get_cmap('jet')
        cNorm  = colors.Normalize(
            vmin=I.min() if clim is None else clim[0],
            vmax=I.max() if clim is None else clim[1])

        scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)
        # ax.set_xlim((self.x0[0], self.h[0].sum()))
        # ax.set_ylim((self.x0[1], self.h[1].sum()))

        Nx = self.r(self.gridN[:, 0], 'N', 'N', 'M')
        Ny = self.r(self.gridN[:, 1], 'N', 'N', 'M')
        cell = self.r(I, 'CC', 'CC', 'M')

        for ii in range(self.nCx):
            for jj in range(self.nCy):
                I = [ii, ii+1, ii+1, ii]
                J = [jj, jj, jj+1, jj+1]
                ax.add_patch(plt.Polygon(np.c_[Nx[I, J], Ny[I, J]], facecolor=scalarMap.to_rgba(cell[ii, jj]), edgecolor='k' if grid else 'none'))

        scalarMap._A = []  # http://stackoverflow.com/questions/8342549/matplotlib-add-colorbar-to-a-sequence-of-line-plots
        ax.set_xlabel('x')
        ax.set_ylabel('y')
        if showIt:
            plt.show()
        return [scalarMap]
项目:tf-image-segmentation    作者:VittalP    | 项目源码 | 文件源码
def _discrete_matshow_adaptive(data, labels_names=[], title=""):
    """Displays segmentation results using colormap that is adapted
    to a number of classes. Uses labels_names to write class names
    aside the color label. Used as a helper function for 
    visualize_segmentation_adaptive() function.

    Parameters
    ----------
    data : 2d numpy array (width, height)
        Array with integers representing class predictions
    labels_names : list
        List with class_names
    """

    fig_size = [7, 6]
    plt.rcParams["figure.figsize"] = fig_size

    #get discrete colormap
    cmap = plt.get_cmap('Paired', np.max(data)-np.min(data)+1)

    # set limits .5 outside true range
    mat = plt.matshow(data,
                      cmap=cmap,
                      vmin = np.min(data)-.5,
                      vmax = np.max(data)+.5)

    #tell the colorbar to tick at integers
    cax = plt.colorbar(mat,
                       ticks=np.arange(np.min(data),np.max(data)+1))

    # The names to be printed aside the colorbar
    if labels_names:
        cax.ax.set_yticklabels(labels_names)

    if title:
        plt.suptitle(title, fontsize=15, fontweight='bold')

    plt.show()