本文整理汇总了Python中pylab.text函数的典型用法代码示例。如果您正苦于以下问题:Python text函数的具体用法?Python text怎么用?Python text使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了text函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: plot_cfl_results
def plot_cfl_results(results):
cfl = np.array([r.CFL_NUMBER for r in results.ANALYSES.values()])
its = np.array([r.ITERATIONS for r in results.ANALYSES.values()])
evl = np.arange(len(cfl))
i = np.argsort(cfl)
cfl = cfl[i]
its = its[i]
evl = evl[i]
its[its > 1000] = np.nan
plt.figure(1)
plt.clf()
plt.plot(cfl, its, "bo-", lw=2, ms=10)
plt.xlabel("CFL Number")
plt.ylabel("Iterations")
for e, x, y in zip(evl, cfl, its):
plt.text(x, y, "%i" % (e + 1))
plt.savefig("cfl_history.eps")
plt.close()
开发者ID:juantresde,项目名称:SU2,代码行数:25,代码来源:find_cfl_number.py
示例2: plotB3reg
def plotB3reg():
w=loadStanFit('revE2B3BHreg.fit')
printCI(w,'mmu')
printCI(w,'mr')
for b in range(2):
subplot(1,2,b+1)
plt.title('')
px=np.array(np.linspace(-0.5,0.5,101),ndmin=2)
a0=np.array(w['mmu'][:,b],ndmin=2).T
a1=np.array(w['mr'][:,b],ndmin=2).T
y=np.concatenate([sap(a0+a1*px,97.5,axis=0),sap(a0+a1*px[:,::-1],2.5,axis=0)])
x=np.squeeze(np.concatenate([px,px[:,::-1]],axis=1))
plt.plot(px[0,:],np.median(a0)+np.median(a1)*px[0,:],'red')
#plt.plot([-1,1],[0.5,0.5],'grey')
ax=plt.gca()
ax.set_aspect(1)
ax.add_patch(plt.Polygon(np.array([x,y]).T,alpha=0.2,fill=True,fc='red',ec='w'))
y=np.concatenate([sap(a0+a1*px,75,axis=0),sap(a0+a1*px[:,::-1],25,axis=0)])
ax.add_patch(plt.Polygon(np.array([x,y]).T,alpha=0.2,fill=True,fc='red',ec='w'))
man=np.array([-0.4,-0.2,0,0.2,0.4])
mus=[]
for m in range(len(man)):
mus.append(loadStanFit('revE2B3BH%d.fit'%m)['mmu'][:,b])
mus=np.array(mus).T
errorbar(mus,x=man)
ax.set_xticks(man)
plt.xlim([-0.5,0.5])
plt.ylim([-0.4,0.8])
#plt.xlabel('Manipulated Displacement')
if b==0:
plt.ylabel('Perceived Displacemet')
plt.gca().set_yticklabels([])
subplot_annotate()
plt.text(-1.1,-0.6,'Pivot Displacement',fontsize=8);
开发者ID:simkovic,项目名称:wolfpackRevisited,代码行数:34,代码来源:Evaluation.py
示例3: cmap_plot
def cmap_plot(cmdLine):
pylab.figure(figsize=[5,10])
a=outer(ones(10),arange(0,1,0.01))
subplots_adjust(top=0.99,bottom=0.00,left=0.01,right=0.8)
maps=[m for m in cm.datad if not m.endswith("_r")]
maps.sort()
l=len(maps)+1
for i, m in enumerate(maps):
print m
subplot(l,1,i+1)
pylab.setp(pylab.gca(),xticklabels=[],xticks=[],yticklabels=[],yticks=[])
imshow(a,aspect='auto',cmap=get_cmap(m),origin="lower")
pylab.text(100.85,0.5,m,fontsize=10)
# render plot
if cmdLine:
pylab.show(block=True)
else:
pylab.ion()
pylab.plot([])
pylab.ioff()
status = 1
return status
开发者ID:KeplerGO,项目名称:PyKE,代码行数:26,代码来源:kepprf.py
示例4: plot_prob_effector
def plot_prob_effector(sens, fpr, xmax=1, baserate=0.1):
"""Plots a line graph of P(effector|positive test) against
the baserate of effectors in the input set to the classifier.
The baserate argument draws an annotation arrow
indicating P(pos|+ve) at that baserate
"""
assert 0.1 <= xmax <= 1, "Max x axis value must be in range [0,1]"
assert 0.01 <= baserate <= 1, "Baserate annotation must be in range [0,1]"
baserates = pylab.arange(0, 1.05, xmax * 0.005)
probs = [p_correct_given_pos(sens, fpr, b) for b in baserates]
pylab.plot(baserates, probs, 'r')
pylab.title("P(eff|pos) vs baserate; sens: %.2f, fpr: %.2f" % (sens, fpr))
pylab.ylabel("P(effector|positive)")
pylab.xlabel("effector baserate")
pylab.xlim(0, xmax)
pylab.ylim(0, 1)
# Add annotation arrow
xpos, ypos = (baserate, p_correct_given_pos(sens, fpr, baserate))
if baserate < xmax:
if xpos > 0.7 * xmax:
xtextpos = 0.05 * xmax
else:
xtextpos = xpos + (xmax-xpos)/5.
if ypos > 0.5:
ytextpos = ypos - 0.05
else:
ytextpos = ypos + 0.05
pylab.annotate('baserate: %.2f, P(pos|+ve): %.3f' % (xpos, ypos),
xy=(xpos, ypos),
xytext=(xtextpos, ytextpos),
arrowprops=dict(facecolor='black', shrink=0.05))
else:
pylab.text(0.05 * xmax, 0.95, 'baserate: %.2f, P(pos|+ve): %.3f' % \
(xpos, ypos))
开发者ID:widdowquinn,项目名称:Teaching-EMBL-Plant-Path-Genomics,代码行数:35,代码来源:ex03.py
示例5: _draw_V
def _draw_V(self):
""" draw the V-cycle on our optional visualization """
xdown = numpy.linspace(0.0, 0.5, self.nlevels)
xup = numpy.linspace(0.5, 1.0, self.nlevels)
ydown = numpy.linspace(1.0, 0.0, self.nlevels)
yup = numpy.linspace(0.0, 1.0, self.nlevels)
pylab.plot(xdown, ydown, lw=2, color="k")
pylab.plot(xup, yup, lw=2, color="k")
pylab.scatter(xdown, ydown, marker="o", color="k", s=40)
pylab.scatter(xup, yup, marker="o", color="k", s=40)
if self.up_or_down == "down":
pylab.scatter(
xdown[self.nlevels - self.current_level - 1],
ydown[self.nlevels - self.current_level - 1],
marker="o",
color="r",
zorder=100,
s=38,
)
else:
pylab.scatter(xup[self.current_level], yup[self.current_level], marker="o", color="r", zorder=100, s=38)
pylab.text(0.7, 0.1, "V-cycle %d" % (self.current_cycle))
pylab.axis("off")
开发者ID:jzuhone,项目名称:pyro2,代码行数:29,代码来源:multigrid.py
示例6: plot_genome
def plot_genome(out_file, data_file, samples, dpi=300, screen=False):
if screen: PL.rcParams.update(PLOT_PARAMS_SCREEN)
LOG.info("plot_genome - out_file=%s, data_file=%s, samples=%s, dpi=%d"%(out_file, data_file, str(samples), dpi))
colors = 'bgryckbgryck'
data = read_posterior(data_file)
if samples is None or len(samples) == 0: samples = data.keys()
if len(samples) == 0: return
PL.figure(None, [14, 4])
right_end = 0 # rightmost plotted base pair
for chrm in sort_chrms(data.values()[0]): # for chromosomes in ascending order
max_site = max(data[samples[0]][chrm]['L']) # length of chromosome
for s, sample in enumerate(samples): # plot all samples
I = SP.where(SP.array(data[sample][chrm]['SD']) < 0.3)[0] # at sites that have confident posteriors
PL.plot(SP.array(data[sample][chrm]['L'])[I] + right_end, SP.array(data[sample][chrm]['AF'])[I], alpha=0.4, color=colors[s], lw=2) # offset by the end of last chromosome
if right_end > 0: PL.plot([right_end, right_end], [0,1], 'k--', lw=0.4, alpha=0.2) # plot separators between chromosomes
new_right = right_end + max(data[sample][chrm]['L'])
PL.text(right_end + 0.5*(new_right - right_end), 0.9, str(chrm), horizontalalignment='center')
right_end = new_right # update rightmost end
PL.plot([0,right_end], [0.5,0.5], 'k--', alpha=0.3)
PL.xlim(0,right_end)
xrange = SP.arange(0,right_end, 1000000)
PL.xticks(xrange, ["%d"%(int(x/1000000)) for x in xrange])
PL.xlabel("Genome (Mb)"), PL.ylabel("Reference allele frequency")
PL.savefig(out_file, dpi=dpi)
开发者ID:PMBio,项目名称:sqtl,代码行数:26,代码来源:genome.py
示例7: plot_frontier
def plot_frontier(self,frontier_only=False,plot_samples=True) :
""" Plot the frontier"""
frontier = self.frontier
frontier_energy = self.frontier_energy
feat1,feat2 = self.feats
pl.figure()
if not frontier_only :
ll_list1,ll_list2 = zip(*self.all_seq_energy)
pl.plot(ll_list1,ll_list2,'b*')
if plot_samples :
ll_list1,ll_list2 = zip(*self.sample_seq_energy)
pl.plot(ll_list1,ll_list2,'g*')
pl.plot(*zip(*sorted(frontier_energy)),color='magenta',\
marker='*', linestyle='dashed')
ctr = dict(zip(set(frontier_energy),[0]*
len(set(frontier_energy))))
for i,e in enumerate(frontier_energy) :
ctr[e] += 1
pl.text(e[0],e[1]+0.1*ctr[e],str(i),fontsize=10)
pl.text(e[0]+0.4,e[1]+0.1*ctr[e],frontier[i],fontsize=9)
pl.xlabel('Energy:'+feat1)
pl.ylabel('Energy:'+feat2)
pl.title('Energy Plot')
xmin,xmax = pl.xlim()
ymin,ymax = pl.ylim()
pl.xlim(xmin,xmax)
pl.ylim(ymin,ymax)
pic_dir = '../docs/tex/pics/'
pl.savefig(pic_dir+self.name+'.pdf')
pl.savefig(pic_dir+self.name+'.png')
开发者ID:smoitra87,项目名称:pareto-hmm,代码行数:32,代码来源:exp1.py
示例8: print_matplotlib
def print_matplotlib(s):
pylab.figure()
pylab.text(0,0,s)
pylab.axis('off')
pylab.figure()
#pylab.show()
return
开发者ID:tsarvey,项目名称:spinwaves,代码行数:7,代码来源:spinwave_calc_file_changed.py
示例9: _show_rates
def _show_rates(rate, wo, wt, attenuator, tau_NP, tau_P):
import pylab
#pylab.figure()
pylab.errorbar(rate, wt[0], yerr=wt[1], fmt='g.', label='attenuated')
pylab.errorbar(rate, wo[0], yerr=wo[1], fmt='b.', label='unattenuated')
pylab.xscale('log')
pylab.yscale('log')
pylab.xlabel('incident rate (counts/second)')
pylab.ylabel('observed rate (counts/second)')
pylab.legend(loc='best')
pylab.grid(True)
pylab.plot(rate, rate/attenuator, 'g-', label='target')
pylab.plot(rate, rate, 'b-', label='target')
Ipeak, Rpeak = peak_rate(tau_NP=tau_NP, tau_P=tau_P)
if rate[0] <= Ipeak <= rate[-1]:
pylab.axvline(x=Ipeak, ls='--', c='b')
pylab.text(x=Ipeak, y=0.05, s=' %g'%Ipeak,
ha='left', va='bottom',
transform=pylab.gca().get_xaxis_transform())
if False:
pylab.axhline(y=Rpeak, ls='--', c='b')
pylab.text(y=Rpeak, x=0.05, s=' %g\n'%Rpeak,
ha='left', va='bottom',
transform=pylab.gca().get_yaxis_transform())
开发者ID:reflectometry,项目名称:reduction,代码行数:27,代码来源:deadtime_fit.py
示例10: scatter_stats
def scatter_stats(db, s1, s2, f1=None, f2=None, **kwargs):
if f1 == None:
f1 = lambda x: x # constant function
if f2 == None:
f2 = f1
x = []
xerr = []
y = []
yerr = []
for k in db:
x_k = [f1(x_ki) for x_ki in db[k].__getattribute__(s1).gettrace()]
y_k = [f2(y_ki) for y_ki in db[k].__getattribute__(s2).gettrace()]
x.append(pl.mean(x_k))
xerr.append(pl.std(x_k))
y.append(pl.mean(y_k))
yerr.append(pl.std(y_k))
pl.text(x[-1], y[-1], " %s" % k, fontsize=8, alpha=0.4, zorder=-1)
default_args = {"fmt": "o", "ms": 10}
default_args.update(kwargs)
pl.errorbar(x, y, xerr=xerr, yerr=yerr, **default_args)
pl.xlabel(s1)
pl.ylabel(s2)
开发者ID:aflaxman,项目名称:bednet_stock_and_flow,代码行数:30,代码来源:explore.py
示例11: compare_models
def compare_models(db, stoch="itn coverage", stat_func=None, plot_type="", **kwargs):
if stat_func == None:
stat_func = lambda x: x
X = {}
for k in sorted(db.keys()):
c = k.split("_")[2]
X[c] = []
for k in sorted(db.keys()):
c = k.split("_")[2]
X[c].append([stat_func(x_ki) for x_ki in db[k].__getattribute__(stoch).gettrace()])
x = pl.array([pl.mean(xc[0]) for xc in X.values()])
xerr = pl.array([pl.std(xc[0]) for xc in X.values()])
y = pl.array([pl.mean(xc[1]) for xc in X.values()])
yerr = pl.array([pl.std(xc[1]) for xc in X.values()])
if plot_type == "scatter":
default_args = {"fmt": "o", "ms": 10}
default_args.update(kwargs)
for c in X.keys():
pl.text(pl.mean(X[c][0]), pl.mean(X[c][1]), " %s" % c, fontsize=8, alpha=0.4, zorder=-1)
pl.errorbar(x, y, xerr=xerr, yerr=yerr, **default_args)
pl.xlabel("First Model")
pl.ylabel("Second Model")
pl.plot([0, 1], [0, 1], alpha=0.5, linestyle="--", color="k", linewidth=2)
elif plot_type == "rel_diff":
d1 = sorted(100 * (x - y) / x)
d2 = sorted(100 * (xerr - yerr) / xerr)
pl.subplot(2, 1, 1)
pl.title("Percent Model 2 deviates from Model 1")
pl.plot(d1, "o")
pl.xlabel("Countries sorted by deviation in mean")
pl.ylabel("deviation in mean (%)")
pl.subplot(2, 1, 2)
pl.plot(d2, "o")
pl.xlabel("Countries sorted by deviation in std err")
pl.ylabel("deviation in std err (%)")
elif plot_type == "abs_diff":
d1 = sorted(x - y)
d2 = sorted(xerr - yerr)
pl.subplot(2, 1, 1)
pl.title("Percent Model 2 deviates from Model 1")
pl.plot(d1, "o")
pl.xlabel("Countries sorted by deviation in mean")
pl.ylabel("deviation in mean")
pl.subplot(2, 1, 2)
pl.plot(d2, "o")
pl.xlabel("Countries sorted by deviation in std err")
pl.ylabel("deviation in std err")
else:
assert 0, "plot_type must be abs_diff, rel_diff, or scatter"
return pl.array([x, y, xerr, yerr])
开发者ID:aflaxman,项目名称:bednet_stock_and_flow,代码行数:60,代码来源:explore.py
示例12: suplabel
def suplabel(axis, label, label_prop=None, labelpad=3, ha='center', va='center'):
"""
Add super ylabel or xlabel to the figure
Similar to matplotlib.suptitle
axis - string: "x" or "y"
label - string
label_prop - keyword dictionary for Text
labelpad - padding from the axis (default: 5)
ha - horizontal alignment (default: "center")
va - vertical alignment (default: "center")
"""
fig = pylab.gcf()
xmin = []
ymin = []
for ax in fig.axes:
xmin.append(ax.get_position().xmin)
ymin.append(ax.get_position().ymin)
xmin, ymin = min(xmin), min(ymin)
dpi = fig.dpi
if axis.lower() == "y":
rotation = 90.
x = xmin-float(labelpad)/dpi
y = 0.5
elif axis.lower() == 'x':
rotation = 0.
x = 0.5
y = ymin - float(labelpad)/dpi
else:
raise Exception("Unexpected axis: x or y")
if label_prop is None:
label_prop = dict()
pylab.text(x, y, label, rotation=rotation,
transform=fig.transFigure,
ha=ha, va=va,
**label_prop)
开发者ID:alainmuls,项目名称:GNSSpy,代码行数:35,代码来源:plotCN0.py
示例13: PASTISConfMap
def PASTISConfMap(confmatrix):
norms = np.sum(confmatrix,axis=1)
for i in range(len(confmatrix[:,0])):
confmatrix[i,:] /= norms[i]
p.figure(12)
p.clf()
p.imshow(confmatrix,interpolation='nearest',origin='lower',cmap='YlOrRd')
#box labels
for x in range(len(confmatrix[:,0])):
for y in range(len(confmatrix[:,0])):
if confmatrix[y,x] > 0.05:
if confmatrix[y,x]>0.7:
p.text(x,y,str(np.round(confmatrix[y,x],decimals=3)),va='center',ha='center',color='w')
else:
p.text(x,y,str(np.round(confmatrix[y,x],decimals=3)),va='center',ha='center')
#plot grid lines (using p.grid leads to unwanted offset)
for x in [0.5,1.5,2.5,3.5,4.5]:
p.plot([x,x],[-0.5,6.5],'k--')
for y in [0.5,1.5,2.5,3.5,4.5]:
p.plot([-0.5,6.5],[y,y],'k--')
p.xlim(-0.5,5.5)
p.ylim(-0.5,5.5)
p.xlabel('Predicted Class')
p.ylabel('True Class')
#class labels
p.xticks([0,1,2,3,4,5],['Planet', 'EB', 'ET', 'PSB','BEB', 'BTP'],rotation='vertical')
p.yticks([0,1,2,3,4,5],['Planet', 'EB', 'ET', 'PSB','BEB', 'BTP'])
开发者ID:Soletmons,项目名称:TransitSOMTest,代码行数:32,代码来源:plottools.py
示例14: plotVowelProportionHistogram
def plotVowelProportionHistogram(wordList, numBins=15):
"""
Plots a histogram of the proportion of vowels in each word in wordList
using the specified number of bins in numBins
"""
vowels = 'aeiou'
vowelProportions = []
for word in wordList:
vowelsCount = 0.0
for letter in word:
if letter in vowels:
vowelsCount += 1
vowelProportions.append(vowelsCount / len(word))
meanProportions = sum(vowelProportions) / len(vowelProportions)
print "Mean proportions: ", meanProportions
pylab.figure(1)
pylab.hist(vowelProportions, bins=15)
pylab.title("Histogram of Proportions of Vowels in Each Word")
pylab.ylabel("Count of Words in Each Bucket")
pylab.xlabel("Proportions of Vowels in Each Word")
ymin, ymax = pylab.ylim()
ymid = (ymax - ymin) / 2
pylab.text(0.03, ymid, "Mean = {0}".format(
str(round(meanProportions, 4))))
pylab.vlines(0.5, 0, ymax)
pylab.text(0.51, ymax - 0.01 * ymax, "0.5", verticalalignment = 'top')
pylab.show()
开发者ID:eshilts,项目名称:intro-to-cs-6.00x,代码行数:34,代码来源:histogramfun.py
示例15: bondlengths
def bondlengths(Ea, dE):
"""Calculate bond lengths and write to bondlengths.csv file"""
B = []
E0 = []
csv = open('bondlengths.csv', 'w')
for formula, energies in dE:
bref = diatomic[formula][1]
b = np.linspace(0.96 * bref, 1.04 * bref, 5)
e = np.polyfit(b, energies, 3)
if not formula in Ea:
continue
ea, eavasp = Ea[formula]
dedb = np.polyder(e, 1)
b0 = np.roots(dedb)[1]
assert abs(b0 - bref) < 0.1
b = np.linspace(0.96 * bref, 1.04 * bref, 20)
e = np.polyval(e, b) - ea
if formula == 'O2':
plt.plot(b, e, '-', color='0.7', label='GPAW')
else:
plt.plot(b, e, '-', color='0.7', label='_nolegend_')
name = latex(data[formula]['name'])
plt.text(b[0], e[0] + 0.2, name)
B.append(bref)
E0.append(-eavasp)
csv.write('`%s`, %.3f, %.3f, %+.3f\n' %
(name[1:-1], b0, bref, b0 - bref))
plt.plot(B, E0, 'g.', label='reference')
plt.legend(loc='lower right')
plt.xlabel('Bond length $\mathrm{\AA}$')
plt.ylabel('Energy [eV]')
plt.savefig('bondlengths.png')
开发者ID:ryancoleman,项目名称:lotsofcoresbook2code,代码行数:33,代码来源:make_csv_files.py
示例16: scatter_from_csv
def scatter_from_csv(self, filename, sand = 'sand', silt = 'silt', clay = 'clay', diameter = '', hue = '', tags = '', **kwargs):
"""Loads data from filename (expects csv format). Needs one header row with at least the columns {sand, silt, clay}. Can also plot two more variables for each point; specify the header value for columns to be plotted as diameter, hue. Can also add a text tag offset from each point; specify the header value for those tags.
Note! text values (header entries, tag values ) need to be quoted to be recognized as text. """
fh = file(filename, 'rU')
soilrec = csv2rec(fh)
count = 0
if (sand in soilrec.dtype.names):
count = count + 1
if (silt in soilrec.dtype.names):
count = count + 1
if (clay in soilrec.dtype.names):
count = count + 1
if (count < 3):
print "ERROR: need columns for sand, silt and clay identified in ', filename"
locargs = {'s': None, 'c': None}
for (col, key) in ((diameter, 's'), (hue, 'c')):
col = col.lower()
if (col != '') and (col in soilrec.dtype.names):
locargs[key] = soilrec.field(col)
else:
print 'ERROR: did not find ', col, 'in ', filename
for k in kwargs:
locargs[k] = kwargs[k]
values = zip(*[soilrec.field(sand), soilrec.field(clay), soilrec.field(silt)])
print values
(xs, ys) = self._toCart(values)
p.scatter(xs, ys, label='_', **locargs)
if (tags != ''):
tags = tags.lower()
for (x, y, tag) in zip(*[xs, ys, soilrec.field(tags)]):
print x,
print y,
print tag
p.text(x + 1, y + 1, tag, fontsize=12)
fh.close()
开发者ID:btweinstein,项目名称:TernaryPlotPy,代码行数:35,代码来源:trianglegraph.py
示例17: plotDirections
def plotDirections(aabb=(),mask=0,bins=20,numHist=True,noShow=False,sphSph=False):
"""Plot 3 histograms for distribution of interaction directions, in yz,xz and xy planes and
(optional but default) histogram of number of interactions per body. If sphSph only sphere-sphere interactions are considered for the 3 directions histograms.
:returns: If *noShow* is ``False``, displays the figure and returns nothing. If *noShow*, the figure object is returned without being displayed (works the same way as :yref:`yade.plot.plot`).
"""
import pylab,math
from yade import utils
for axis in [0,1,2]:
d=utils.interactionAnglesHistogram(axis,mask=mask,bins=bins,aabb=aabb,sphSph=sphSph)
fc=[0,0,0]; fc[axis]=1.
subp=pylab.subplot(220+axis+1,polar=True);
# 1.1 makes small gaps between values (but the column is a bit decentered)
pylab.bar(d[0],d[1],width=math.pi/(1.1*bins),fc=fc,alpha=.7,label=['yz','xz','xy'][axis])
#pylab.title(['yz','xz','xy'][axis]+' plane')
pylab.text(.5,.25,['yz','xz','xy'][axis],horizontalalignment='center',verticalalignment='center',transform=subp.transAxes,fontsize='xx-large')
if numHist:
pylab.subplot(224,polar=False)
nums,counts=utils.bodyNumInteractionsHistogram(aabb if len(aabb)>0 else utils.aabbExtrema())
avg=sum([nums[i]*counts[i] for i in range(len(nums))])/(1.*sum(counts))
pylab.bar(nums,counts,fc=[1,1,0],alpha=.7,align='center')
pylab.xlabel('Interactions per body (avg. %g)'%avg)
pylab.axvline(x=avg,linewidth=3,color='r')
pylab.ylabel('Body count')
if noShow: return pylab.gcf()
else:
pylab.ion()
pylab.show()
开发者ID:Haider-BA,项目名称:trunk,代码行数:28,代码来源:utils.py
示例18: _plot
def _plot(self, attribute_name, file_path=None):
clf() # Clear existing plot
a = self._values[0] * 100
b = self._values[1] * 100
ax = subplot(111)
plot(a, a, "k--", a, b, "r")
ax.set_ylim([0, 100])
ax.grid(color="0.5", linestyle=":", linewidth=0.5)
xlabel("population")
ylabel(attribute_name)
title("Lorenz curve")
font = {"fontname": "Courier", "color": "r", "fontweight": "bold", "fontsize": 11}
box = {"pad": 6, "facecolor": "w", "linewidth": 1, "fill": True}
text(5, 90, "Gini coefficient: %(gini)f" % {"gini": self._ginicoeff}, font, color="k", bbox=box)
majorLocator = MultipleLocator(20)
majorFormatter = FormatStrFormatter("%d %%")
minorLocator = MultipleLocator(5)
ax.xaxis.set_major_locator(majorLocator)
ax.xaxis.set_major_formatter(majorFormatter)
ax.xaxis.set_minor_locator(minorLocator)
ax.yaxis.set_major_locator(majorLocator)
ax.yaxis.set_major_formatter(majorFormatter)
ax.yaxis.set_minor_locator(minorLocator)
if file_path:
savefig(file_path)
close()
else:
show()
开发者ID:psrc,项目名称:urbansim,代码行数:29,代码来源:matplotlib_lorenzcurve.py
示例19: plot_different_versions
def plot_different_versions(repo_name, pre_fetch_size, distance_to_fetch,
fig_name=None):
"""Sample plot of several different repos."""
x = range(100)
legend = []
fig, ax = plt.subplots()
for version in version_color:
csv_reader = _file_to_csv(
version=version, repo_name=repo_name,
pre_fetch_size=pre_fetch_size, distance_to_fetch=distance_to_fetch)
y = get_column(csv_reader, 'hit_rate')
if y is not None:
plt.plot(x, y, color=version_color[version])
line = mlines.Line2D(
[], [],
label=version, color=version_color[version], linewidth=2)
legend.append(line)
plt.title('Different version outputs of %s.git' % (repo_name,),
y=1.02)
plt.legend(handles=legend, loc=4)
plt.ylabel('hit rate')
plt.xlabel('cache size (%)')
legend_text = 'pfs = %s, dtf = %s\ncommit_num = %s' % (
pre_fetch_size, distance_to_fetch, REPO_DATA[repo_name]['commit_num'])
text(0.55, 0.07, legend_text, ha='center', va='center',
transform=ax.transAxes, multialignment='left',
bbox=dict(alpha=1.0, boxstyle='square', facecolor='white'))
plt.grid(True)
plt.autoscale(False)
plt.show()
开发者ID:sztankatt,项目名称:fixcache,代码行数:35,代码来源:graphs.py
示例20: generateNetwork
def generateNetwork(aINDEX, dDIFF, AM, name):
R = 100
X = []
Y = []
Z = []
for i in range(len(aINDEX)):
#r = 100*R + sum(AM[i])*R
r = 1000*R + 10000*abs(dDIFF[aINDEX[i]])*R
t = 2*math.pi*random.random()
X.append(r*math.cos(t))
Y.append(r*math.sin(t))
Z.append(sum(AM[i]))
fig = P.figure()
P.axis('off')
P.scatter(X, Y, Z, edgecolor = '', c = 'lightblue', alpha = 0.5)
for i in range(len(aINDEX)):
for j in range(i):
if sum(AM[i]) > 200 and sum(AM[j]) > 200:
P.plot([X[i], X[j]], [Y[i], Y[j]],'k',lw = 0.01)
for i in range(len(aINDEX)):
if sum(AM[i])>200:
P.text(X[i], Y[i], aINDEX[i], fontsize = 8)
#P.show()
fig.savefig('figures/' + name + '.png')
return
开发者ID:HACP,项目名称:BACKGROUND_CONTENT,代码行数:33,代码来源:PNlib.py
注:本文中的pylab.text函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论