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


Python ScalarFormatter.set_scientific方法代码示例

本文整理汇总了Python中matplotlib.ticker.ScalarFormatter.set_scientific方法的典型用法代码示例。如果您正苦于以下问题:Python ScalarFormatter.set_scientific方法的具体用法?Python ScalarFormatter.set_scientific怎么用?Python ScalarFormatter.set_scientific使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在matplotlib.ticker.ScalarFormatter的用法示例。


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

示例1: set_arbitrary_ticks

# 需要导入模块: from matplotlib.ticker import ScalarFormatter [as 别名]
# 或者: from matplotlib.ticker.ScalarFormatter import set_scientific [as 别名]
def set_arbitrary_ticks(ax,axis,events,index1,index2,fontsize=10,fontname='sans'):
    """
    if an axis is using an unknown scale or we just with to use the data to scale 
    the axis
    """

    buff = 0.02
    formatter = ScalarFormatter(useMathText=True)
    formatter.set_scientific(True)
    formatter.set_powerlimits((-3,3))

    ## handle data edge buffers
    if axis in ['x','both']:
        bufferX = buff * (events[:,index1].max() - events[:,index1].min())
        ax.set_xlim([events[:,index1].min()-bufferX,events[:,index1].max()+bufferX])
        ax.xaxis.set_major_formatter(formatter)
    if axis in ['y','both']:
        bufferY = buff * (events[:,index2].max() - events[:,index2].min())
        ax.set_ylim([events[:,index2].min()-bufferY,events[:,index2].max()+bufferY])
        ax.yaxis.set_major_formatter(formatter)

    if axis in ['x','both']:
        for tick in ax.xaxis.get_major_ticks():
            tick.label.set_fontsize(fontsize-2) 
            tick.label.set_fontname(fontname)
    if axis in ['y','both']:
        for tick in ax.yaxis.get_major_ticks():
            tick.label.set_fontsize(fontsize-2) 
            tick.label.set_fontname(fontname)
开发者ID:ajrichards,项目名称:cytostream,代码行数:31,代码来源:PlottingFns.py

示例2: quickPlot

# 需要导入模块: from matplotlib.ticker import ScalarFormatter [as 别名]
# 或者: from matplotlib.ticker.ScalarFormatter import set_scientific [as 别名]
def quickPlot(filename, path, datalist, xlabel="x", ylabel="y", xrange=["auto", "auto"], yrange=["auto", "auto"], yscale="linear", xscale="linear", col=["r", "b"]):
	"""Plots Data to .pdf File in Plots Folder Using matplotlib"""
	if "plots" not in os.listdir(path):
		os.mkdir(os.path.join(path, "plots"))
	coltab = col*10
	seaborn.set_context("notebook", rc={"lines.linewidth": 1.0})
	formatter = ScalarFormatter(useMathText=True)
	formatter.set_scientific(True)
	formatter.set_powerlimits((-2, 3))
	fig = Figure(figsize=(6, 6))
	ax = fig.add_subplot(111)
	for i, ydata in enumerate(datalist[1:]):
		ax.plot(datalist[0], ydata, c=coltab[i])
	ax.set_title(filename)
	ax.set_yscale(yscale)
	ax.set_xscale(xscale)
	ax.set_xlabel(xlabel)
	ax.set_ylabel(ylabel)
	if xrange[0] != "auto":
		ax.set_xlim(xmin=xrange[0])
	if xrange[1] != "auto":
		ax.set_xlim(xmax=xrange[1])
	if yrange[0] != "auto":
		ax.set_ylim(ymin=yrange[0])
	if yrange[1] != "auto":
		ax.set_ylim(ymax=yrange[1])
	if yscale == "linear":
		ax.yaxis.set_major_formatter(formatter)
	ax.xaxis.set_major_formatter(formatter)
	canvas = FigureCanvasPdf(fig)
	canvas.print_figure(os.path.join(path, "plots", filename+".pdf"))
	return
开发者ID:jzmnd,项目名称:myfunctions,代码行数:34,代码来源:myfunctions.py

示例3: setAxes

# 需要导入模块: from matplotlib.ticker import ScalarFormatter [as 别名]
# 或者: from matplotlib.ticker.ScalarFormatter import set_scientific [as 别名]
def setAxes(ax):
    globalAxesSettings(ax)
    ax.yaxis.set_major_locator(MaxNLocator(4))
    ax.xaxis.set_minor_locator(AutoMinorLocator(2))
    ax.yaxis.set_minor_locator(AutoMinorLocator(2))
    f = ScalarFormatter(useMathText=True)
    f.set_scientific(True)
    f.set_powerlimits((0, 3))
    ax.yaxis.set_major_formatter(f)
开发者ID:MattNolanLab,项目名称:ei-attractor,代码行数:11,代码来源:plot_bump_ranges.py

示例4: plotResults

# 需要导入模块: from matplotlib.ticker import ScalarFormatter [as 别名]
# 或者: from matplotlib.ticker.ScalarFormatter import set_scientific [as 别名]
def plotResults(a1, a2, b1, b2, fname, ofname):
  #read data from csv file
  print('Reading data from csv file...')
  a = np.genfromtxt(fname, delimiter=';')
  noRows = a.shape[0]
  noCols = a.shape[1]
  a = a[0:noRows, 0:(noCols-1)]
  deltaX = a2-a1
  deltaY = b2-b1
  stepX = deltaX / (noRows)
  stepY = deltaY / (noCols-1)
  print('done.')

  print('Preparing plot...')
  fig = plt.figure(figsize=(5, 3), dpi=500)
  ax = fig.gca(projection='3d')
  X = np.arange(a1, a2, stepX)
  Y = np.arange(b1, b2, stepY)
  X, Y = np.meshgrid(X, Y)
  Z = a
  vMax=Z.max()
  vMin=Z.min()
  vMax=vMax+0.1*abs(vMax)
  vMin=vMin-0.1*abs(vMin)
  surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.Greys_r,
        linewidth=0, antialiased=True, vmin=vMin, vmax=vMax)
  zAxisFormatter = ScalarFormatter()
  zAxisFormatter.set_scientific(True)
  zAxisFormatter.set_powerlimits((0, 1))
  #ax.zaxis.set_major_formatter(zAxisFormatter)
  print('Drawing...')
  fontSize=8 #set fontsize on plot
  ax.set_xlabel('x', fontsize=fontSize)
  ax.set_ylabel('y', fontsize=fontSize)
  ax.zaxis.set_rotate_label(False)
  ax.set_zlabel('u(x,y)', fontsize=fontSize, rotation=90)
  ax.view_init(27, 35)
  t = ax.zaxis.get_offset_text()
  t.set_size(fontSize-2)
  #t.set_position((0,0))
  t.set_rotation(45)
  t.set_verticalalignment('center')
  #t.set_z(0)
  plt.setp(ax.get_xticklabels(), fontsize=fontSize)
  plt.setp(ax.get_yticklabels(), fontsize=fontSize)
  plt.setp(ax.get_zticklabels(), fontsize=fontSize)
  plt.legend()
  cbar=fig.colorbar(surf, shrink=0.75, aspect=15)
  cbar.ax.tick_params(labelsize=fontSize)
  
  #plt.show()
  plt.savefig(filename=ofname, format='eps')
  plt.close()
开发者ID:tomaszhof,项目名称:scripts,代码行数:55,代码来源:pyPlotSolution.py

示例5: __init__

# 需要导入模块: from matplotlib.ticker import ScalarFormatter [as 别名]
# 或者: from matplotlib.ticker.ScalarFormatter import set_scientific [as 别名]
 def __init__(self, figure, x_label='', y_label=''):
     """
     Initializes a _plot_list, which contains plot_data.
     
     Keyword arguments:
     figure -- The matplotlib figure to which the plots are added.
     x_label -- The x-axis label to use for all plots (default: '')
     y_label -- The y-axis label to use for all plots (default: '')
     """
     self.x_label = x_label
     self.y_label = y_label
     self.figure = figure
     
     self.sub_plots = []
     # set default formatter for the time being
     frmt = ScalarFormatter(useOffset = True)   
     frmt.set_powerlimits((-3,3))
     frmt.set_scientific(True)
     self.default_formatter = (frmt, frmt)
开发者ID:ganxueliang88,项目名称:ping-graph-tool,代码行数:21,代码来源:wxplot.py

示例6: plot_learn_zips_summary

# 需要导入模块: from matplotlib.ticker import ScalarFormatter [as 别名]
# 或者: from matplotlib.ticker.ScalarFormatter import set_scientific [as 别名]
def plot_learn_zips_summary(name,control_zip,learn_zips,vals,skip_rows=0,png=False,num_mins=3):
    _,control = read_zip(control_zip,skip_rows=skip_rows)
    baseline = 1
    scale = baseline/numpy.mean(control)
    
    figsize = (5,2.5)
    pylab.figure(figsize=figsize,dpi=300)
    
    means = []
    
    for learn_zip in learn_zips:
        _,learn = read_zip(learn_zip,skip_rows=skip_rows)
        means.append(numpy.mean(learn)*scale)
    
    sorted_means = list(means)
    sorted_means.sort()
    min_means_loc = [vals[means.index(sorted_means[i])] for i in range(num_mins)]
    
    ax = pylab.axes((0.18,0.2,0.8,0.7))
    
    fmt = ScalarFormatter()
    fmt.set_powerlimits((-3,4))
    fmt.set_scientific(True)
    ax.xaxis.set_major_formatter(fmt)
    ax.xaxis.set_minor_locator(MultipleLocator(float(vals[1])-float(vals[0])))
    
    pylab.plot(vals,means,color='k',linewidth=2)
    pylab.plot(min_means_loc,sorted_means[:num_mins],'o',markerfacecolor='None')
    pylab.plot(min_means_loc[0],sorted_means[0],'ko')
    
    pylab.axhline(baseline,linestyle='--',linewidth=1,color='k')
    
    pylab.ylabel('Mean relative error\n(learning vs. analytic)\n\n',ha='center')    
    pylab.xlabel(name)
    pylab.axis('tight')
    
    if png:
        if not os.path.exists('png'):
            os.mkdir('png')
        pylab.savefig('png/'+learn_zips[0].split('-')[0]+'-summary.png',figsize=figsize,dpi=600)
    else:
        pylab.show()
开发者ID:tbekolay,项目名称:bekolay,代码行数:44,代码来源:learning_plots.py

示例7: CreatePlot

# 需要导入模块: from matplotlib.ticker import ScalarFormatter [as 别名]
# 或者: from matplotlib.ticker.ScalarFormatter import set_scientific [as 别名]
	def CreatePlot(self): #just sample plot, it will be replaced with real one after you load some data
		formatter = ScalarFormatter()
		formatter.set_scientific(True)
		formatter.set_powerlimits((0,0)) 
		self.figure = Figure()
		self.figure.set_facecolor('white')
		self.figure.subplots_adjust(bottom=0.3, left=0.25) 
		self.axes = self.figure.add_subplot(111)
		self.axes.xaxis.set_major_formatter(formatter) 
		self.axes.yaxis.set_major_formatter(formatter) 
		x = np.arange(0,6,.01)
		y = np.sin(x**2)*np.exp(-x)
		self.axes.plot(x,y, ls = 'dotted',label = "This is just a sample plot and it will be replaced with\nthe real plot once when you load some data...")
		self.setScales()
	
		handles, labels = self.axes.get_legend_handles_labels()
		self.axes.legend(handles[::-1], labels[::-1], fancybox=True)
		frame=self.axes.get_frame()
		frame.set_alpha(0.4) 
		self.canvas = FigCanvas(self.plotPanel, wx.ID_ANY, self.figure) #jako bitna stavka
		return 1
开发者ID:vzupanovic,项目名称:skripte,代码行数:23,代码来源:benchmarkGUI.py

示例8: plot

# 需要导入模块: from matplotlib.ticker import ScalarFormatter [as 别名]
# 或者: from matplotlib.ticker.ScalarFormatter import set_scientific [as 别名]

#.........这里部分代码省略.........
			field1 = statsResults.getColumn('EffectSize')
			field2 = None
			
			bLogScale = statsResults.confIntervMethod.bRatio
			xLabel = statsResults.confIntervMethod.plotLabel
			
		features = statsResults.getColumn('Features')	# get sorted feature labels

		# *** Truncate feature labels
		highlightedFeatures = list(self.preferences['Highlighted sample features'])
		if self.preferences['Truncate feature names']:
			length = self.preferences['Length of truncated feature names']
			
			for i in xrange(0, len(features)):
				if len(features[i]) > length+3:
					features[i] = features[i][0:length] + '...'

			for i in xrange(0, len(highlightedFeatures)):
				if len(highlightedFeatures[i]) > length+3:
					highlightedFeatures[i] = highlightedFeatures[i][0:length] + '...'
						
		# *** Check that there is at least one significant feature
		if len(features) <= 0:
			self.emptyAxis('No significant features')			
			return

		# *** Set figure size
		padding = 0.2							 #inches
		heightBottomLabels = 0.4		# inches
		
		imageHeight = len(features)*self.figHeightPerRow + padding + heightBottomLabels
		self.fig.set_size_inches(self.figWidth, imageHeight)	
							
		yPlotOffsetFigSpace = heightBottomLabels / imageHeight 
		heightPlotFigSpace = 1.0 - yPlotOffsetFigSpace - padding / imageHeight
			 
		yLabelBounds = self.yLabelExtents(features, 8)
		xPlotOffsetFigSpace = yLabelBounds.width + 0.1 / self.figWidth
		widthPlotFigSpace = 1.0 - xPlotOffsetFigSpace - padding / self.figWidth
		
		axesBar = self.fig.add_axes([xPlotOffsetFigSpace,yPlotOffsetFigSpace,widthPlotFigSpace,heightPlotFigSpace])
		
		# *** Plot data
		barHeight = 0.35 
		
		if bLogScale:
			field1 = np.log10(field1)
			xLabel = 'log(' + xLabel + ')'
			if field2 != None:
				field2 = np.log10(field2)
		
		if field2 == None:
			rects1 = axesBar.barh(np.arange(len(features)), field1, height=barHeight)	
			axesBar.set_yticks(np.arange(len(features)) + 0.5*barHeight)		
			axesBar.set_ylim([0, len(features)-1.0 + barHeight + 0.1])			
		elif field2 != None:
			rects2 = axesBar.barh(np.arange(len(features)), field2, height=barHeight, color=profile2Colour)	
			rects1 = axesBar.barh(np.arange(len(features))+barHeight, field1, height=barHeight, color=profile1Colour)
			axesBar.set_yticks(np.arange(len(features)) + barHeight)		
			axesBar.set_ylim([0, len(features)-1.0 + 2*barHeight + 0.1])			 
				
		axesBar.set_yticklabels(features)	
		axesBar.set_xlabel(xLabel)
		
		scalarFormatter = ScalarFormatter(useMathText=False)
		scalarFormatter.set_scientific(True)
		scalarFormatter.set_powerlimits((-3,4))
		axesBar.xaxis.set_major_formatter(scalarFormatter)

		# *** Prettify plot
		if self.legendPos != -1 and field2 != None:
			legend = axesBar.legend([rects1[0], rects2[0]], (profile.sampleNames[0], profile.sampleNames[1]), loc=self.legendPos)
			legend.get_frame().set_linewidth(0)
				
		for label in axesBar.get_yticklabels():
			if label.get_text() in highlightedFeatures:
					label.set_color('red')
			
		for a in axesBar.yaxis.majorTicks:
			a.tick1On=False
			a.tick2On=False
				
		for a in axesBar.xaxis.majorTicks:
			a.tick1On=True
			a.tick2On=False
			
		for line in axesBar.yaxis.get_ticklines(): 
			line.set_color(axesColour)
				
		for line in axesBar.xaxis.get_ticklines(): 
			line.set_color(axesColour)
			
		for loc, spine in axesBar.spines.iteritems():
			if loc in ['right','top']:
					spine.set_color('none') 
			else:
				spine.set_color(axesColour)
		
		self.updateGeometry()			 
		self.draw()
开发者ID:beiko-lab,项目名称:STAMP,代码行数:104,代码来源:Bar.py

示例9: range

# 需要导入模块: from matplotlib.ticker import ScalarFormatter [as 别名]
# 或者: from matplotlib.ticker.ScalarFormatter import set_scientific [as 别名]
plot_m.grid(True)

plot_I = fig.add_subplot(2, 2, 4, sharex=plot_a)
if isLog:
  plot = plot_I.semilogx
else:
  plot = plot_I.plot

for planet in range(nb_planete):
  plot(t[planet][id_min:id_max+1], I[planet][id_min:id_max+1], color=colors[planet], label='PLANETE'+str(planet))
plot_I.set_xlabel("time [years]")
plot_I.set_ylabel("Inclination [degrees]")
plot_I.grid(True)

myyfmt = ScalarFormatter(useOffset=False)
myyfmt.set_scientific(True)
myyfmt.set_powerlimits((-2, 3)) 
myxfmt = ScalarFormatter(useOffset=True)
myxfmt._set_offset(1e5)
myxfmt.set_scientific(True)
myxfmt.set_powerlimits((-3, 3)) 

plot_a.xaxis.set_major_formatter(myxfmt)
plot_I.yaxis.set_major_formatter(myyfmt)


nom_fichier_plot = "evolution_planete"
fig.savefig('%s.%s' % (nom_fichier_plot, OUTPUT_EXTENSION), format=OUTPUT_EXTENSION)

pl.show()
开发者ID:Autiwa,项目名称:mercury-90,代码行数:32,代码来源:mercury-plot-planets.py

示例10: compare_plots_one_param_line_hist

# 需要导入模块: from matplotlib.ticker import ScalarFormatter [as 别名]
# 或者: from matplotlib.ticker.ScalarFormatter import set_scientific [as 别名]
def compare_plots_one_param_line_hist(list_of_pos_by_name,param,cl,color_by_name,cl_lines_flag=True,legend='right',analyticPDF=None):


    """
    Plots a gaussian kernel density estimate for a set
    of Posteriors onto the same axis.

    @param list_of_pos: a list of Posterior class instances.

    @param plot1DParams: a dict; {paramName:Nbins}

    """

    from scipy import seterr as sp_seterr

    #Create common figure
    myfig=plt.figure(figsize=(6,4.5),dpi=150)
  #myfig.add_axes([0.1,0.1,0.65,0.85])
  #myfig.add_axes([0.15,0.15,0.6,0.76])
    axes=plt.Axes(myfig,[0.15,0.15,0.6,0.76])
    myfig.add_axes(axes)
    majorFormatterX=ScalarFormatter(useMathText=True)
    majorFormatterX.format_data=lambda data:'%.6g'%(data)
    majorFormatterY=ScalarFormatter(useMathText=True)
    majorFormatterY.format_data=lambda data:'%.6g'%(data)
    majorFormatterX.set_scientific(True)
    majorFormatterY.set_scientific(True)

    list_of_pos=list_of_pos_by_name.values()
    list_of_pos_names=list_of_pos_by_name.keys()

    allmins=map(lambda a: np.min(a[param].samples), list_of_pos)
    allmaxes=map(lambda a: np.max(a[param].samples), list_of_pos)
    min_pos=np.min(allmins)
    max_pos=np.max(allmaxes)

    injvals=[]

    patch_list=[]
    max_y=0

    posbins=np.linspace(min_pos,max_pos,50)

    for name,posterior in list_of_pos_by_name.items():
        colour=color_by_name[name]
        #myfig.gca(autoscale_on=True)
        if posterior[param].injval:
            injvals.append(posterior[param].injval)

        try:
            n,bins=np.histogram(posterior[param].samples,bins=posbins,normed=True,new=True)
        except:
            n,bins=np.histogram(posterior[param].samples,bins=posbins,normed=True)
        if min(bins)==max(bins):
            print 'Skipping '+param
            continue
        locmaxy=max(n)
        if locmaxy>max_y: max_y=locmaxy
#(n, bins, patches)=plt.hist(posterior[param].samples,bins=bins,facecolor='white',label=name,normed=True,hold=True,color=color_by_name[name])#range=(min_pos,max_pos)
        (n, bins, patches)=plt.hist(posterior[param].samples,bins=bins,histtype='step',label=name,normed=True,hold=True,color=color_by_name[name])
        patch_list.append(patches[0])

    Nchars=max(map(lambda d:len(majorFormatterX.format_data(d)),axes.get_xticks()))
    if Nchars>8:
      Nticks=3
    elif Nchars>5:
      Nticks=4
    elif Nchars>4:
      Nticks=6
    else:
      Nticks=6
    locatorX=mpl.ticker.MaxNLocator(nbins=Nticks)
    locatorX.view_limits(bins[0],bins[-1])
    axes.xaxis.set_major_locator(locatorX)

    plt.xlim(min_pos,max_pos)
    top_cl_intervals_list={}
    pos_names=list_of_pos_by_name.keys()


    for name,posterior in list_of_pos_by_name.items():
        #toppoints,injectionconfidence,reses,injection_area,cl_intervals=bppu.greedy_bin_one_param(posterior,{param:greedyBinSizes[param]},[cl])
        cl_intervals=posterior[param].prob_interval([cl])
        colour=color_by_name[name]
        if cl_intervals[0] is not None and cl_lines_flag:
            try:
                plt.plot([cl_intervals[0][0],cl_intervals[0][0]],[0,max_y],color=colour,linestyle='--')
                plt.plot([cl_intervals[0][1],cl_intervals[0][1]],[0,max_y],color=colour,linestyle='--')
            except:
                print "MAX_Y",max_y,[cl_intervals[0][0],cl_intervals[0][0]],[cl_intervals[0][1],cl_intervals[0][1]]
        top_cl_intervals_list[name]=(cl_intervals[0][0],cl_intervals[0][1])

    if cl_lines_flag:
        pos_names.append(str(int(cl*100))+'%')
        patch_list.append(mpl.lines.Line2D(np.array([0.,1.]),np.array([0.,1.]),linestyle='--',color='black'))

    plt.grid()
    plt.xlim(min_pos,max_pos)
    if legend is not None:
      oned_legend=plt.figlegend(patch_list,pos_names,'right')
#.........这里部分代码省略.........
开发者ID:GeraintPratten,项目名称:lalsuite,代码行数:103,代码来源:cbcBayesCompPos.py

示例11: ra_plot

# 需要导入模块: from matplotlib.ticker import ScalarFormatter [as 别名]
# 或者: from matplotlib.ticker.ScalarFormatter import set_scientific [as 别名]
def ra_plot(array_dict, tcas_ra_array, tcas_ctl_array, tcas_up_array, tcas_down_array, 
            vert_ctl_array, sens_array, filename, orig, dest, tstart, tend):
    '''plot tcas: vertical speed + controls    '''
    import matplotlib.pyplot as plt
    from matplotlib.ticker import ScalarFormatter 
    formatter = ScalarFormatter(useOffset=False) 
    formatter.set_powerlimits((-8,8)) 
    formatter.set_scientific(False) 
    formatter.set_useOffset(0.0) 

    plt.figure(figsize=(15,15)) #set size in inches
    plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=0.5)
    
    # top time series plot
    axts    = plt.subplot2grid((8, 1), (0, 0), rowspan=2) #time series    
    axts.xaxis.set_major_formatter(formatter) 
    series_names = array_dict.keys()  #only first 4
    series_formats = ['k','r','g','b']    #color codes
    for i,nm in enumerate(series_names):
        ln=axts.plot(array_dict[nm], series_formats[i], alpha=0.45)
        plt.setp(ln, linewidth=2)
    leg = axts.legend(series_names, 'upper left', fancybox=True)
    leg.get_frame().set_alpha(0.5)
    axts.grid(True, color='gray')
    plt.title('Vertical Speed (fpm)')
    axts.autoscale(enable=False)
    
    # tcas ra
    ax_ra = plt.subplot2grid((8, 1), (2, 0), sharex=axts)     # 
    ra_states = tcas_ra_array.values_mapping.values()
    ra_states = [s.replace('Most Dangerous','') for s in ra_states]
    ra_array = tcas_ra_array.data 
    plot_mapped_array(plt, ax_ra, ra_states, ra_array, title="TCAS RA")

    # combined control
    ax_ctl = plt.subplot2grid((8, 1), (3, 0), sharex=axts)     # 
    ctl_states = tcas_ctl_array.values_mapping.values()
    ctl_states = [s.replace('Advisory','Advzy').replace('Corrective', 'Corr.') for s in ctl_states]
    ctl_array = tcas_ctl_array.data 
    plot_mapped_array(plt, ax_ctl, ctl_states, ctl_array, title="TCAS Combined Control")

    # up and down advisory
    ax_updown   = plt.subplot2grid((8, 1), (4, 0), sharex=axts, rowspan=2)  
    up_states   = [' ']+tcas_up_array.values_mapping.values()
    down_states = [' ']+tcas_down_array.values_mapping.values()
    ud_states    = up_states + down_states
    
    def disp_state(st):
        st = st.replace('Descent Corrective','Desc Corr.')
        st = st.replace('Descend ','Desc>')
        st = st.replace('Advisory','Advzy').replace('advisory','Advzy')
        st = st.replace("Don't Climb ","Don't Climb>")
        return st

    ud_states = [ disp_state(s) for s in ud_states]
    plt.yticks( np.arange(len(ud_states)), ud_states )   

    up_array = tcas_up_array.data + 1 # adjust for display
    ax_updown.plot(up_array, 'g')
    down_array = tcas_down_array.data + len(up_states)+1 # adjust for display
    ax_updown.plot(down_array, 'r')
    ax_updown.grid(True, color='gray')
    plt.ylim(0, len(up_states) + len(down_states)) 
    plt.title('TCAS Up/Down Advisory')
    
    # vertical control
    ax_vert   = plt.subplot2grid((8, 1), (6, 0), sharex=axts)  
    vert_states   = vert_ctl_array.values_mapping.values()    
    vert_states = [' ']+[s.replace("Advisory is not one of the following types",'NA') for s in vert_states]
    vert_array = vert_ctl_array.data + 1
    plot_mapped_array(plt, ax_vert, vert_states, vert_array, title="TCAS Vertical Control")
    
    #sensitivity mode    
    ax_sens   = plt.subplot2grid((8, 1), (7, 0), sharex=axts)  
    sens_states   = sens_array.values_mapping.values()    
    sens_states = [' ']+[s.replace("SL = ",'') for s in sens_states]
    sens_arr = sens_array.data + 1 # adjust for display
    plot_mapped_array(plt, ax_sens, sens_states, sens_arr, title="TCAS Sensitivity Mode")

    plt.xlabel('time index')
    plt.xlim(tstart, tend) 
    plt.suptitle('TCAS RA: '+filename.value + '\n  '+orig.value['code']['icao']+'-'+dest.value['code']['icao']+ ' '+str(tstart)+':'+str(tend))
    return plt
开发者ID:catawbasam,项目名称:asias_fds_profiles,代码行数:85,代码来源:tcas_profile.py

示例12: ConvexHull

# 需要导入模块: from matplotlib.ticker import ScalarFormatter [as 别名]
# 或者: from matplotlib.ticker.ScalarFormatter import set_scientific [as 别名]
for simplex in hull.simplices:
    large_plt, = plt.plot(points[simplex,0], points[simplex,1], 'k-', linewidth = 4.0, label = '68th percentile')

# 95 % contour
huge_plt = []
hull = ConvexHull( points[0 : int(round(len(tmp_points) * 0.95))] )
for simplex in hull.simplices:
    huge_plt, = plt.plot(points[simplex,0], points[simplex,1], 'g-', linewidth = 4.0, label = '95th percentile')

plt.axis([0.02, 50, 0.02, 50])
plt.xscale('log')
plt.yscale('log')
plt.axhline(y=1, linewidth = 2.0, color = 'r')
plt.axvline(x=1, linewidth = 2.0, color = 'r')
a = plt.gca()
a.set_xticks([0.025, 0.1, 1, 10, 40])
a.set_yticks([0.025, 0.1, 1, 10, 40])

formatter = ScalarFormatter()
formatter.set_scientific(False) 

a.xaxis.set_major_formatter(formatter)
a.yaxis.set_major_formatter(formatter)

plt.xlabel("Throughput improvement")
plt.ylabel("Delay improvement")

plt.legend([median_plt, large_plt, huge_plt], ["50th percentile", "68th percentile", "95th percentile"])

plt.show()
开发者ID:keithw,项目名称:dissertation,代码行数:32,代码来源:random_sampling_contours.py

示例13: dict

# 需要导入模块: from matplotlib.ticker import ScalarFormatter [as 别名]
# 或者: from matplotlib.ticker.ScalarFormatter import set_scientific [as 别名]
ax.tick_params(labeltop="off")  # don't put tick labels at the top
ax2.xaxis.tick_bottom()

d = 0.015  # how big to make the diagonal lines in axes coordinates
# arguments to pass plot, just so we don't keep repeating them
kwargs = dict(transform=ax.transAxes, color="k", clip_on=False)
ax.plot((-d, +d), (-d, +d), **kwargs)  # top-left diagonal
ax.plot((1 - d, 1 + d), (-d, +d), **kwargs)  # top-right diagonal

kwargs.update(transform=ax2.transAxes)  # switch to the bottom axes
ax2.plot((-d, +d), (1 - d, 1 + d), **kwargs)  # bottom-left diagonal
ax2.plot((1 - d, 1 + d), (1 - d, 1 + d), **kwargs)  # bottom-right diagonal

ax.ticklabel_format(style="sci", axis="y")  # scientific notation

sf = ScalarFormatter()
sf.set_scientific(True)

# What's cool about this is that now if we vary the distance between
# ax and ax2 via f.subplots_adjust(hspace=...) or plt.subplot_tool(),
# the diagonal lines will move accordingly, and stay right at the tips
# of the spines they are 'breaking'

# draw a bbox of the region of the inset axes in the parent axes and
# connecting lines between the bbox and the inset axes area
mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")

fig.subplots_adjust(wspace=0.1)

plt.show()
开发者ID:caja-matematica,项目名称:pyRBC,代码行数:32,代码来源:broken_axis.py

示例14: LightCurve

# 需要导入模块: from matplotlib.ticker import ScalarFormatter [as 别名]
# 或者: from matplotlib.ticker.ScalarFormatter import set_scientific [as 别名]
def LightCurve():
    
    from astropy.io import fits
    import matplotlib.pyplot as plt
    from matplotlib import pylab
    from matplotlib.ticker import ScalarFormatter

    # open and set the fermi data
    # set file name
    if object == '3C454':
        fermiFile = '3C454.3_86400.lc.txt'

    hdulist = fits.open("/Users/Stephanie/Fermi/%s/%s" % (object, fermiFile))
    tbdata = hdulist[1].data
    time = []
    mag = []
    for time_seconds_MET in tbdata.field('START'):
        # convert MET to MJD
        time_days_MET = time_seconds_MET/86400
        time_MJD = 51910 + time_days_MET 
        time.append(time_MJD)
    for flux in tbdata.field('FLUX_100_300000'):
        mag.append(flux)
    errorLAT = []
    for error in tbdata.field('ERROR_100_300000'):
        errorLAT.append(error)

    # call the SwiftData function to get the correct times
    # define filter
    swift_filter1 = 'B'
    plotSWIFTtime1 = SwiftData(swift_filter1,'time')
    
    lat = 0
    plotLATtime = []
    plotLATmag = []
    plotLATerror = []
    for times in time:
        if times >= plotSWIFTtime1[0] and times <= plotSWIFTtime1[len(plotSWIFTtime1)-1]:
            plotLATtime.append(times)
            plotLATmag.append(mag[lat])
            plotLATerror.append(errorLAT[lat])
        lat = lat + 1
    hdulist.close

    # set filters
    smarts_filter1 = 'B'
    smarts_filter2 = 'J'

    # call SwiftData and SmartsData functions to get magnitudes, times and errors
    plotSWIFTmag1 = SwiftData(swift_filter1, 'magnitude')
    plotSWIFTerror1 = SwiftData(swift_filter1, 'error')
    plotSMARTStime1 = SmartsData(smarts_filter1, 'time')
    plotSMARTSmag1 = SmartsData(smarts_filter1, 'magnitude')
    plotSMARTSerror1 = SmartsData(smarts_filter1, 'error')
    plotSMARTStime2 = SmartsData(smarts_filter2, 'time')
    plotSMARTSmag2 = SmartsData(smarts_filter2,'magnitude')
    plotSMARTSerror2 = SmartsData(smarts_filter2,'error')

    # plot the light curves

    fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True)
    ax0.errorbar(plotSWIFTtime1, plotSWIFTmag1, yerr=plotSWIFTerror1, color='red', fmt='o', label='Swift %s' % (swift_filter1))
    ax0.errorbar(plotSMARTStime1, plotSMARTSmag1, yerr=plotSMARTSerror1, color='blue',fmt='o', label='SMARTS %s' % (smarts_filter1))
    ax0.errorbar(plotSMARTStime2, plotSMARTSmag2, yerr=plotSMARTSerror2, color='purple', fmt='o', label='SMARTS %s' % (smarts_filter2))
    
    ax0.set_title(object)
    ax0.legend(bbox_to_anchor=(0.95, 1), loc=2)
    ax0.set_ylabel('Magnitude')
    ax0.set_ylim([16,11])
    
    ax1.errorbar(plotLATtime, plotLATmag, yerr=plotLATerror, color='gray', fmt='o')
    ax1.set_ylabel('.1 - 300 GeV  ' + r'$photons/cm^2/s$')
    plt.subplots_adjust(bottom = 0.1, right = 0.8, top = 0.9)
    plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0))
    xticklabels = ax1.get_xticklabels()
    plt.setp(xticklabels, visible=True)
    fmt=ScalarFormatter(useOffset=False)
    fmt.set_scientific(False)
    gca().xaxis.set_major_formatter(fmt)
    plt.show()
开发者ID:smhathaw,项目名称:uvotLightCurveRep,代码行数:82,代码来源:JB_3C454.py

示例15: finalize_draw

# 需要导入模块: from matplotlib.ticker import ScalarFormatter [as 别名]
# 或者: from matplotlib.ticker.ScalarFormatter import set_scientific [as 别名]
def finalize_draw(ax,events,channelDict,index1,index2,transform,fontSize,fontName,useSimple=False,axesOff=False,useScaled=False):

    ## variables
    xTransformed, yTransformed = False, False
    buff = 0.02
    formatter = ScalarFormatter(useMathText=True)
    formatter.set_scientific(True)
    formatter.set_powerlimits((-3,3))

    ## handle data edge buffers
    def scaled_axis(axis):
        if axis == 'x':
            bufferX = buff * (events[:,index1].max() - events[:,index1].min())
            ax.set_xlim([events[:,index1].min()-bufferX,events[:,index1].max()+bufferX])
        elif axis == 'y':
            bufferY = buff * (events[:,index2].max() - events[:,index2].min())
            ax.set_ylim([events[:,index2].min()-bufferY,events[:,index2].max()+bufferY])

    ## check to see if we force scale the axes
    if channelDict.has_key('time') and index1 == channelDict['time']:
        scaled_axis('x')
        xTransformed = True
        ax.xaxis.set_major_formatter(formatter)
    if channelDict.has_key('time') and index2 == channelDict['time']:
        scaled_axis('y')
        ax.yaxis.set_major_formatter(formatter)
        yTransformed = True

    ## handle scatter axes
    for key,val in channelDict.iteritems():
        if xTransformed == False and re.search(scatterPattern,key) and index1 == val:
            set_scatter_ticks(ax,'x',fontsize=fontSize,fontname=fontName)
            xTransformed = True
        if yTransformed == False and re.search(scatterPattern,key) and index2 == val:
            set_scatter_ticks(ax,'y',fontsize=fontSize,fontname=fontName)
            yTransformed = True

    ## handle other channels
    if xTransformed == False and transform == 'logicle':
        set_logicle_transformed_ticks(ax,axis='x',fontsize=fontSize,fontname=fontName)
    elif xTransformed == False and transform == 'log':
        set_log_transformed_ticks(ax,axis='x',fontsize=fontSize,fontname=fontName)

    if yTransformed == False and transform == 'logicle':
        set_logicle_transformed_ticks(ax,axis='y',fontsize=fontSize,fontname=fontName)
    elif yTransformed == False and transform == 'log':
        set_logicle_transformed_ticks(ax,axis='y',fontsize=fontSize,fontname=fontName)

    ## check to see if we force scale the axes
    if useScaled == True:
        scaled_axis('x')
        scaled_axis('y')
        
    ## for an axesless vesion
    if axesOff == True:
        ax.set_yticks([])
        ax.set_xticks([])

    ## for a simple version
    if useSimple == True:
        ax.set_yticks([])
        ax.set_xticks([])
        ax.set_title('')
        ax.set_ylabel('')
        ax.set_xlabel('')

    ## ensure the same fontsize, type
    for t in ax.get_yticklabels():
        t.set_fontsize(fontSize)
        t.set_fontname(fontName)

    for t in ax.get_xticklabels():
        t.set_fontsize(fontSize)
        t.set_fontname(fontName)
      
    ## make axes square
    ax.set_aspect(1./ax.get_data_ratio())
开发者ID:ajrichards,项目名称:cytostream,代码行数:79,代码来源:BasePlotters.py


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