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

Python axes_grid.make_axes_locatable函数代码示例

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

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



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

示例1: setup_axes

def setup_axes(fig, header):
    from mpl_toolkits.axes_grid import make_axes_locatable

    ax0 = pywcsgrid2.subplot(111, wcs=header)
    divider = make_axes_locatable(ax0)

    gh1 = pywcsgrid2.GridHelperSimple(wcs=header, axis_nums=[0, 2])
    ax_v = divider.new_vertical(1.5, pad=0.1, sharex=ax0,
                                axes_class=pywcsgrid2.Axes,
                                grid_helper=gh1)
    fig.add_axes(ax_v)

    gh2 = pywcsgrid2.GridHelperSimple(wcs=header, axis_nums=[2, 1])
    ax_h = divider.new_horizontal(1.5, pad=0.1, sharey=ax0,
                                axes_class=pywcsgrid2.Axes,
                                grid_helper=gh2)

    fig.add_axes(ax_h)


    ax_h.axis["left"].toggle(label=False, ticklabels=False)
    ax_v.axis["bottom"].toggle(label=False, ticklabels=False)


    return ax0, ax_v, ax_h
开发者ID:leejjoon,项目名称:matplotlib_astronomy_gallery,代码行数:25,代码来源:ic443_pv_map.py


示例2: drawmap

def drawmap(DATA,TITLESTRING,PROD,UNITS):
    F = plt.gcf()  # Gets the current figure

    m.drawstates(color='k', linewidth=1.25)
    m.drawcoastlines(color='k')
    m.drawcountries(color='k', linewidth=1.25)
	#m.readshapefile(shapefile='/data/geog/shapefiles/fe_2007_40_county.shp',name='COUNTY',drawbounds='True')
	#m.readshapefile(shapefile='/data/geog/shapefiles/fe_2007_48_county.shp',name='COUNTY',drawbounds='True')
	#plt.suptitle('%s' % UNITS, fontsize = 11, x = 0.08, y = 0.105)
    plt.title('UW WRF-ARW %s (%s)   Valid: %s' % (TITLESTRING, UNITS, curtimestring), \
		fontsize=11,bbox=dict(facecolor='white', alpha=0.65),\
		x=0.5,y=.95,weight = 'demibold',style='oblique', \
		stretch='normal', family='sans-serif')

    # Code to make the colorbar outside of the main axis, on the bottom, and lined up
    ax = plt.gca()  # Gets the current axes
    divider = make_axes_locatable(ax)  # Lets us move axes around
    cax = divider.append_axes("bottom", size="2%",pad=-0.02,axes_class=maxes.Axes) # Adds an axis for the colorbar
    F.add_axes(cax)  # Adds the new axis to the figure as the current working axis
    bar = plt.colorbar(DATA,cax=cax,orientation='horizontal',format='%4.2f',extend='both') # Plots colorbar in new axis 
    bar.ax.xaxis.set_major_locator(matplotlib.ticker.MultipleLocator(base=1.0)) # Make the colorbars numbers nice
    bar.update_ticks()

    file_id = '%s_%s_f%02d' % (dom, PROD, time+restart_time)
    filename = '%s.png' % (file_id)
	
    plt.savefig(filename,bbox_inches='tight') # Saves the figure with small margins
    plt.close()

    #if export_flag == 1:
    # Convert the figure to a gif file
    os.system('convert -render -flatten %s %s.gif' % (filename, file_id))
    os.system('rm -f %s' % filename)
开发者ID:lmadaus,项目名称:old_wrf_plotting_scripts,代码行数:33,代码来源:plot_wrf_maps.py


示例3: plot

def plot(axes, net):

    classname = net.__class__.__name__

    axes.set_xticks([])
    axes.set_yticks([])
    divider = make_axes_locatable(axes)
    subaxes = divider.new_vertical(1.0, pad=0.4, sharex=axes)
    fig.add_axes(subaxes)
    subaxes.set_xticks([])
    subaxes.yaxis.set_major_locator(matplotlib.ticker.MaxNLocator(2))
    subaxes.yaxis.set_ticks_position('right')
    subaxes.set_ylabel('Distortion')
    subaxes.set_xlabel('Time')

    Y = net.distortion[::1]
    X = np.arange(len(Y))/float(len(Y)-1)
    subaxes.plot(X,Y)

    if classname == 'NG':
        plt.title('Neural Gas', fontsize=20)
    elif classname == 'SOM':
        plt.title('Self-Organizing Map', fontsize=20)
    elif classname == 'DSOM':
        plt.title('Dynamic Self-Organizing Map', fontsize=20)

    axes.axis([0,1,0,1])
    axes.set_aspect(1)

    codebook = net.codebook
    axes.imshow(codebook, interpolation='nearest')
                         #interpolation='bicubic')

    if classname == 'NG':
        axes.text(0.5, -0.01,
                  r'$\lambda_i = %.3f,\lambda_f = %.3f, \varepsilon_i=%.3f, \varepsilon_f=%.3f$' % (
                net.sigma_i, net.sigma_f, net.lrate_i, net.lrate_f),
                  fontsize=16, 
                  horizontalalignment='center',
                  verticalalignment='top',
                  transform = axes.transAxes)
    if classname == 'SOM':
        axes.text(0.5, -0.01,
                  r'$\sigma_i = %.3f,\sigma_f = %.3f, \varepsilon_i=%.3f, \varepsilon_f=%.3f$' % (
                net.sigma_i, net.sigma_f, net.lrate_i, net.lrate_f),
                  fontsize=16, 
                  horizontalalignment='center',
                  verticalalignment='top',
                  transform = axes.transAxes)
    elif classname == 'DSOM':
        axes.text(0.5, -0.01,
                  r'$elasticity = %.2f$' % (net.elasticity),
                  fontsize=16, 
                  horizontalalignment='center',
                  verticalalignment='top',
                  transform = axes.transAxes)
开发者ID:rougier,项目名称:dynamic-som,代码行数:56,代码来源:figure-color.py


示例4: plot_dist

    def plot_dist(self, axes):
        ''' Plot network on given axes
        '''

        classname = self.__class__.__name__
        fig = plt.gcf()
        divider = make_axes_locatable(axes)
        axes.axis([0,1,0,.5])


        Y = self.distortion[::1]
        X = np.arange(len(Y))/float(len(Y)-1)
        axes.plot(X,Y)
开发者ID:lightbright,项目名称:basic-self-organizing-map,代码行数:13,代码来源:network.py


示例5: QC_Chromosome_Plot

def QC_Chromosome_Plot(calls, title=None, outfile=None):
    x = np.array(calls.calls["num_probes"].values)
    y = np.array(calls.calls["median_svdzrpkm"].values)

    fig = plt.figure(1, figsize=(9,9))

    from mpl_toolkits.axes_grid import make_axes_locatable

    axScatter = plt.subplot(111)
    divider = make_axes_locatable(axScatter)

    # create a new axes with a height of 1.2 inch above the axScatter
    axHistx = divider.new_vertical(1.2, pad=0.1, sharex=axScatter)

    # create a new axes with a width of 1.2 inch on the right side of the
    # axScatter
    axHisty = divider.new_horizontal(1.2, pad=0.1, sharey=axScatter)

    fig.add_axes(axHistx)
    fig.add_axes(axHisty)

    # make some labels invisible
    plt.setp(axHistx.get_xticklabels() + axHisty.get_yticklabels(),
             visible=False)

    # the scatter plot:
    #axScatter.scatter(x[x<0], y[x<0], lw=0, alpha=0.3, color="r")
    axScatter.scatter(x[x>=0], y[x>=0], lw=0, alpha=0.3, color="b")
    #axScatter.set_aspect(1.)
    axScatter.set_xscale("symlog")
    axHistx.set_xscale("symlog")

    axScatter.set_xlabel("Size of call (# of probes)")
    axScatter.set_ylabel("Signal Strength (Median SVD-ZRPKM)")

    axHistx.hist(x, bins=np.arange(0,np.max(x)), histtype="stepfilled", lw=0,align='left')
    axHisty.hist(y, bins=200, orientation='horizontal', histtype="stepfilled", lw=0)

    for tl in axHistx.get_xticklabels():
        tl.set_visible(False)

    axHisty.set_xticklabels(["%d" % i for i in axHisty.get_xticks()], rotation=-90)
    if title is not None:
        axHistx.set_title(title)

    if outfile is not None:
        plt.savefig(outfile)
开发者ID:Tmacme,项目名称:conifer-tools,代码行数:47,代码来源:plotting.py


示例6: _stabilityassessment

def _stabilityassessment(headers, data1d, dist, fig_correlmatrices, correlmatrixaxes, std_multiplier,
                         correlmatrix_colormap,
                         correlmatrix_filename, logarithmic_correlmatrix=True, cormaptest=True):
    # calculate and plot correlation matrix
    cmatrix, badidx, rowavg = correlmatrix(data1d, std_multiplier, logarithmic_correlmatrix)
    rowavgmean = rowavg.mean()
    rowavgstd = rowavg.std()
    writemarkdown('#### Assessing sample stability')
    writemarkdown("- Mean of row averages: " + str(rowavgmean))
    writemarkdown("- Std of row averages: " + str(rowavgstd) + ' (%.2f %%)' % (rowavgstd / rowavgmean * 100))

    img = correlmatrixaxes.imshow(cmatrix, interpolation='nearest', cmap=matplotlib.cm.get_cmap(correlmatrix_colormap))
    cax = make_axes_locatable(correlmatrixaxes).append_axes('right', size="5%", pad=0.1)
    fig_correlmatrices.colorbar(img, cax=cax)
    fsns = [h.fsn for h in headers]

    correlmatrixaxes.set_title('%.2f mm' % dist)
    correlmatrixaxes.set_xticks(list(range(len(data1d))))
    correlmatrixaxes.set_xticklabels([str(f) for f in fsns], rotation='vertical')
    correlmatrixaxes.set_yticks(list(range(len(data1d))))
    correlmatrixaxes.set_yticklabels([str(f) for f in fsns])
    np.savez_compressed(correlmatrix_filename,
                        correlmatrix=cmatrix, fsns=np.array(fsns))

    # Report table on sample stability
    tab = [['FSN', 'Date', 'Discrepancy', 'Relative discrepancy ((x-mean(x))/std(x))', 'Quality', 'Quality (cormap)']]
    badfsns = []
    badfsns_datcmp = []
    if cormaptest:
        matC, matp, matpadj, datcmp_ok = datcmp(*data1d)
    else:
        datcmp_ok = [not x for x in badidx]
    for h, bad, discr, dcmp_ok in zip(headers, badidx, rowavg, datcmp_ok):
        tab.append([h.fsn, h.date.isoformat(), discr, (discr - rowavgmean) / rowavgstd,
                    ["\u2713", "\u2718\u2718\u2718\u2718\u2718"][bad],
                    ["\u2713", "\u2718\u2718\u2718\u2718\u2718"][dcmp_ok != 1]])
        if bad:
            badfsns.append(h.fsn)
        if (not dcmp_ok and not np.isnan(dcmp_ok)):
            badfsns_datcmp.append(h.fsn)
    tab = ipy_table.IpyTable(tab)
    tab.apply_theme('basic')
    return badfsns, badfsns_datcmp, tab, rowavg
开发者ID:awacha,项目名称:credolib,代码行数:43,代码来源:procedures.py


示例7: plot

    def plot(self, axes):
        ''' Plot network on given axes
        '''

        classname = self.__class__.__name__
        fig = plt.gcf()
        divider = make_axes_locatable(axes)
        axes.axis([0,1,0,1])

        # Plot samples
        axes.scatter(self.samples[:,0], self.samples[:,1], s=1, color='g', alpha=0.5)
        C = self.adj
        Cx,Cy = C[...,0], C[...,1]

        if classname != 'SSk':
        
            for i in range(C.shape[0]):
                axes.plot (Cx[i,:], Cy[i,:], 'k', alpha=1, lw=1.5)
        
            for i in range(C.shape[1]):
                axes.plot (Cx[:,i], Cy[:,i], 'k', alpha=1, lw=1.5)
开发者ID:lightbright,项目名称:basic-self-organizing-map,代码行数:21,代码来源:network.py


示例8: plot_eigenvectors

def plot_eigenvectors(ax, Y, idx, colormap):
    from matplotlib.ticker import MaxNLocator
    from mpl_toolkits.axes_grid import make_axes_locatable

    divider = make_axes_locatable(ax)
    ax2 = divider.new_vertical(size="100%", pad=0.05)
    fig1 = ax.get_figure()
    fig1.add_axes(ax2)
    ax2.set_title("Eigenvectors", fontsize=10)
    ax2.scatter(np.arange(0, len(Y)), Y[:, 0], s=10, c=idx, cmap=colormap, alpha=0.9, facecolors="none")
    ax2.axhline(0, ls="--", c="k")
    ax2.yaxis.set_major_locator(MaxNLocator(4))
    ax.yaxis.set_major_locator(MaxNLocator(4))
    ax.axhline(0, ls="--", c="k")
    ax.scatter(np.arange(0, len(Y)), Y[:, 1], s=10, c=idx, cmap=colormap, alpha=0.9, facecolors="none")
    ax.set_xlabel("index", fontsize=8)
    ax2.set_ylabel("2nd Smallest", fontsize=8)
    ax.set_ylabel("3nd Smallest", fontsize=8)
    change_tick_fontsize(ax, 8)
    change_tick_fontsize(ax2, 8)
    for tl in ax2.get_xticklabels():
        tl.set_visible(False)
开发者ID:yongleli,项目名称:pyProCT,代码行数:22,代码来源:circles_generation.py


示例9: print

        if (num == 0):
            Vortensity0 = Vortensity

        print("Doing geometric transformation to R-theta plane...")
        # create polar-coordinate array
        Vortensity_polar = geometric_transform(Vortensity.T, cartesian2polar, output_shape=(Vortensity.T.shape[0], Vortensity.T.shape[0]),
                                               extra_keywords={'inputshape': Vortensity.T.shape, 'origin': (Vortensity.T.shape[0]/2, Vortensity.T.shape[1]/2)})
        if (num == 0):
            Vortensity0_polar = Vortensity_polar

        ####################################################################
        # plot
        if not (skip_cartesian):

            ax = fig.add_subplot(1, len(dir_array), count_dir)
            divider = make_axes_locatable(ax)

            cmap = cm.get_cmap('jet')
            im = ax.imshow(np.log10(Vortensity/Vortensity0), origin='lower',
                           vmin=min_scale, vmax=max_scale,
                           extent=[rangeX[0], rangeX[1], rangeY[0], rangeY[1]], cmap=cmap)

            xlabel("$x$", fontsize=16)
            ylabel("$y$", fontsize=16)
            ax.set_xlim(rangeX[0], rangeX[1])
            ax.set_ylim(rangeY[0], rangeY[1])

            xticks, yticks = ax.xaxis.get_majorticklocs(), ax.yaxis.get_majorticklocs()
            ax.xaxis.set_ticklabels(['%d' % (xticks[n] - 0.5*BoxX)
                                     for n in range(len(xticks))])
            ax.yaxis.set_ticklabels(['%d' % (yticks[n] - 0.5 * BoxY)
开发者ID:djmunoz,项目名称:disk_data_analysis,代码行数:31,代码来源:plot_vortensity_array.py


示例10: show

    def show(self, location='right', width=0.2, pad=0.05, ticks=None, labels=True, box=None, box_orientation='vertical'):
        '''
        Show a colorbar on the side of the image.

        Optional Keyword Arguments:

            *location*: [ string ]
                Where to place the colorbar. Should be one of 'left', 'right', 'top', 'bottom'.

            *width*: [ float ]
                The width of the colorbar relative to the canvas size.

            *pad*: [ float ]
                The spacing between the colorbar and the image relative to the canvas size.

            *ticks*: [ None or list ]
                The position of the ticks on the colorbar.

            *labels*: [ True or False ]
                Whether to show numerical labels.

            *box*: [ list ]
                A custom box within which to place the colorbar. This should
                be in the form [xmin, ymin, dx, dy] and be in relative figure
                units. This overrides the location argument.

            *box_orientation* [ str ]
                The orientation of the colorbar within the box. Can be
                'horizontal' or 'vertical'
        '''

        self._base_settings['location'] = location
        self._base_settings['width'] = width
        self._base_settings['pad'] = pad
        self._base_settings['ticks'] = ticks
        self._base_settings['labels'] = labels
        self._base_settings['box'] = box
        self._base_settings['box_orientation'] = box_orientation

        if self._parent.image:

            if self._colorbar_axes:
                self._parent._figure.delaxes(self._colorbar_axes)

            if box is None:

                divider = make_axes_locatable(self._parent._ax1)

                if location == 'right':
                    self._colorbar_axes = divider.new_horizontal(size=width, pad=pad, axes_class=maxes.Axes)
                    orientation = 'vertical'
                elif location == 'top':
                    self._colorbar_axes = divider.new_vertical(size=width, pad=pad, axes_class=maxes.Axes)
                    orientation = 'horizontal'
                elif location == 'left':
                    warnings.warn("Left colorbar not fully implemented")
                    self._colorbar_axes = divider.new_horizontal(size=width, pad=pad, pack_start=True, axes_class=maxes.Axes)
                    locator = divider.new_locator(nx=0, ny=0)
                    self._colorbar_axes.set_axes_locator(locator)
                    orientation = 'vertical'
                elif location == 'bottom':
                    warnings.warn("Bottom colorbar not fully implemented")
                    self._colorbar_axes = divider.new_vertical(size=width, pad=pad, pack_start=True, axes_class=maxes.Axes)
                    locator = divider.new_locator(nx=0, ny=0)
                    self._colorbar_axes.set_axes_locator(locator)
                    orientation = 'horizontal'
                else:
                    raise Exception("location should be one of: right/top")

                self._parent._figure.add_axes(self._colorbar_axes)

            else:

                self._colorbar_axes = self._parent._figure.add_axes(box)
                orientation = box_orientation

            self._colorbar = self._parent._figure.colorbar(self._parent.image, cax=self._colorbar_axes, orientation=orientation, ticks=ticks)

            if location == 'right':
                for tick in self._colorbar_axes.yaxis.get_major_ticks():
                    tick.tick1On = True
                    tick.tick2On = True
                    tick.label1On = False
                    tick.label2On = labels
            elif location == 'top':
                for tick in self._colorbar_axes.xaxis.get_major_ticks():
                    tick.tick1On = True
                    tick.tick2On = True
                    tick.label1On = False
                    tick.label2On = labels
            elif location == 'left':
                for tick in self._colorbar_axes.yaxis.get_major_ticks():
                    tick.tick1On = True
                    tick.tick2On = True
                    tick.label1On = labels
                    tick.label2On = False
            elif location == 'bottom':
                for tick in self._colorbar_axes.xaxis.get_major_ticks():
                    tick.tick1On = True
                    tick.tick2On = True
#.........这里部分代码省略.........
开发者ID:d80b2t,项目名称:python,代码行数:101,代码来源:colorbar.py


示例11: isNum

for str in flist:
	str=str.rstrip('\n')
	if str.find('Real') != -1:
		flag=1
	elif flag==1 and str.find('Imag') != -1:
		flag=0
	elif flag==1 and isNum(str):
		x.append(float(str))
	elif flag==0 and isNum(str):
		y.append(float(str))


fig = plt.figure(1, figsize=(10,10), dpi=50)

axScatter = plt.subplot(111)
divider = make_axes_locatable(axScatter)

axScatter.scatter(x, y)
axScatter.set_aspect(1.)

axes = fig.get_axes()[0]
axes.set_xlim((-3, 3))
axes.set_ylim((-3, 3))
axes.set_aspect('auto', adjustable='box')

plt.draw()
plt.show()


os.remove('/tmp/symbols.txt')
os.remove('/tmp/symbols_noise.txt')
开发者ID:alring,项目名称:BERsim,代码行数:31,代码来源:scatterPlot_old.py


示例12: plot


#.........这里部分代码省略.........
				self.emptyAxis()	
				reply = QtGui.QMessageBox.question(self, 'Excessively large plot', 'The resulting plot is too large to display.')
				QtGui.QApplication.instance().restoreOverrideCursor()
				return
		
		self.fig.set_size_inches(self.imageWidth, self.imageHeight)	
				
		# *** Determine width of y-axis labels
		yLabelBounds = self.yLabelExtents(features, 8)
		
		# *** Size plots which comprise the extended errorbar plot
		self.fig.clear()
		
		spacingBetweenPlots = 0.25	# inches
		widthNumSeqPlot = 1.25	# inches
		if self.bShowBarPlot == False:
			widthNumSeqPlot = 0.0
			spacingBetweenPlots = 0.0
		
		widthPvalueLabels = 0.75	# inches
		if self.bShowPValueLabels == False:
			widthPvalueLabels = 0.1
				 
		yPlotOffsetFigSpace = heightBottomLabels / self.imageHeight 
		heightPlotFigSpace = plotHeight / self.imageHeight
			 
		xPlotOffsetFigSpace = yLabelBounds.width + 0.1 / self.imageWidth
		pValueLabelWidthFigSpace =	widthPvalueLabels / self.imageWidth
		widthPlotFigSpace = 1.0 - pValueLabelWidthFigSpace - xPlotOffsetFigSpace
		
		widthErrorBarPlot = widthPlotFigSpace*self.imageWidth - widthNumSeqPlot - spacingBetweenPlots
				
		axInitAxis = self.fig.add_axes([xPlotOffsetFigSpace,yPlotOffsetFigSpace,widthPlotFigSpace,heightPlotFigSpace])
		divider = make_axes_locatable(axInitAxis)
		divider.get_vertical()[0] = Size.Fixed(len(features)*self.figHeightPerRow)
	 
		if self.bShowBarPlot == True:	
			divider.get_horizontal()[0] = Size.Fixed(widthNumSeqPlot)
			axErrorbar = divider.new_horizontal(widthErrorBarPlot, pad=spacingBetweenPlots, sharey=axInitAxis)
			self.fig.add_axes(axErrorbar)
		else:
			divider.get_horizontal()[0] = Size.Fixed(widthErrorBarPlot)
			axErrorbar = axInitAxis
				
		# *** Plot of sequences for each subsystem
		if self.bShowBarPlot == True:
			axNumSeq = axInitAxis
			
			if self.percentageOrSeqCount == 'Proportion (%)':
				# plot percentage
				axNumSeq.barh(np.arange(len(features))+0.0, percentage1, height = 0.3, color=profile1Colour, zorder=10, ecolor='black')
				axNumSeq.barh(np.arange(len(features))-0.3, percentage2, height = 0.3, color=profile2Colour, zorder=10, ecolor='black')
				for value in np.arange(-0.5, len(features)-1, 2):
					axNumSeq.axhspan(value, value+1, facecolor=highlightColor,edgecolor='none',zorder=1)
				
				axNumSeq.set_xlabel(self.percentageOrSeqCount)
				maxPercentage = max(max(percentage1), max(percentage2))
				axNumSeq.set_xticks([0, maxPercentage])
				axNumSeq.set_xlim([0, maxPercentage*1.05])
				maxPercentageStr = '%.1f' % maxPercentage
				axNumSeq.set_xticklabels(['0.0', maxPercentageStr])
			else:
				# plot sequence count
				axNumSeq.barh(np.arange(len(features))+0.0, seqs1, height = 0.3, color=profile1Colour, zorder=10, ecolor='black')
				axNumSeq.barh(np.arange(len(features))-0.3, seqs2, height = 0.3, color=profile2Colour, zorder=10, ecolor='black')
				for value in np.arange(-0.5, len(features)-1, 2):
开发者ID:IUEayhu,项目名称:STAMP,代码行数:67,代码来源:ExtendedErrorBar.py


示例13: create_scatterhist


#.........这里部分代码省略.........
        raise Exception('Select two different parameters')
          
    #check if parameter and of are really arrays
    if not isinstance(parameters, np.ndarray):
        raise Exception('parameters need to be numpy ndarray')
    if not isinstance(scaled_of, np.ndarray):
        raise Exception('objective function need to be numpy ndarray')

    # check if objective function is of size 1xN     
    scaled_of = np.atleast_2d(scaled_of).T
    if (len(scaled_of.shape) != 2 ):
       raise Exception("Objective function need to be of size (1, N) got %s instead" %(scaled_of.shape))
   
    # check that SSE row length is equal to parameters
    if not parameters.shape[0] == scaled_of.shape[0]:
        raise Exception("None corresponding size of parameters and OF!")

    # Check if threshold is in range of SSE values
    if threshold < 0 or threshold > 1:
        raise Exception("Threshold outside objective function ranges")

    # Select behavioural parameter sets with of lower as threshold
    search=np.where(scaled_of < threshold)
    behav_par = parameters[search[0]]
    behav_obj = selected_of[search[0]].T 
    print("Number of behavioural parametersets = " + str(behav_obj.shape[0]) + " out of " + str(parameters.shape[0]))
    
    
    if not behav_par.size > 0:
        raise Exception('Threshold to severe, no behavioural sets.')

        
    fig, ax_scatter = plt.subplots(figsize=(8,6))
    divider = make_axes_locatable(ax_scatter)
    ax_scatter.set_autoscale_on(True)
      
        
    # create a new axes with  above the axScatter
    ax_histx = divider.new_vertical(1.5, pad=0.0001, sharex=ax_scatter)

    # create a new axes on the right side of the axScatter
    ax_histy = divider.new_horizontal(1.5, pad=0.0001, sharey=ax_scatter)

    fig.add_axes(ax_histx)
    fig.add_axes(ax_histy)
    

    # now determine nice limits by hand:
    xmin = np.min(all_parameters[:,parameter1])
    xmax = np.max(all_parameters[:,parameter1])
    ymin = np.min(all_parameters[:,parameter2])
    ymax = np.max(all_parameters[:,parameter2])
    
    ax_histx.set_xlim( (xmin, xmax) )
    ax_histy.set_ylim( (ymin, ymax) )

    #determine binwidth (pylab examples:scatter_hist.py )
    
    xbinwidth = (xmax-xmin)*xbinwidth
    binsx = np.arange(xmin,xmax+xbinwidth,xbinwidth)
    
    ybinwidth = (ymax-ymin)*ybinwidth
    binsy = np.arange(ymin,ymax+ybinwidth,ybinwidth)

        
    # create scatter & histogram
开发者ID:stijnvanhoey,项目名称:EGU2015,代码行数:67,代码来源:scatter_hist_season.py


示例14: show

    def show(self, location='right', width=0.2, pad=0.05, ticks=None,
             labels=True, log_format=False, box=None,
             box_orientation='vertical', axis_label_text=None,
             axis_label_rotation=None, axis_label_pad=5):
        '''
        Show a colorbar on the side of the image.

        Parameters
        ----------

        location : str, optional
            Where to place the colorbar. Should be one of 'left', 'right', 'top', 'bottom'.

        width : float, optional
            The width of the colorbar relative to the canvas size.

        pad : float, optional
            The spacing between the colorbar and the image relative to the
            canvas size.

        ticks : list, optional
            The position of the ticks on the colorbar.

        labels : bool, optional
            Whether to show numerical labels.

        log_format : bool, optional
            Whether to format ticks in exponential notation

        box : list, optional
            A custom box within which to place the colorbar. This should
            be in the form [xmin, ymin, dx, dy] and be in relative figure
            units. This overrides the location argument.

        box_orientation str, optional
            The orientation of the colorbar within the box. Can be
            'horizontal' or 'vertical'

        axis_label_text str, optional
            Optional text label of the colorbar.
        '''

        self._base_settings['location'] = location
        self._base_settings['width'] = width
        self._base_settings['pad'] = pad
        self._base_settings['ticks'] = ticks
        self._base_settings['labels'] = labels
        self._base_settings['log_format'] = log_format
        self._base_settings['box'] = box
        self._base_settings['box_orientation'] = box_orientation
        self._base_settings['axis_label_text'] = axis_label_text
        self._base_settings['axis_label_rotation'] = axis_label_rotation
        self._base_settings['axis_label_pad'] = axis_label_pad

        if self._parent.image:

            if self._colorbar_axes:
                self._parent._figure.delaxes(self._colorbar_axes)

            if box is None:

                divider = make_axes_locatable(self._parent.ax)

                if location == 'right':
                    self._colorbar_axes = divider.new_horizontal(size=width, pad=pad, axes_class=maxes.Axes)
                    orientation = 'vertical'
                elif location == 'top':
                    self._colorbar_axes = divider.new_vertical(size=width, pad=pad, axes_class=maxes.Axes)
                    orientation = 'horizontal'
                elif location == 'left':
                    warnings.warn("Left colorbar not fully implemented")
                    self._colorbar_axes = divider.new_horizontal(size=width, pad=pad, pack_start=True, axes_class=maxes.Axes)
                    locator = divider.new_locator(nx=0, ny=0)
                    self._colorbar_axes.set_axes_locator(locator)
                    orientation = 'vertical'
                elif location == 'bottom':
                    warnings.warn("Bottom colorbar not fully implemented")
                    self._colorbar_axes = divider.new_vertical(size=width, pad=pad, pack_start=True, axes_class=maxes.Axes)
                    locator = divider.new_locator(nx=0, ny=0)
                    self._colorbar_axes.set_axes_locator(locator)
                    orientation = 'horizontal'
                else:
                    raise Exception("location should be one of: right/top")

                self._parent._figure.add_axes(self._colorbar_axes)

            else:

                self._colorbar_axes = self._parent._figure.add_axes(box)
                orientation = box_orientation

            if log_format:
                format = LogFormatterMathtext()
            else:
                format = None

            self._colorbar = self._parent._figure.colorbar(self._parent.image, cax=self._colorbar_axes,
                                                       orientation=orientation, format=format,
                                                       ticks=ticks)
            if axis_label_text:
#.........这里部分代码省略.........
开发者ID:anizami,项目名称:aplpy_wrapper,代码行数:101,代码来源:colorbar.py


示例15: plot

    def plot(self, axes):
        ''' Plot network on given axes

         :Parameters:
         `axes` : matploltlib Axes
             axes where to draw network
        '''

        classname = self.__class__.__name__

        # Plot samples
        axes.scatter(self.samples[:,0], self.samples[:,1], s=1.0, color='b', alpha=0.25)

        fig = plt.gcf()
        divider = make_axes_locatable(axes)

        # Plot network
        C = self.codebook
        Cx,Cy = C[...,0], C[...,1]
        if classname != 'NG':
            for i in range(C.shape[0]):
                axes.plot (Cx[i,:], Cy[i,:], 'k', alpha=0.85, lw=1.5)
            for i in range(C.shape[1]):
                axes.plot (Cx[:,i], Cy[:,i], 'k', alpha=0.85, lw=1.5)
        axes.scatter (Cx.flatten(), Cy.flatten(), s=50, c= 'w', edgecolors='k', zorder=10)
        axes.axis([0,1,0,1])
        axes.set_xticks([])
        axes.set_yticks([])
        axes.set_aspect(1)

        # Plot distortion
        subaxes = divider.new_vertical(1.0, pad=0.4, sharex=axes)
        fig.add_axes(subaxes)
        subaxes.set_xticks([])
        subaxes.yaxis.set_major_locator(matplotlib.ticker.MaxNLocator(2))
        subaxes.yaxis.set_ticks_position('right')
        subaxes.set_ylabel('Distortion')
        subaxes.set_xlabel('Time')
        #subaxes.axis([0,1,0,1])
        Y = self.distortion[::1]
        X = np.arange(len(Y))/float(len(Y)-1)
        subaxes.plot(X,Y)
        axes.axis([0,1,0,1])

        if classname == 'NG':
            plt.title('Neural Gas', fontsize=20)
        elif classname == 'SOM':
            plt.title('Self-Organizing Map', fontsize=20)
        elif classname == 'DSOM':
            plt.title('Dynamic Self-Organizing Map', fontsize=20)
        if classname == 'NG':
            axes.text(0.5, -0.01,
                      r'$\lambda_i = %.3f,\lambda_f = %.3f, \varepsilon_i=%.3f, \varepsilon_f=%.3f$' % (
                    self.sigma_i, self.sigma_f, self.lrate_i, self.lrate_f),
                      fontsize=16, 
                      horizontalalignment='center',
                      verticalalignment='top',
                      transform = axes.transAxes)
        if classname == 'SOM':
            axes.text(0.5, -0.01,
                      r'$\sigma_i = %.3f,\sigma_f = %.3f, \varepsilon_i=%.3f, \varepsilon_f=%.3f$' % (
                    self.sigma_i, self.sigma_f, self.lrate_i, self.lrate_f),
                      fontsize=16, 
                      horizontalalignment='center',
                      verticalalignment='top',
                      transform = axes.transAxes)
        elif classname == 'DSOM':
            axes.text(0.5, -0.01,
                      r'$elasticity = %.2f$, $\varepsilon = %.3f$' % (self.elasticity, self.lrate),
                      fontsize=16, 
                      horizontalalignment='center',
                      verticalalignment='top',
                      transform = axes.transAxes)
开发者ID:rougier,项目名称:dynamic-som,代码行数:73,代码来源:network.py


示例16: make_axes_locatable

from mpl_toolkits.axes_grid import make_axes_locatable
import  matplotlib.axes as maxes
from matplotlib import cm

if __name__ == '__main__':

    fig = P.figure(figsize=(10,10))
    ax1 = fig.add_subplot(221)
    ax2 = fig.add_subplot(222)
    ax3 = fig.add_subplot(223)
    ax4 = fig.add_subplot(224)

    s1 = ax1.scatter(numpy.random.rand(10),
                     numpy.random.rand(10),
                     c=numpy.random.rand(10))
    divider = make_axes_locatable(ax1)
    cax1 = divider.new_horizontal('5%', pad=0.0, axes_class=maxes.Axes)
    fig.add_axes(cax1)
    c1 = fig.colorbar(s1, cax = cax1,orientation = 'horizontal')

    s2 = ax2.scatter(numpy.random.rand(10),
                     numpy.random.rand(10),
                     c=numpy.random.rand(10),
                     cmap = cm.get_cmap('jet'))
    divider = make_axes_locatable(ax2)
    cax2 = divider.append_axes('right', 0.1, pad=0.1)
    c2 = fig.colorbar(s2, cax = cax2)
    #p =  matplotlib.patches.Patch(color=cm.get_cmap('jet'))
    #ax2.legend([p],['Test'])

    s3 = ax3.scatter(numpy.random.rand(10),
开发者ID:eddienko,项目名称:SamPy,代码行数:31,代码来源:colorbarExample2.py


示例17: makePlot

def makePlot(in_m, channel_names=None, fig=None, x_tick_rot=0, size=None, 
	     cmap=plt.cm.RdBu_r, colorbar=True, color_anchor=None, title=None, max_val=None, min_val=None):

	N = in_m.shape[0]
	ind = np.arange(N)  # the evenly spaced plot indices                                                    

	def channel_formatter(x, pos=None):
		thisind = np.clip(int(x), 0, N - 1)
		return channel_names[thisind]

	if fig is None:
		fig=plt.figure()

	if size is not None:
		fig.set_figwidth(size[0])
		fig.set_figheight(size[1])
	wid=fig.get_figwidth()
	ht=fig.get_figheight()
	ax_im = fig.add_subplot(1, 1, 1)

	#If you want to draw the colorbar:
	# what is make_axes_locatable?
        divider = make_axes_locatable(ax_im)
        ax_cb = divider.new_vertical(size="20%", pad=0.2, pack_start=True)
        fig.add_axes(ax_cb)

	#Make a copy of the input, so that you don't make changes to the original                               
	#data provided                                                                                          
	m = in_m.copy()

	
	#Null the upper triangle, so that you don't get the redundant and
	#the diagonal values:                                                                            
	#idx_null = triu_indices(m.shape[0])
	#m[idx_null] = np.nan

	#Extract the minimum and maximum values for scaling of the
	#colormap/colorbar:
	if max_val is None:
		max_val = np.nanmax(m)
		min_val = np.nanmin(m)

	if color_anchor is None:
		color_min = min_val
		color_max = max_val
	elif color_anchor == 0:
		bound = max(abs(max_val), abs(min_val))
		color_min = -bound
		color_max = bound
	else:
		color_min = color_anchor[0]
		color_max = color_anchor[1]

	#The call to imshow produces the matrix plot:
	im = ax_im.imshow(m, origin='upper', interpolation='nearest',
	vmin=color_min, vmax=color_max, cmap=cmap)

	#Formatting:
	ax = ax_im
	ax.grid(True)
	#Label each of the cells with the row and the column:
	if channel_names is not None:
		for i in xrange(0, m.shape[0]):
			if i < (m.shape[0] - 1):
				ax.text(i - 0.3, i, channel_names[i], rotation=x_tick_rot)
			if i > 0:
				ax.text(-1, i + 0.3, channel_names[i], horizontalalignment='right')

        ax.set_axis_off()
        ax.set_xticks(np.arange(N))
        ax.xaxis.set_major_formatter(ticker.FuncFormatter(channel_formatter))
        fig.autofmt_xdate(rotation=x_tick_rot)
        ax.set_yticks(np.arange(N))
        ax.set_yticklabels(channel_names)
        ax.set_ybound([-0.5, N - 0.5])
        ax.set_xbound([-0.5, N - 1.5])

	#Make the tick-marks invisible:                                                                         
	for line in ax.xaxis.get_ticklines():
		line.set_markeredgewidth(0)

	for line in ax.yaxis.get_ticklines():
		line.set_markeredgewidth(0)

	ax.set_axis_off()

	if title is not None:
		ax.set_title(title)

	#The following produces the colorbar and sets the ticks                                                 
	if colorbar:
        #Set the ticks - if 0 is in the interval of values, set that, as well                               
        #as the maximal and minimal values:                                                                 
		if min_val < 0:
			ticks = [min_val, 0, max_val]
		#Otherwise - only set the minimal and maximal value:                                                
		else:
			ticks = [min_val, max_val]

        #This makes the colorbar:                                                                           
#.........这里部分代码省略.........
开发者ID:ecounterman,项目名称:megavista,代码行数:101,代码来源:cohAnalysis.py


示例18: plot_ica_components

def plot_ica_components(ica, picks=None, ch_type='mag', res=64,
                        layout=None, vmin=None, vmax=None, cmap='RdBu_r',
                        sensors=True, colorbar=False, title=None,
                        show=True, outlines='head', contours=6,
                        image_interp='bilinear'):
    """Project unmixing matrix on interpolated sensor topogrpahy.

    Parameters
    ----------
    ica : instance of mne.preprocessing.ICA
        The ICA solution.
    picks : int | array-like | None
        The indices of the sources to be plotted.
        If None all are plotted in batches of 20.
    ch_type : 'mag' | 'grad' | 'planar1' | 'planar2' | 'eeg'
        The channel type to plot. For 'grad', the gradiometers are
        collected in pairs and the RMS for each pair is plotted.
    layout : None | Layout
        Layout instance specifying sensor positions (does not need to
        be specified for Neuromag data). If possible, the correct layout is
        inferred from the data.
    vmin : float | callable
        The value specfying the lower bound of the color range.
        If None, and vmax is None, -vmax is used. Else np.min(data).
        If callable, the output equals vmin(data).
    vmax : float | callable
        The value specfying the upper bound of the color range.
        If None, the maximum absolute value is used. If vmin is None,
        but vmax is not, defaults to np.min(data).
        If callable, the output equals vmax(data).
    cmap : matplotlib colormap
        Colormap.
    sensors : bool | str
        Add markers for sensor locations to the plot. Accepts matplotlib
        plot format string (e.g., 'r+' for red plusses). If True, a circle
        will be used (via .add_artist). Defaults to True.
    colorbar : bool
        Plot a colorbar.
    res : int
        The resolution of the topomap image (n pixels along each side).
    show : bool
        Call pyplot.show() at the end.
    outlines : 'head' | dict | None
            The outlines to be drawn. If 'head', a head scheme will be drawn.
            If dict, each key refers to a tuple of x and y positions. The
            values in 'mask_pos' will serve as image mask. If None,
            nothing will be drawn. defaults to 'head'.
    contours : int | False | None
        The number of contour lines to draw. If 0, no contours will be drawn.
    image_interp : str
        The image interpolation to be used. All matplotlib options are
        accepted.

    Returns
    -------
    fig : instance of matplotlib.pyplot.Figure or list
        The figure object(s).
    """
    import matplotlib.pyplot as plt
    from mpl_toolkits.axes_grid import make_axes_locatable

    if picks is None:  # plot components by sets of 20
        n_components = ica.mixing_matrix_.shape[1]
        p = 20
        figs = []
        for k in range(0, n_components, p):
            picks = range(k, min(k + p, n_components))
            fig = plot_ica_components(ica, picks=picks,
                                      ch_type=ch_type, res=res, layout=layout,
                                      vmax=vmax, cmap=cmap, sensors=sensors,
                                      colorbar=colorbar, title=title,
                                      show=show, outlines=outlines,
                                      contours=contours,
                                      image_interp=image_interp)
            figs.append(fig)
        return figs
    elif np.isscalar(picks):
        picks = [picks]

    data = np.dot(ica.mixing_matrix_[:, picks].T,
                  ica.pca_components_[:ica.n_components_])

    if ica.info is None:
        raise RuntimeError('The ICA\'s measurement info is missing. Please '
                           'fit the ICA or add the corresponding info object.')

    data_picks, pos, merge_grads, names, _ = _prepare_topo_plot(ica, ch_type,
                                                                layout)
    pos, outlines = _check_outlines(pos, outlines)
    if outlines not in (None, 'head'):
        image_mask, pos = _make_image_mask(outlines, pos, res)
    else:
        image_mask = None

    data = np.atleast_2d(data)
    data = data[:, data_picks]

    # prepare data for iteration
    fig, axes = _prepare_trellis(len(data), max_col=5)
    if title is None:
#.........这里部分代码省略.........
开发者I

鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python axislines.SubplotZero类代码示例发布时间:2022-05-27
下一篇:
Python mpiunittest.main函数代码示例发布时间: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