当前位置: 首页>>代码示例>>Python>>正文


Python colorbar.make_axes函数代码示例

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


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


注:本文中的matplotlib.colorbar.make_axes函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。