本文整理汇总了Python中matplotlib.pyplot.text函数的典型用法代码示例。如果您正苦于以下问题:Python text函数的具体用法?Python text怎么用?Python text使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了text函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: view
def view(key,reciprocals=None,show=True,suspend=False,save=True,name='KMap'):
'''
View the KMap.
Parameters
----------
key : 'L','S','H'
The key of the database of KMap.
reciprocals : iterable of 1d ndarray, optional
The translation vectors of the reciprocal lattice.
show : logical, optional
True for showing the view. Otherwise not.
suspend : logical, optional
True for suspending the view. Otherwise not.
save : logical, optional
True for saving the view. Otherwise not.
name : str, optional
The title and filename of the view. Otherwise not.
'''
assert key in KMap.database
if key=='L': reciprocals=np.asarray(reciprocals) or np.array([1.0])*2*np.pi
elif key=='S': reciprocals=np.asarray(reciprocals) or np.array([[1.0,0.0],[0.0,1.0]])*2*np.pi
elif key=='H': reciprocals=np.asarray(reciprocals) or np.array([[1.0,-1.0/np.sqrt(3.0)],[0,-2.0/np.sqrt(3.0)]])*2*np.pi
plt.title(name)
plt.axis('equal')
for tag,position in KMap.database[key].items():
if '1' not in tag:
coords=reciprocals.T.dot(position)
assert len(coords)==2
plt.scatter(coords[0],coords[1])
plt.text(coords[0],coords[1],'%s(%s1)'%(tag,tag) if len(tag)==1 else tag,ha='center',va='bottom',color='green',fontsize=14)
if show and suspend: plt.show()
if show and not suspend: plt.pause(1)
if save: plt.savefig('%s.png'%name)
plt.close()
示例2: export
def export(self, query, n_topics, n_words, title="PCA Export", fname="PCAExport"):
vec = DictVectorizer()
rows = topics_to_vectorspace(self.model, n_topics, n_words)
X = vec.fit_transform(rows)
pca = skPCA(n_components=2)
X_pca = pca.fit(X.toarray()).transform(X.toarray())
match = []
for i in range(n_topics):
topic = [t[1] for t in self.model.show_topic(i, len(self.dictionary.keys()))]
m = None
for word in topic:
if word in query:
match.append(word)
break
pyplot.figure()
for i in range(X_pca.shape[0]):
pyplot.scatter(X_pca[i, 0], X_pca[i, 1], alpha=.5)
pyplot.text(X_pca[i, 0], X_pca[i, 1], s=' '.join([str(i), match[i]]))
pyplot.title(title)
pyplot.savefig(fname)
pyplot.close()
示例3: drawVectors
def drawVectors(transformed_features, components_, columns, plt, scaled):
if not scaled:
return plt.axes() # No cheating ;-)
num_columns = len(columns)
# This funtion will project your *original* feature (columns)
# onto your principal component feature-space, so that you can
# visualize how "important" each one was in the
# multi-dimensional scaling
# Scale the principal components by the max value in
# the transformed set belonging to that component
xvector = components_[0] * max(transformed_features[:,0])
yvector = components_[1] * max(transformed_features[:,1])
## visualize projections
# Sort each column by it's length. These are your *original*
# columns, not the principal components.
important_features = { columns[i] : math.sqrt(xvector[i]**2 + yvector[i]**2) for i in range(num_columns) }
important_features = sorted(zip(important_features.values(), important_features.keys()), reverse=True)
print "Features by importance:\n", important_features
ax = plt.axes()
for i in range(num_columns):
# Use an arrow to project each original feature as a
# labeled vector on your principal component axes
plt.arrow(0, 0, xvector[i], yvector[i], color='b', width=0.0005, head_width=0.02, alpha=0.75)
plt.text(xvector[i]*1.2, yvector[i]*1.2, list(columns)[i], color='b', alpha=0.75)
return ax
示例4: createResponsePlot
def createResponsePlot(dataframe,plotdir):
mag = dataframe['MAGPDE'].as_matrix()
response = (dataframe['TFIRSTPUB'].as_matrix())/60.0
response[response > 60] = 60 #anything over 60 minutes capped at 6 minutes
imag5 = (mag >= 5.0).nonzero()[0]
imag55 = (mag >= 5.5).nonzero()[0]
fig = plt.figure(figsize=(8,6))
n,bins,patches = plt.hist(response[imag5],color='g',bins=60,range=(0,60))
plt.hold(True)
plt.hist(response[imag55],color='b',bins=60,range=(0,60))
plt.xlabel('Response Time (min)')
plt.ylabel('Number of earthquakes')
plt.xticks(np.arange(0,65,5))
ymax = text.ceilToNearest(max(n),10)
yinc = ymax/10
plt.yticks(np.arange(0,ymax+yinc,yinc))
plt.grid(True,which='both')
plt.hold(True)
x = [20,20]
y = [0,ymax]
plt.plot(x,y,'r',linewidth=2,zorder=10)
s1 = 'Magnitude 5.0, Events = %i' % (len(imag5))
s2 = 'Magnitude 5.5, Events = %i' % (len(imag55))
plt.text(35,.85*ymax,s1,color='g')
plt.text(35,.75*ymax,s2,color='b')
plt.savefig(os.path.join(plotdir,'response.pdf'))
plt.savefig(os.path.join(plotdir,'response.png'))
plt.close()
print 'Saving response.pdf'
示例5: plotFrame
def plotFrame(lines, chop_times,dist,samDist,DetDist,fracEi,Eis):
modSamDist=dist[-1]+samDist
totDist=modSamDist+DetDist
for i in range(len(dist)):
plt.plot([-20000,120000],[dist[i],dist[i]],c='k',linewidth=1.)
for j in range(len(chop_times[i][:])):
plt.plot(chop_times[i][j],[dist[i],dist[i]],c='white',linewidth=1.)
plt.plot([-20000,120000],[totDist,totDist],c='k',linewidth=2.)
for i in range(len(lines)):
x0=-lines[i][0][1]/lines[i][0][0]
x1=(modSamDist-lines[i][0][1])/lines[i][0][0]
plt.plot([x0,x1],[0,modSamDist],c='b')
x2=(totDist-lines[i][0][1])/lines[i][0][0]
plt.plot([x1,x2],[modSamDist,totDist],c='b')
newline=[lines[i][0][0]*np.sqrt(1+fracEi),modSamDist-lines[i][0][0]*np.sqrt(1+fracEi)*x1]
x3=(totDist-newline[1])/(newline[0])
plt.plot([x1,x3],[modSamDist,totDist],c='r')
newline=[lines[i][0][0]*np.sqrt(1-fracEi),modSamDist-lines[i][0][0]*np.sqrt(1-fracEi)*x1]
x4=(totDist-newline[1])/(newline[0])
plt.plot([x1,x4],[modSamDist,totDist],c='r')
plt.text(x2,totDist+0.2,"{:3.1f}".format(Eis[i]))
plt.xlabel('TOF ($\mu$sec)')
plt.ylabel('Distance (m)')
plt.xlim(0,100000)
plt.show()
示例6: plot_confusion_matrix
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=None,
zmin=1):
"""This function prints and plots the confusion matrix for the intent classification.
Normalization can be applied by setting `normalize=True`."""
import numpy as np
zmax = cm.max()
plt.imshow(cm, interpolation='nearest', cmap=cmap if cmap else plt.cm.Blues, aspect='auto',
norm=LogNorm(vmin=zmin, vmax=zmax))
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=90)
plt.yticks(tick_marks, classes)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
logger.info("Normalized confusion matrix: \n{}".format(cm))
else:
logger.info("Confusion matrix, without normalization: \n{}".format(cm))
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, cm[i, j],
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.ylabel('True label')
plt.xlabel('Predicted label')
示例7: autolabel
def autolabel(rects,labels):
# attach some text labels
for i,(rect,label) in enumerate(zip(rects,labels)):
height = rect.get_height()
plt.text(rect.get_x() + rect.get_width()/2., 1.05*height,
label,
ha='left', va='bottom',fontsize=8,rotation=45)
示例8: plot_confusion_matrix
def plot_confusion_matrix(y_true, y_pred, thresh, classes):
"""
This function plots the (normalized) confusion matrix.
"""
# obtain class predictions from probabilities
y_pred = (y_pred>=thresh)*1
# obtain (unnormalized) confusion matrix
cm = confusion_matrix(y_true, y_pred)
# normalize confusion matrix
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
plt.figure()
plt.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues)
plt.title('Confusion matrix')
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], '.2f'),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.show()
示例9: make_equil_plts_2
def make_equil_plts_2(phi, tad, xeq, gas):
"""
make_equil_plts_2
make_equil_plts_2 makes plots from Python function equil; it's the same as make_equil_plts, but with 2 separate figures
"""
plt.figure(1)
phitadplt = plt.plot(phi,tad)
plt.xlabel('Equivalence Ratio')
plt.ylabel('Temperature (K)')
plt.title('Adiabatic Flame Temperature')
plt.figure(2)
plt.ylim(10.**(-14),1)
plt.xlim(phi[0],phi[49])
phixeqsemilogyplt = plt.semilogy(phi,xeq) # matplotlib semilogy takes in the correct dimensions! What I mean is that say phi is a list of length 50. Suppose xeq is a numpy array of shape (50,53). This will result in 53 different (line) graphs on the same plot, the correct number of line graphs for (50) (x,y) data points/dots!
plt.xlabel('Equivalence Ratio')
plt.ylabel('Mole Fraction')
plt.title('Equilibrium Composition')
j = 10
for k in range(gas.n_species):
plt.text(phi[j],1.5*xeq[j,k],gas.species_name(k))
j = j + 2
if j > 46:
j = 10
plt.show()
return phitadplt, phixeqsemilogyplt
示例10: main
def main(args):
histogram = args.histogram
min_limit = args.min_limit
max_limit = args.max_limit
kmer = args.kmer
output_name = args.output_name
Kmer_histogram = pd.io.parsers.read_csv(histogram, sep="\t", header=None)
Kmer_coverage = Kmer_histogram[Kmer_histogram.columns[0]].tolist()
Kmer_count = Kmer_histogram[Kmer_histogram.columns[1]].tolist()
Kmer_freq = [Kmer_coverage[i] * Kmer_count[i] for i in range(len(Kmer_coverage))]
# coverage peak, disregarding initial peak
kmer_freq_peak = Kmer_freq.index(max(Kmer_freq[min_limit:max_limit]))
kmer_freq_peak_value = max(Kmer_freq[min_limit:max_limit])
xmax = max_limit
ymax = kmer_freq_peak_value + (kmer_freq_peak_value * 0.30)
plt.plot(Kmer_coverage, Kmer_freq)
plt.title("K-mer length = {}".format(kmer))
plt.xlim((0, xmax))
plt.ylim((0, ymax))
plt.vlines(kmer_freq_peak, 0, kmer_freq_peak_value, colors="r", linestyles="--")
plt.text(kmer_freq_peak, kmer_freq_peak_value + 2000, str(kmer_freq_peak))
plotname = "{}".format(output_name)
plt.savefig(plotname)
plt.clf()
return 0
示例11: pylot_show
def pylot_show():
sql = 'select * from douban;'
cur.execute(sql)
rows = cur.fetchall() # 把表中所有字段读取出来
count = [] # 每个分类的数量
category = [] # 分类
for row in rows:
count.append(int(row[2]))
category.append(row[1])
y_pos = np.arange(len(category)) # 定义y轴坐标数
#color = cm.jet(np.array(2)/max(count))
plt.barh(y_pos, count, color='y', align='center', alpha=0.4) # alpha图表的填充不透明度(0~1)之间
plt.yticks(y_pos, category) # 在y轴上做分类名的标记
plt.grid(axis = 'x')
for count, y_pos in zip(count, y_pos):
# 分类个数在图中显示的位置,就是那些数字在柱状图尾部显示的数字
plt.text(count+3, y_pos, count, horizontalalignment='center', verticalalignment='center', weight='bold')
plt.ylim(+28.0, -2.0) # 可视化范围,相当于规定y轴范围
plt.title('douban_top250') # 图表的标题 fontproperties='simhei'
plt.ylabel('movie category') # 图表y轴的标记
plt.subplots_adjust(bottom = 0.15)
plt.xlabel('count') # 图表x轴的标记
#plt.savefig('douban.png') # 保存图片
plt.show()
示例12: histogram
def histogram(arrayGenes):
arrayG = np.array(arrayGenes)
mean = arrayG.mean()
std = arrayG.std()
print 'mean = ', mean
print 'std = ', std
# mu, sigma = 100, 15
# x = mu + sigma * np.random.randn(100)
#
# print np.random.randn(2)
#
# for each in x:
# print each
# the histogram of the data
n, bins, patches = plt.hist(arrayG, 60, normed=1, facecolor='g', alpha=0.75)
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.axis([0, 1000, 0, 1000])
plt.grid(True)
plt.show()
示例13: labelgridcells
def labelgridcells(shapefile):
labelcount=len(shapef.shapes())
for shape in shapef.shapes():
x,y= gMap(shape.points[0][0],shape.points[0][1])
plt.text(x,y,labelcount,color='w')
#print str(labelcount)+' '+str(shape.points[0][0])+' '+str(shape.points[0][1])
labelcount-=1
示例14: plot_traj
def plot_traj(self,ap=True,ag=True,fig=[],cps=20,ans=40,**kwargs):
if fig ==[]:
fig = plt.figure('trajectory', figsize=(20, 5), dpi=100)
fig, ax = self.layout.showG('s',fig=fig,nodes=False,**kwargs)
if ag:
for i,n in enumerate(self.agents):
cp=0
for j,p in enumerate(self.data[n]['p']):
if j == 0:
ax.plot(p[0],p[1],'o',color=self.colors[n],label='agent #'+n,**kwargs)
else: # to avoid multiple label in legend
ax.plot(p[0],p[1],'o',color=self.colors[n],**kwargs)
if j%self.checkpoint==0:
ax.plot(p[0],p[1],'o',color=self.colors[n],ms=cps)
plt.text(p[0]-0.2,p[1]-0.2, str(cp), fontsize=10)
cp = cp+1
if ap:
for i,n in enumerate(self.ap):
if n =='6' or n == '9':
color='r'
else :
color='g'
ax.plot(self.data[n]['p'][0,0],self.data[n]['p'][0,1]
,'^',color=color,label='AP #'+n,ms=ans)
ax.grid('off')
ax.legend(numpoints=1)
return fig,ax
示例15: draw_path
def draw_path(order, boundaries=None):
if boundaries:
(p1, p2, p3), (p1a, p2a, p3a) = boundaries
b_dict = {p1: "p1", p1a: "p1a", p2: "p2", p2a: "p2a", p3: "p3", p3a: "p3a"}
else:
b_dict = {}
locations = hack_locations
locations2 = np.zeros(locations.shape)
for i in order:
locations2[i, :] = locations[order[i], :]
print locations
print order
print locations2
x1 = []
y1 = []
delta = 0.0
for i in order:
x1.append(locations[i, 0] - delta)
y1.append(locations[i, 1] - delta)
delta -= 0.005
x1.append(locations[order[0], 0])
y1.append(locations[order[0], 1])
plt.xlim((-0.1, 1.2))
plt.ylim((-0.1, 1.2))
plt.plot(x1, y1, marker="x", linestyle="-", color="b")
for i, o in enumerate(order):
plt.text(x1[i], y1[i] + 0.01, "%d %s" % (i, b_dict.get(i, "")))