• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python colorbar.make_axes函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中matplotlib.colorbar.make_axes函数的典型用法代码示例。如果您正苦于以下问题:Python make_axes函数的具体用法?Python make_axes怎么用?Python make_axes使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了make_axes函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: train_svm

    def train_svm(self):

        width = float(self.sigma.text())
        degree = int(self.degree.text())

        self.axes.clear()
        self.axes.grid(True)
        self.axes.plot(self.data.x1_pos, self.data.x2_pos, 'ro')
        self.axes.plot(self.data.x1_neg, self.data.x2_neg, 'bo')

        # train svm
        labels = self.data.get_labels()
        print type(labels)
        lab = BinaryLabels(labels)
        features = self.data.get_examples()
        train = RealFeatures(features)

        kernel_name = self.kernel_combo.currentText()
        print "current kernel is %s" % (kernel_name)

        if kernel_name == "LinearKernel":
            gk = LinearKernel(train, train)
            gk.set_normalizer(IdentityKernelNormalizer())
        elif kernel_name == "PolynomialKernel":
            gk = PolyKernel(train, train, degree, True)
            gk.set_normalizer(IdentityKernelNormalizer())
        elif kernel_name == "GaussianKernel":
            gk = GaussianKernel(train, train, width)

        cost = float(self.cost.text())

        print "cost", cost
        svm = LibSVM(cost, gk, lab)
        svm.train()
        svm.set_epsilon(1e-2)

        x, y, z = util.compute_output_plot_isolines(svm, gk, train)
        plt=self.axes.pcolor(x, y, z, shading='interp')
        CS=self.axes.contour(x, y, z, [-1,0,1], linewidths=1, colors='black', hold=True)
        #CS=self.axes.contour(x, y, z, linewidths=1, colors='black', hold=True)
        #CS=self.axes.contour(x, y, z, 5, linewidths=1, colors='black', hold=True)
        matplotlib.pyplot.clabel(CS, inline=1, fontsize=10)

        self.axes.set_xlim((-5,5))
        self.axes.set_ylim((-5,5))

        cmap = matplotlib.cm.jet
        norm = mpl.colors.Normalize(numpy.min(z), numpy.max(z))
        print CS.get_clim()
        if not self.cax:
            self.cax, kw = make_axes(self.axes)

# ColorbarBase derives from ScalarMappable and puts a colorbar
# in a specified axes, so it has everything needed for a
# standalone colorbar.  There are many more kwargs, but the
# following gives a basic continuous colorbar with ticks
# and labels.
        cb1 = mpl.colorbar.ColorbarBase(self.cax, cmap=cmap,
                                           norm=norm)
        self.canvas.draw()
开发者ID:42MachineLearning,项目名称:shogun,代码行数:60,代码来源:interactive_svm_demo.py


示例2: plot_orient_quiver

def plot_orient_quiver(data, odata, mask=None, imfile='', fps=1, savename='', figsize=None):
    """ plot_orient_quiver(data, odata, mask=None, imfile='')
    """
    import matplotlib.colors as mcolors
    import matplotlib.colorbar as mcolorbar
    pl.figure(tight_layout=False, figsize=figsize)
    if imfile is not None:
        bgimage = Im.open(extdir+prefix+'_0001.tif' if imfile is '' else imfile)
        pl.imshow(bgimage, cmap=cm.gray, origin='upper')
    #pl.quiver(X, Y, U, V, **kw)
    if mask is None:
        try:
            mask = np.all(np.isfinite(odata['orient']), axis=1)
        except ValueError:
            mask = np.isfinite(odata['orient'])

    n = odata.shape[-1] if odata.ndim > 1 else 1
    ndex = np.repeat(np.arange(mask.sum()), n)
    nz = mcolors.Normalize()
    nz.autoscale(data['f'][mask]/fps)
    qq = pl.quiver(
            data['y'][mask][ndex], data['x'][mask][ndex],
            odata['cdisp'][mask][...,1].flatten(), -odata['cdisp'][mask][...,0].flatten(),
            color=cm.jet(nz(data['f'][mask]/fps)),
            scale=1, scale_units='xy')
    #pl.title(', '.join(imfile.split('/')[-1].split('_')[:-1]) if imfile else '')
    cax,_ = mcolorbar.make_axes(pl.gca())
    cb = mcolorbar.ColorbarBase(cax, cmap=cm.jet, norm=nz)
    cb.set_label('time '+('(s)'if fps > 1 else '(frame)'))
    if savename:
        print "saving to", savename
        pl.savefig(savename)
    pl.show()
    return qq, cb
开发者ID:moji2289,项目名称:square-tracking,代码行数:34,代码来源:orientation.py


示例3: make_plot

def make_plot(data, output_file):

    # Set plot parameters.
    titles = ('Clean Data $(X)$', 'Noisy Data $(Y)$',
              'Reconstruction $(\hat{X})$', 'Residual $(|Y-M\hat{X}|)$')

    # Set vmax when mode = 'obj'.
    if opts.vmax_mode == 'obj':
        opts.vmax = np.max(data)

    # Set the colour levels.
    if isinstance(opts.levels, type(None)):
        colourbin = 0.05
    else:
        colourbin = (opts.vmax - opts.vmin) / opts.levels

    boundaries = np.arange(opts.vmin, opts.vmax, colourbin)
    norm = BoundaryNorm(boundaries, cm.get_cmap(name=opts.cmap).N)

    # Make plot.
    fig, axes = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True)
    for ax, x, title in zip(axes.flat, data, titles):
        if opts.white:
            x[x == 0.0] = np.nan
        im = ax.imshow(x, norm=norm, cmap=opts.cmap, interpolation=opts.interp)
        ax.set_title(title)
        ax.set_adjustable('box-forced')
    cax, kw = make_axes([ax for ax in axes.flat])
    plt.colorbar(im, cax=cax, **kw)

    # Output file.
    plt.savefig(output_file)
    plt.close(fig)
    print 'Output saved to:', output_file
开发者ID:sfarrens,项目名称:python_lib,代码行数:34,代码来源:compare.py


示例4: colorbar

  def colorbar(self, ax=None, **kwargs):
    if ax is None: ax=self.default_axes
    class MyFormatter(Formatter):
      def __init__(self, logscale, vmin, vmax):
        self.logscale = logscale
        self.vmin = vmin
        self.vmax = vmax
        self.scale = 10 **(_fr10(vmax - vmin)[1] - 1)
        if vmax != 0 and \
           numpy.abs((vmin - vmax) / vmax) < 0.01:
          self.offset = vmax
        else:
          self.offset = 0
      def get_offset(self):
        if self.offset != 0:
          return '+%.3g\n x%.3g' % (self.offset, self.scale)
        else:
          return r'x%.3g' % self.scale
      def __call__(self, data, pos=None):
        if self.offset != 0:
          return '%.3g' % ((data - self.offset) / self.scale)
        else:
          return '%.3g' % (data / self.scale)

    if not hasattr(ax, 'colorbarax'):
      ca = ax.get_figure().gca()
      ax.colorbarax, kwargs = mcb.make_axes(ax, **kwargs)
      ax.get_figure().sca(ca)
    color = self.last['color']
    mcb.ColorbarBase(ax=ax.colorbarax, 
           cmap=self.last['cmap'], 
           norm=mcb.colors.Normalize(
             vmin=color.vmin, vmax=color.vmax),
           format = MyFormatter(color.logscale, color.vmin, color.vmax)
           )
开发者ID:rainwoodman,项目名称:gaepsi,代码行数:35,代码来源:gaplot.py


示例5: makeFrameImage

def makeFrameImage(basename, pixels, outputpath):
    """ Create the frame image. """

    x_min = 0

    x_max = 256

    y_min = 0

    y_max = 256

    w = 256

    h = 256

    ## The maximum count value.
    C_max = max(pixels.values())

    # Create the figure.
    plt.close('all')

    figsize = 5.0 #max(radius*0.8, 3.0)

    ## The figure for the frame.
    frfig = plt.figure(1, figsize=(figsize*1.27, figsize), dpi=150, facecolor='w', edgecolor='w')

    ## The frame axes.
    frfigax = frfig.add_subplot(111, axisbg='#222222')

    # Add the frame background (blue).
    frfigax.add_patch(plt.Rectangle((0,0),256,256,facecolor='#82bcff'))

    # Add a grid.
    plt.grid(1)

    # Select the "hot" colour map for the pixel counts.

    cmap = plt.cm.hot

    colax, _ = colorbar.make_axes(plt.gca())

    col_max = 10*(np.floor(C_max/10.)+1)

    colorbar.ColorbarBase(colax,cmap=cmap,norm=colors.Normalize(vmin=0,vmax=col_max))

    # Loop over the pixels and plot them.
    for X, C in pixels.iteritems():
        x = X % 256; y = X / 256
        scaled_C = float(C)/float(col_max)
        frfigax.add_patch(plt.Rectangle((x,y),1,1,edgecolor=cmap(scaled_C),facecolor=cmap(scaled_C)))

    # Set the axis limits based on the cluster radius.
    b = 3 # border

    frfigax.set_xlim([0 - b, 256 + 3])
    frfigax.set_ylim([0 - b, 256 + 3])

    # Save the figure.
    frfig.savefig(outputpath + "/%s.png" % (basename))
开发者ID:CERNatschool,项目名称:cluster-sorter,代码行数:59,代码来源:visualisation.py


示例6: deconvolve

def deconvolve(fluor, pos, prctile=10, A0=0.15, lamb0=0.15, do_plot=True):

    nc, nt = fluor.shape

    # euclidean distances
    dist = all_distances(pos)
    ij, distvec = submission.adjacency2vec(dist)

    # Pearson correlation coefficients for small fluorescence values
    corr = threshold_corr(fluor, prctile)
    ij, corrvec = submission.adjacency2vec(corr)

    # from Stetter et al 2012
    # A = 0.15
    # lamb = 0.15
    A, lamb = fit_gauss_blur(distvec, corrvec, A0, lamb0)

    # convolution matrix (nc x nc)
    C = gauss((A / 2., lamb), dist)   # why divide by 2?

    # # we set the diagonal to zero, since we don't consider a cell's own
    # # fluorescence
    # C[np.diag_indices(nc)] = 0

    # F + CF    = F_sc
    # (I + C)F  = F_sc
    deconv = np.linalg.solve((np.eye(nc) + C), fluor)

    if do_plot:

        corr2 = threshold_corr(deconv, prctile)
        ij, corrvec2 = submission.adjacency2vec(corr2)
        A2, lamb2 = fit_gauss_blur(distvec, corrvec2, A0, lamb0)

        fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, sharey=True,
                                       figsize=(8, 8))

        plot_hist_fit(distvec, corrvec, (A, lamb), ax=ax1)
        plot_hist_fit(distvec, corrvec2, (A2, lamb2), ax=ax2)

        ax1.set_title('Original', fontsize=18)
        ax2.set_title(      'Deconvolved', fontsize=18)

        ax2.set_xlabel('Distance (mm)', fontsize=14)
        ax1.set_ylabel('Correlation coefficient', fontsize=14)
        ax2.set_ylabel('Correlation coefficient', fontsize=14)

        cax, kw = colorbar.make_axes((ax1, ax2))
        ax2.images[0].set_clim(ax1.images[0].get_clim())
        cb = plt.colorbar(ax1.images[0], cax=cax, **kw)
        cb.set_label('Density')

        plt.show()

    return deconv
开发者ID:alimuldal,项目名称:konnectomics-public,代码行数:55,代码来源:deconvolution.py


示例7: plot3DGrid

def plot3DGrid(scores, paramsToPlot, keysToPlot, scoreLabel, vrange):
    """
    Plots a grid of heatmaps of scores, over the paramsToPlot
    :param scores: A list of scores, estimated using parallelizeScore
    :param paramsToPlot: The parameters to plot, chosen automatically by plotScores
    :param scoreLabel: The specified score label (dependent on scoring metric used)
    :param vrange: The visible range of the heatmap (range you wish the heatmap to be specified over)
    """
    vmin = np.min(scores)
    vmax = np.max(scores)
    scoreGrid = np.reshape(scores, (len(paramsToPlot[keysToPlot[0]]), len(
        paramsToPlot[keysToPlot[1]]), len(paramsToPlot[keysToPlot[2]])))

    smallest_dim = np.argmin(scoreGrid.shape)
    if smallest_dim != 2:
        scoreGrid = np.swapaxes(scoreGrid, smallest_dim, 2)
        keysToPlot[smallest_dim], keysToPlot[2] = keysToPlot[2], keysToPlot[smallest_dim]

    nelements = scoreGrid.shape[2]
    nrows = np.floor(nelements ** 0.5).astype(int)
    ncols = np.ceil(1. * nelements / nrows).astype(int)
    fig, axes = plt.subplots(nrows=nrows, ncols=ncols, sharex='all', sharey='all', figsize=(int(round(len(
        paramsToPlot[keysToPlot[1]]) * ncols * 1.33)), int(round(len(paramsToPlot[keysToPlot[0]]) * nrows * 1.33))))
    i = 0
    for ax in axes.flat:
        if vrange is not None:
            im = ax.imshow(scoreGrid[:, :, i], cmap='jet',
                           vmin=vrange[0], vmax=vrange[1])
        else:
            im = ax.imshow(scoreGrid[:, :, i],
                           cmap='jet', vmin=vmin, vmax=vmax)
        ax.set_xlabel(keysToPlot[1])
        ax.set_xticks(np.arange(len(paramsToPlot[keysToPlot[1]])))
        ax.set_xticklabels(paramsToPlot[keysToPlot[1]])
        ax.set_ylabel(keysToPlot[0])
        ax.set_yticks(np.arange(len(paramsToPlot[keysToPlot[0]])))
        ax.set_yticklabels(paramsToPlot[keysToPlot[0]])
        ax.set_title(keysToPlot[2] + ' = ' +
                     str(paramsToPlot[keysToPlot[2]][i]))
        ax.spines["top"].set_visible(False)
        ax.spines["right"].set_visible(False)
        ax.spines["bottom"].set_visible(False)
        ax.spines["left"].set_visible(False)
        i += 1
        if i == nelements:
            break
    if scoreLabel is not None:
        fig.suptitle(scoreLabel, fontsize=18)
    else:
        fig.suptitle('Score', fontsize=18)
    fig.subplots_adjust(right=0.8)
    cbar = cb.make_axes(ax, location='right', fraction=0.03)
    fig.colorbar(im, cax=cbar[0])
    plt.show()
开发者ID:Michal-Fularz,项目名称:decision_tree,代码行数:54,代码来源:plot.py


示例8: _create_colorbars

def _create_colorbars(fig, axes, qm, ticks):
    """
    """

    for i in range(axes.shape[1]):
        parents = [ax for ax in axes[:,i].flat]
        cax, kw = make_axes(parents, location='bottom', pad=0.03, shrink=1.0,
                           fraction=0.01, aspect=20)
        fig.colorbar(mappable=qm[i], cax=cax, orientation='horizontal',
                     ticks=ticks[i], drawedges=False, spacing='uniform')

    return
开发者ID:kirknorth,项目名称:lab-scripts,代码行数:12,代码来源:plot_csaprinnerC1mmcgI7.b1.py


示例9: colorbar

    def colorbar(self, mappable, cax=None, ax=None, **kw):
        """
        Create a colorbar for a ScalarMappable instance, *mappable*.

        Documentation for the pylab thin wrapper:
        %(colorbar_doc)s
        """
        if ax is None:
            ax = self.gca()
        use_gridspec = kw.pop("use_gridspec", True)
        if cax is None:
            if use_gridspec and isinstance(ax, SubplotBase):
                cax, kw = cbar.make_axes_gridspec(ax, **kw)
            else:
                cax, kw = cbar.make_axes(ax, **kw)
        cax.hold(True)
        cb = cbar.colorbar_factory(cax, mappable, **kw)

        self.sca(ax)
        return cb
开发者ID:jesper-friis,项目名称:matplotlib,代码行数:20,代码来源:figure.py


示例10: _init_plot_eval

    def _init_plot_eval(self):
        from panobbgo.ui import NavigationToolbar
        from matplotlib import colorbar
        import gtk
        mx = self.problem.dim
        vbox = gtk.VBox(False, 0)
        if mx <= 1:
            vbox.add(gtk.Label("not enough dimensions"))
            return
        self.eval_canvas, fig = self.ui.mk_canvas()
        self.eval_ax = fig.add_subplot(111)
        self.eval_cb_ax, _ = colorbar.make_axes(self.eval_ax)

        spinner_hbox = gtk.HBox(gtk.FALSE, 5)

        def mk_cb(l):
            cb = gtk.combo_box_new_text()
            [cb.append_text('Axis %d' % i) for i in range(0, mx)]
            cb.set_active(mk_cb.i)
            mk_cb.i += 1
            spinner_hbox.add(gtk.Label(l))
            spinner_hbox.add(cb)
            return cb
        mk_cb.i = 0

        cb_0 = mk_cb("X Coord:")
        cb_1 = mk_cb("Y Coord:")

        for cb in [cb_0, cb_1]:
            cb.connect('changed', self.on_eval_spinner, cb_0, cb_1)

        self.eval_btn = btn = gtk.Button("Redraw")
        btn.connect('clicked', self.on_eval_spinner, cb_0, cb_1)
        spinner_hbox.add(btn)

        vbox.pack_start(self.eval_canvas, True, True)
        vbox.pack_start(spinner_hbox, False, False)
        self.toolbar = NavigationToolbar(self.eval_canvas, self)
        vbox.pack_start(self.toolbar, False, False)
        return "Values", vbox
开发者ID:haraldschilly,项目名称:panobbgo,代码行数:40,代码来源:best.py


示例11: plotSolution

	def plotSolution(self, heatExch, axes, var, zmin = None, zmax = None, cmap = cm.jet):
		vertexIDs = self.mesh._orderedCellVertexIDs
		vertexCoords = self.mesh.vertexCoords
		xCoords = np.take(vertexCoords[0], vertexIDs)
		yCoords = np.take(vertexCoords[1], vertexIDs)
		polys = []
		for x, y in zip(xCoords.swapaxes(0,1), yCoords.swapaxes(0,1)):
			if hasattr(x, 'mask'):
				x = x.compressed()
			if hasattr(y, 'mask'):
				y = y.compressed()
			polys.append(zip(x,y))
			
		from matplotlib.collections import PolyCollection
		# Set limits
		xmin = xCoords.min()
		xmax = xCoords.max()
		ymin = yCoords.min()
		ymax = yCoords.max()
		axes.set_xlim(xmin=xmin, xmax=xmax)
		axes.set_ylim(ymin=ymin, ymax=ymax)
		Z = var.value
		if (zmin is None):
			zmin = np.min(Z)
		if (zmax is None):
			zmax = np.max(Z)

		norm = Normalize(zmin, zmax)
		collection = PolyCollection(polys, cmap = cmap, norm = norm)
		collection.set_linewidth(0.)
		axes.add_collection(collection)

		cbax, _ = colorbar.make_axes(axes)
		cb = colorbar.ColorbarBase(cbax, cmap=cmap,
			norm = norm)
		cb.set_label('Temperature [K]')
 		collection.set_array(np.array(Z))
开发者ID:SysMo,项目名称:SmoWeb,代码行数:37,代码来源:HeatExchangerSolver.py


示例12: saveDamagePlot

	def saveDamagePlot(self, folderPath, dataName, channelName, nLevels):
		import pylab as plt
		from matplotlib.colors import LogNorm
		import matplotlib.colorbar as colorbar 
		import matplotlib.cm as cm
		
		maxDamage = self.damage.max()
		levels = np.logspace(np.log10(maxDamage / 100.), np.log10(maxDamage), nLevels )
		norm = LogNorm(vmin = maxDamage / 100., vmax = maxDamage)
		cmap = cm.get_cmap('jet', nLevels)
		
		fig = plt.figure()
		axes = fig.add_subplot(111)
		axes.contourf(self.damage, extent = (0, 180, 0, 180), 
				norm = norm, cmap = cmap, levels = levels)
		#axes.contourf(self.damage)
		cbax, _ = colorbar.make_axes(axes)
		cb = colorbar.ColorbarBase(cbax, cmap=cmap,	norm = norm)
		cb.set_label('Damage [-]')
		
		axes.set_xlabel(r'$\theta$ [deg]')
		axes.set_ylabel(r'$\varphi$ [deg]')
		axes.set_title('Damage for {}, channel {}'.format(dataName, channelName))
		fig.savefig(os.path.join(folderPath, '{}_{}.png'.format(dataName, channelName)))
开发者ID:SysMo,项目名称:SmoWeb,代码行数:24,代码来源:MultiaxialDamangeCalculator.py


示例13: make_frame_image

def make_frame_image(basename, pixels, outputpath, pixel_mask = {}):
    """ Create the frame image. """

    # The frame limits.
    x_min = 0; x_max = 256; y_min = 0; y_max = 256

    ## The frame width.
    w = 256

    ## The frame height.
    h = 256

    # Remove the masked pixels.
    for X in pixel_mask.keys():
        if X in pixels.keys():
            del pixels[X]

    ## The maximum count value.
    C_max = max(pixels.values())

    # Create the figure.
    plt.close('all')

    ## The size of the figure.
    figsize = 5.0

    ## The figure for the frame.
    frfig = plt.figure(1, figsize=(figsize*1.27, figsize), dpi=150, facecolor='w', edgecolor='w')

    ## The frame axes.
    frfigax = frfig.add_subplot(111, axisbg='#222222')

    # Add the frame background (blue).
    frfigax.add_patch(plt.Rectangle((0,0),256,256,facecolor='#82bcff'))

    # Add a grid.
    plt.grid(1)

    # Select the "hot" colour map for the pixel counts.

    ## The colour map.
    cmap = plt.cm.hot

    ## The colour bar axis.
    colax, _ = colorbar.make_axes(plt.gca())

    ## The maximum value on the colour axis.
    col_max = 10*(np.floor(C_max/10.)+1)
    #
    colorbar.ColorbarBase(colax,cmap=cmap,norm=colors.Normalize(vmin=0,vmax=col_max))

    # Loop over the pixels and plot them.
    for X, C in pixels.iteritems():
        x = X % 256; y = X / 256
        scaled_C = float(C)/float(col_max)
        frfigax.add_patch(plt.Rectangle((x,y),1,1,edgecolor=cmap(scaled_C),facecolor=cmap(scaled_C)))

    # Loop over the masked pixels and plot them.
    for X, C in pixel_mask.iteritems():
        x = X % 256; y = X / 256
        frfigax.add_patch(plt.Rectangle((x,y),1,1,edgecolor='#00CC44',facecolor='#00CC44'))

    # Set the axis limits based.
    b = 3 # border

    # Set the axis limits.
    frfigax.set_xlim([0 - b, 256 + b])
    frfigax.set_ylim([0 - b, 256 + b])

    frfigax.set_aspect('equal')

    # Show the figure.
    frfig.show()
    raw_input()

    # Save the figure.
    frfig.savefig(outputpath + "/%s.png" % (basename))
开发者ID:twhyntie,项目名称:frame-viewer,代码行数:77,代码来源:visualisation.py


示例14: plot


#.........这里部分代码省略.........
        # set y-axis major ticks
        self.ax.yaxis.set_ticks([np.log10(plot_periodlist[ll]) * self.ystretch for ll in np.arange(0, n, self.ystep)])

        # set y-axis minor ticks
        self.ax.yaxis.set_ticks(
            [np.log10(plot_periodlist[ll]) * self.ystretch for ll in np.arange(0, n, 1)], minor=True
        )
        # set y-axis tick labels
        self.ax.set_yticklabels(yticklabels)

        # set x-axis ticks
        self.ax.set_xticks(self.offsetlist * self.xstretch)

        # set x-axis tick labels as station names
        xticklabels = self.stationlist
        if self.xstep != 1:
            xticklabels = np.zeros(len(self.stationlist), dtype=self.stationlist.dtype)
            for xx in range(0, len(self.stationlist), self.xstep):
                xticklabels[xx] = self.stationlist[xx]
        self.ax.set_xticklabels(xticklabels)

        # --> set x-limits
        if self.xlimits == None:
            self.ax.set_xlim(
                self.offsetlist.min() * self.xstretch - es * 2, self.offsetlist.max() * self.xstretch + es * 2
            )
        else:
            self.ax.set_xlim(self.xlimits)

        # --> set y-limits
        if self.ylimits == None:
            self.ax.set_ylim(pmax + es * 2, pmin - es * 2)
        else:
            pmin = np.log10(self.ylimits[0]) * self.ystretch
            pmax = np.log10(self.ylimits[1]) * self.ystretch
            self.ax.set_ylim(pmax + es * 2, pmin - es * 2)

        # --> set title of the plot
        if self.plot_title == None:
            pass
        else:
            self.ax.set_title(self.plot_title, fontsize=self.font_size + 2)

        # put a grid on the plot
        self.ax.grid(alpha=0.25, which="both", color=(0.25, 0.25, 0.25))

        # print out the min an max of the parameter plotted
        print "-" * 25
        print ck + " min = {0:.2f}".format(min(minlist))
        print ck + " max = {0:.2f}".format(max(maxlist))
        print "-" * 25

        # ==> make a colorbar with appropriate colors
        if self.cb_position == None:
            self.ax2, kw = mcb.make_axes(self.ax, orientation=self.cb_orientation, shrink=0.35)
        else:
            self.ax2 = self.fig.add_axes(self.cb_position)

        if cmap == "mt_seg_bl2wh2rd":
            # make a color list
            self.clist = [(cc, cc, 1) for cc in np.arange(0, 1 + 1.0 / (nseg), 1.0 / (nseg))] + [
                (1, cc, cc) for cc in np.arange(1, -1.0 / (nseg), -1.0 / (nseg))
            ]

            # make segmented colormap
            mt_seg_bl2wh2rd = colors.ListedColormap(self.clist)

            # make bounds so that the middle is white
            bounds = np.arange(ckmin - ckstep, ckmax + 2 * ckstep, ckstep)

            # normalize the colors
            norms = colors.BoundaryNorm(bounds, mt_seg_bl2wh2rd.N)

            # make the colorbar
            self.cb = mcb.ColorbarBase(
                self.ax2, cmap=mt_seg_bl2wh2rd, norm=norms, orientation=self.cb_orientation, ticks=bounds[1:-1]
            )
        else:
            self.cb = mcb.ColorbarBase(
                self.ax2,
                cmap=mtcl.cmapdict[cmap],
                norm=colors.Normalize(vmin=ckmin, vmax=ckmax),
                orientation=self.cb_orientation,
            )

        # label the color bar accordingly
        self.cb.set_label(mtpl.ckdict[ck], fontdict={"size": self.font_size, "weight": "bold"})

        # place the label in the correct location
        if self.cb_orientation == "horizontal":
            self.cb.ax.xaxis.set_label_position("top")
            self.cb.ax.xaxis.set_label_coords(0.5, 1.3)

        elif self.cb_orientation == "vertical":
            self.cb.ax.yaxis.set_label_position("right")
            self.cb.ax.yaxis.set_label_coords(1.5, 0.5)
            self.cb.ax.yaxis.tick_left()
            self.cb.ax.tick_params(axis="y", direction="in")

        plt.show()
开发者ID:rmorel,项目名称:mtpy,代码行数:101,代码来源:plotresidualptps.py


示例15: _corr2d4fig

def _corr2d4fig(spec, a1_label=r'$\bar{A}(\nu_1)$', 
               a2_label=r'$\bar{A}(\nu_2)$', **contourkwds): 
    """ Abstract layout for 2d correlation analysis plot.  
    
    **contourkwds
        Passed directly to _gencontour; includes keywords like xlabel, ylabel
        and so forth.
    """

    # Maybe this should take X, Y, Z not ts

    #fig, ax #how to handle these in general 2d
    # Maybe it's helpful to have args for top plots (ie ax1,2,3)
    
    title = contourkwds.pop('title', '')
    cbar = contourkwds.pop('cbar', False)
    grid = contourkwds.setdefault('grid', True) #Adds grid to plot and side plots
    
    # REFACTOR THIS
    cbar_nticks = 5
  
    
    # This will create a fig
    ax1 = plt.subplot2grid((5,5), (0,0), colspan=1) # top left
    plt.subplots_adjust(hspace = 0, wspace=0)    # Remove whitespace
    
    ax1.plot([0,-1], color='black')    

    ax1.text(.18, -.78, a1_label, size=12) 
    ax1.text(.55, -.35, a2_label, size=12)    

    ax2 = plt.subplot2grid((5,5), (0,1), colspan=4) # top
    ax3 = plt.subplot2grid((5,5), (1,0), colspan=1, rowspan=4) #left
    ax4 = plt.subplot2grid((5,5), (1, 1), colspan=4, rowspan=4) #main contour
    ax3.invert_xaxis()
    ax4.yaxis.tick_right()
    ax4.xaxis.tick_bottom() #remove top xticks
    ax4.yaxis.set_label_position('right')
    
    ax4, contours = _gen2d3d(spec, ax=ax4, **contourkwds)
        
    # Bisecting line
    pvutil.diag_line(ax4)  
    
    # Fig is created by _gen2d in ax4 _gen2d3d
    fig = plt.gcf()
      
    # Hide axis labels 
    for ax in [ax2, ax3]:
        if grid:
            pvutil.hide_axis(ax, axis='both', axislabel=True, ticklabels=True)
        else:
            pvutil.hide_axis(ax, axis='both', hide_everything = True)
            
    pvutil.hide_axis(ax1, axis='both', hide_everything=True)
  
    #plt.colorbar() doesn't work
    # Handles its own colorbar (See links below; important)
   # http://stackoverflow.com/questions/13784201/matplotlib-2-subplots-1-colorbar
   # http://matplotlib.org/api/colorbar_api.html#matplotlib.colorbar.make_axes
    if cbar:
        if cbar in ['left', 'right', 'top', 'bottom']:
        # if bottom or right, should repad this
            location = cbar
        else:
            location = 'top'
        cax,kw = mplcbar.make_axes([ax1, ax2, ax3, ax4], 
                                   location=location,
                                   pad = 0.05,
                                   aspect = 30, #make skinnier
                                   shrink=0.75) 
        
        cb = fig.colorbar(contours, cax=cax,**kw)# ticks=[0,zz.max().max()], **kw)
        cb.locator = mplticker.MaxNLocator(nbins=cbar_nticks+1) #Cuts off one usually
        cb.set_label(spec.iunit)        
        cb.update_ticks()


    #ax1 will take care of itself in contour
    if grid:
        if grid == True:
            ax2.grid()
            ax3.grid()
  
        else:
            ax2.grid(color=grid)
            ax3.grid(color=grid)

    fig.suptitle(title, fontsize='large') # Still overpads
    return (ax1, ax2, ax3, ax4)
开发者ID:Schroedingberg,项目名称:scikit-spectra,代码行数:90,代码来源:correlation_plot.py


示例16: plot_complex_function

def plot_complex_function(f, re=(-2, 2), im=(-2, 2), n=600, title='',
                          contours=True, numCtr=15, figsize=(5.5, 5.5), **kwargs):
    """plots complex functions in 2D using domain mapping technique

    Parameters
    ----------
    f : function object
        the function
    re : tuple
        2-tuple to indicate the bounds of real axis
    im : list
        2-tuple to indicate the bounds of imaginary axis
    n : integer
        number of grid points is n**2
    title : string
        title for the plot
    contours : bool
        if True (default), contours lines are drawn
    numCtr : integer
        number of contour lines
    figsize : tuple
        2-tuple figure size as (width, height) in inches

    Returns
    -------
    None

    Examples
    --------
    >>> plot_complex_function(lambda z:np.sqrt(z), title='$f(z)=\sqrt{z}$')
    >>> plot_complex_function(lambda z:1/np.tan(z), re=[-3, 3], im=[-2, 2],
                              title='$f(z)=ctan(z)$', figsize=(8,5))
    >>> plot_complex_function(lambda z:np.log(z), title='$f(z)=log(z)$')

    Notes
    -----
    1. The phase/angle/argument is continuously mapped to hue such that the
       mathematically significant phase values, specifically the multiples
       of π/2 correponding to the real and imaginary axes, are mapped to
       more immediately recognizable colors as follows:

            | hue     |  phase (radians)  |
            -------------------------------
            | red     |     0 mod 2π (+1) |
            | yellow  |   π/2 mod 2π (+i) |
            | cyan    |     π mod 2π (-1) |
            | blue    |  3π/2 mod 2π (-i) |
            | orange  |   π/4 mod 2π      |
            | green   |  3π/4 mod 2π      |
            | magenta |  7π/4 mod 2π      |

    2. |z| is mapped to show the direction of growth of the magnitude (from dark to
       bright within each ring), and the absolute value doubles for each ring.
       discontinuity in the intensity

    3. The grids/contours helps to see whether the function is conformal or
       not (a conformal function preserves the angles between two smooth
       curves)

    4. A discontinuity in hue represents a branch cut

    References
    ----------
    1. Visualizing complex-valued functions with Matplotlib and Mayavi,
       E. Petrisor, 2014
    2. About color maps (NIST Digital Library of Mathematical Functions).
       http://dlmf.nist.gov/help/vrml/aboutcolor
    3. Trigonometry Is a Complex Subject. Revisiting inverse, complex, hyperbolic,
       floating-point trig functions, Cleve Moler, 1998
    4. Visualizing complex analytic functions using domain coloring, Hans Lundmark
    """
    w = _eval_func(f, re, im, n)
    domc = _domain_map(w, satu=0.7)
    fig = _plt.figure(figsize=figsize)
    ax = fig.add_axes([0.15, 0.0, 0.85, 1.0])
    ax.set_xlabel("Re(z)")
    ax.set_ylabel("Im(z)")
    tfs = 16 # title font size could be a **kwargs input later
    ax.set_title(title, fontsize=tfs, y=1.02)
    if contours:
        levelsX = _np.linspace(2.0*re[0], 2.0*re[1], 2.0*numCtr + 1)
        levelsY = _np.linspace(2.0*im[0], 2.0*im[1], 2.0*numCtr + 1)
        ax.contour(_np.real(w), levels=levelsX, origin="lower",
                   extent=[re[0], re[1], im[0], im[1]], colors='k',
                   lw=1.5, linestyles='solid')
        ax.contour(_np.imag(w), levels=levelsY, origin="lower",
                   extent=[re[0], re[1], im[0], im[1]], colors='k',
                   lw=1.5, linestyles='solid')
    ax.imshow(domc, origin="lower", extent=[re[0], re[1], im[0], im[1]],
                   interpolation="hermite", zorder=20, alpha=0.9)
    norm = _mplc.Normalize(vmin=0, vmax=2.0*_np.pi)
    cbTickLocs = [0.0,  _np.pi/2, _np.pi, 3*_np.pi/2, 2*_np.pi]
    cbTicLbls = ['$0$', '$\pi/2$', '$\pi$' , '$3\pi/2$', '$2\pi$']
    cbax, kw = _mplcbar.make_axes(parents=ax, location='right', aspect=40,
                                  shrink=0.66, pad=0.08)
    cb = _mplcbar.ColorbarBase(ax=cbax, cmap=cplotHSVcm, norm=norm,)
    cb.set_alpha(0.9)
    cb.set_ticks(cbTickLocs)
    cb.set_ticklabels(cbTicLbls)
    _plt.show()
开发者ID:indranilsinharoy,项目名称:iutils,代码行数:100,代码来源:mplutils.py


示例17: make_frame_image

def make_frame_image(xs, ys, Cs):
    """ Create a figure displaying the frame data. """

    ## The minimum x value.
    x_min = 0

    ## The maximum x value.
    x_max = 256

    ## The minimum y value.
    y_min = 0

    ## The maximum y value.
    y_max = 256

    ## The width of the frame.
    w = 256

    ## The height of the frame.
    h = 256

    ## The maximum count value.
    C_max = 1

    # We add this just in case there are no pixels supplied.
    if len(Cs) > 0:
        C_max = max(Cs)

    # Create the figure.
    plt.close('all')

    ## The default size of the figure [inches].
    fig_size = 5.0

    ## The figure for the frame.
    fig = plt.figure(1, figsize=(fig_size*1.27, fig_size), dpi=150, facecolor='w', edgecolor='w')

    ## The frame axes.
    figax = fig.add_subplot(111, axisbg='#222222')

    # Add the frame background (blue).
    figax.add_patch(plt.Rectangle((0,0),256,256,facecolor='#82bcff'))

    # Add a grid.
    plt.grid(1)

    # Select the "hot" colour map for the pixel counts and add a
    # colour bar to indicate the count value for each pixel.
    #
    cmap = plt.cm.hot
    #
    colax, _ = colorbar.make_axes(plt.gca())
    #
    col_max = 10*(np.floor(C_max/10.)+1)
    #
    colorbar.ColorbarBase(colax,cmap=cmap,norm=colors.Normalize(vmin=0,vmax=col_max))

    # Loop over the pixels and add them to the figure.
    for i, x in enumerate(xs):
        ## The scaled count value (for the colour map).
        scaled_C = float(Cs[i])/float(col_max)

        # Rather than use, say, a 2D histogram for the pixels, we add
        # a coloured square to the plot for each pixel.
        figax.add_patch(plt.Rectangle((xs[i],ys[i]),1,1,edgecolor=cmap(scaled_C),facecolor=cmap(scaled_C)))

    ## The frame border width [pixels].
    b = 3

    # Set the axis limits based on the cluster radius.
    figax.set_xlim([0 - b, 256 + b])
    figax.set_ylim([0 - b, 256 + b])
开发者ID:CERNatschool,项目名称:get-coding,代码行数:72,代码来源:helpers.py


示例18: _plot_unit

    def _plot_unit(self, pinfo, ax):
        x = pinfo.pop('x')
        y = pinfo.pop('y')
        fill = pinfo.pop('fill')

        # TODO: Fix this hack!
        # Currently, if the fill is specified in the ggplot aes wrapper, ggplot
        # will assign colors without regard to the fill values. This is okay for
        # categorical maps but not heatmaps. At this stage in the pipeline the
        # geom can't recover the original values.
        #
        # However, if the fill is specified in the geom_tile aes wrapper, the
        # original fill values are sent unaltered, so we can make a heat map
        # with the values.

        # Was the fill specified in geom wrapper only? (i.e. not in ggplot)
        if 'fill' in self.aes_unique_to_geom:
            # Determine if there are non-numeric values.
            if False in [isinstance(v, (int, long, float, complex)) for v in set(fill)]:
                # No need to handle this case. Instruct the user to put categorical
                # values in the ggplot wrapper.
                raise Exception('For categorical fill values specify fill in the ggplot aes instead of the geom_tile aes.')

            # All values are numeric so determine fill using colormap.
            else:
                fill_min  = np.min(fill)
                fill_max  = np.max(fill)

                if np.isnan(fill_min):
                    raise Exception('Fill values cannot contain NaN values.')

                fill_rng  = float(fill_max - fill_min)
                fill_vals = (fill - fill_min) / fill_rng

                cmap = self.gg.colormap(fill_vals.tolist())
                fill      = [colors.rgb2hex(c) for c in cmap[::, :3]]

        df = pd.DataFrame(
            {'x': x, 'y': y, 'fill': fill}).set_index(['x', 'y']).unstack(0)

        # Setup axes.
        x_ticks   = range(2*len(set(x)) + 1)
        y_ticks   = range(2*len(set(y)) + 1)

        x_indices = sorted(set(x))
        y_indices = sorted(set(y))

        # Setup box plotting parameters.
        x_start   = 0
        y_start   = 0
        x_step    = 2
        y_step    = 2

        # Plot grid.
        on_y = y_start
        for yi in xrange(len(y_indices)):
            on_x = x_start
            for xi in xrange(len(x_indices)):
                color = df.iloc[yi,xi]
                if not isinstance(color, float):
                    ax.add_patch(Rectangle((on_x, on_y), x_step, y_step, facecolor=color))
                on_x += x_step
            on_y += y_step

        # Draw the colorbar scale if drawing a heat map.
        if 'cmap' in locals():
            norm = colors.Normalize(vmin = fill_min, vmax = fill_max)
            cax, kw = colorbar.make_axes(ax)
            cax.hold(True)
            colorbar.ColorbarBase(cax, cmap = self.gg.colormap, norm = norm)

        # Set axis labels and ticks.
        x_labels = ['']*(len(x_indices)+1)
        for i,v in enumerate(x_indices): x_labels.insert(2*i+1, v)
        y_labels = ['']*(len(y_indices)+1)
        for i,v in enumerate(y_indices): y_labels.insert(2*i+1, v)

        ax.set_xticklabels(x_labels)
        ax.set_xticks(x_ticks)
        ax.set_yticklabels(y_labels)
        ax.set_yticks(y_ticks)
开发者ID:Camr0n,项目名称:ggplot,代码行数:81,代码来源:geom_tile.py


示例19: makeKlusterImage

def makeKlusterImage(klusterid, kl, outputpath):
    """ Create the kluster image. """

    # FIXME: Make configurable.

    pixels = kl.getPixelMap()

    x_min = kl.getXMin()

    x_max = kl.getXMax()

    y_min = kl.getYMin()

    y_max = kl.getYMax()

    w = kl.getWidth()

    h = kl.getHeight()

    ## The maximum count value.
    C_max = kl.getMaxCountValue()

    x_bar = kl.getXUW()

    y_bar = kl.getYUW()

    radius = kl.getRadiusUW()

    m, c, sumR = kl.getLineOfBestFitValues()

    # Create the figure.
    plt.close('all')

    figsize = 5.0

    ## The figure for the cluster image.
    blobfig = plt.figure(1, figsize=(figsize*1.27, figsize), dpi=150, facecolor='w', edgecolor='w')

    # Set the beyond-frame background colour.
    blobfigax = blobfig.add_subplot(111, axisbg='#222222')

    # Add the frame background (blue).
    blobfigax.add_patch(plt.Rectangle((0,0),256,256,facecolor='#82bcff'))

    # Add a grid.
    plt.grid(1)

    # Select the "hot" colour map for the pixel counts.

    cmap = plt.cm.hot

    colax, _ = colorbar.make_axes(plt.gca())

    col_max = 10*(np.floor(C_max/10.)+1)

    colorbar.ColorbarBase(colax,cmap=cmap,norm=colors.Normalize(vmin=0,vmax=col_max))

    # Add the line of best fit.
    addLineOfBestFit(blobfigax, m, c)

    # Add the radius circle.
    addRadiusCircle(blobfigax, x_bar, y_bar, radius)

    # Loop over the pixels and plot them.
    for X, C in pixels.iteritems():
        x = X % 256; y = X / 256
        scaled_C = float(C)/float(col_max)
        blobfigax.add_patch(plt.Rectangle((x,y),1,1,facecolor=cmap(scaled_C)))

    # Set the axis limits based on the cluster radius.
    b = 3 # border

    xlim_min = x_bar - (np.floor(radius)+b)
    xlim_max = x_bar + (np.floor(radius)+b)
    ylim_min = y_bar - (np.floor(radius)+b)
    ylim_max = y_bar + (np.floor(radius)+b)

    blobfigax.set_xlim([xlim_min, xlim_max])
    blobfigax.set_ylim([ylim_min, ylim_max])

    # Set the axis tick mark spacing.
    blobfigax.xaxis.set_major_locator(MultipleLocator(10))
    blobfigax.yaxis.set_major_locator(MultipleLocator(10))

    # Save the figure.
    blobfig.savefig(outputpath + "/%s.png" % (klusterid))
开发者ID:CERNatschool,项目名称:beta-attenuation,代码行数:86,代码来源:visualisation.py


示例20:


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python colorbar.ColorbarBase类代码示例发布时间:2022-05-27
下一篇:
Python collections.RegularPolyCollection类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap