本文整理汇总了Python中pylab.annotate函数的典型用法代码示例。如果您正苦于以下问题:Python annotate函数的具体用法?Python annotate怎么用?Python annotate使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了annotate函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: plotScoringFunction
def plotScoringFunction(data, bestParameterSet, patients, scoringFunction):
x = []
y = []
labels = []
for i in range(data.shape[1]):
if (
abs((data[:, i][0]) - (bestParameterSet[0])) < 0.00001
and abs((data[:, i][2]) - (bestParameterSet[2])) < 0.00001
and abs((data[:, i][1]) - (bestParameterSet[1])) < 0.00001
and abs((data[:, i][3]) - (bestParameterSet[3])) < 0.00001
and abs((data[:, i][4]) - (bestParameterSet[4])) < 0.00001
):
x += [data[:, i][5]]
y += [data[:, i][6]]
labels += [patients[i]]
scoringFunction(x, y, plot=True)
for label, xi, yi in zip(labels, x, y):
plt.annotate(
label,
xy=(xi, yi),
textcoords="offset points",
ha="right",
va="bottom",
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=0"),
)
开发者ID:junggi,项目名称:Rest,代码行数:26,代码来源:plotResults.py
示例2: graphSimpleResults
def graphSimpleResults(resultsDir):
x=[]
y=[]
files=[open("%s/objectiveFunctionReport.txt" % resultsDir),
open("%s/fitnessReport.txt" % resultsDir)]
for f in files:
x.append([])
y.append([])
i=len(x)-1
for line in f:
line=line.split(',')
if line[0] != "gen":
x[i].append(int(line[0]))
y[i].append(float(line[1]))
ylen=len(y[0])
pl.subplot(2,1,1)
pl.plot(x[0],y[0],'bo')
pl.ylabel('Maximum x')
pl.title('Maximizing x**2 with SGA')
pl.annotate("{0:,}".format(y[0][0]),xy=(x[0][0],y[0][0]), xycoords='data',
xytext=(50, 30), textcoords='offset points',
arrowprops=dict(arrowstyle="->") )
pl.annotate("{0:,}".format(y[0][ylen-1]),xy=(x[0][ylen-1],y[0][ylen-1]), xycoords='data',
xytext=(-30, -30), textcoords='offset points',
arrowprops=dict(arrowstyle="->") )
pl.subplot(2,1,2)
pl.plot(x[1],y[1],'go')
pl.xlabel('Generation')
pl.ylabel('Fitness')
pl.savefig("%s/simple_result.png" % resultsDir)
开发者ID:valreee,项目名称:GeneticAlgorithms,代码行数:32,代码来源:utilities.py
示例3: plot_datasets
def plot_datasets(dataset_ids, title=None, legend=True, labels=True):
"""
Plots one or more dataset.
:param dataset_ids: list of datasets to plot
:type dataset_ids: list of integers
:param title: title of the plot
:type title: string
:param legend: whether or not to show legend
:type legend: boolean
:param labels: whether or not to plot point labels
:type labels: boolean
"""
title = title if title else "Datasets " + ",".join(
[str(d) for d in dataset_ids])
pl.title(title)
data = {k: v for k, v in npoints.items() if k in dataset_ids}
lines = [pl.plot(zip(*p)[0], zip(*p)[1], 'o-')[0] for p in data.values()]
if legend:
pl.legend(lines, data.keys())
if labels:
for x, y, l in [i for s in data.values() for i in s]:
pl.annotate(str(l), xy=(x, y), xytext=(x, y + 0.1))
pl.grid(True)
return pl
开发者ID:fhirschmann,项目名称:algolab,代码行数:31,代码来源:plot.py
示例4: annotator
def annotator(data, labels, lang):
labelStyle = 'normal' if lang == 'en' else 'italic'
color = 'blue' if lang == 'en' else 'red'
for label, x, y in zip(labels, data[:, 0], data[:, 1]):
if label in ['man','hombre','woman','mujer']:
pylab.scatter([x],[y],20,[color])
pylab.annotate(label, xy = (x, y), style = labelStyle)
开发者ID:hans,项目名称:deepBLE,代码行数:7,代码来源:plottest.py
示例5: draw_circle_arcs
def draw_circle_arcs(arcs,n=100,label=False,full=False,dots=False,jitter=None):
import pylab
for p,poly in enumerate(arcs):
X = poly['x']
q = poly['q']
Xn = roll(X,-1,axis=0)
l = magnitudes(Xn-X)
center = .5*(X+Xn)+.25*(1/q-q).reshape(-1,1)*rotate_left_90(Xn-X)
if 0:
print 'draw %d: x0 %s, x1 %s, center %s'%(0,X[0],Xn[0],center[0])
radius = .25*l*(1/q+q)
print 'radius = %s'%radius
assert allclose(magnitudes(X-center),abs(radius))
theta = array([2*pi]) if full else 4*atan(q)
points = center.reshape(-1,1,2)+Rotation.from_angle(theta[:,None]*arange(n+1)/n)*(X-center).reshape(-1,1,2)
if dots:
pylab.plot(X[:,0],X[:,1],'.')
if full:
for i,pp in enumerate(points):
pylab.plot(pp[:,0],pp[:,1],'--')
pylab.plot(center[i,0],center[i,1],'+')
if label:
pylab.annotate(str(arcs.offsets[p]+i),center[i])
else:
if label:
for i in xrange(len(poly)):
pylab.annotate(str(arcs.offsets[p]+i),points[i,n//2])
points = concatenate([points.reshape(-1,2),[points[-1,-1]]])
if jitter is not None:
points += jitter*random.uniform(-1,1,points.shape) # Jitter if you want to be able to differentiate concident points:
pylab.plot(points[:,0],points[:,1])
开发者ID:omco,项目名称:geode,代码行数:31,代码来源:test_circle.py
示例6: plot_words
def plot_words(wordVectors, set1p, set1n, imgFile):
X = []
labels = []
for word in set1p+set1n:
if word in wordVectors:
labels.append(word)
X.append(wordVectors[word])
X = numpy.array(X)
for r, row in enumerate(X):
X[r] /= math.sqrt((X[r]**2).sum() + 1e-6)
Y = tsne(X, 2, 80, 20.0);
Plot.scatter(Y[:,0], Y[:,1], s=0.1)
for label, x, y in zip(labels, Y[:, 0], Y[:, 1]):
if label in set1p:
Plot.annotate(
label, color="green", xy = (x, y), xytext = None,
textcoords = None, bbox = None, arrowprops = None, size=10
)
if label in set1n:
Plot.annotate(
label, color="red", xy = (x, y), xytext = None,
textcoords = None, bbox = None, arrowprops = None, size=10
)
Plot.savefig(imgFile, bbox_inches='tight')
Plot.close()
开发者ID:billy322,项目名称:Python,代码行数:29,代码来源:tsne+copy.py
示例7: demo_fwhm
def demo_fwhm():
"""
Show the available interface functions and the corresponding probability
density functions.
"""
# Plot the cdf and pdf
import pylab
w = 10
perf = Erf.as_fwhm(w)
ptanh = Tanh.as_fwhm(w)
z = pylab.linspace(-w, w, 800)
pylab.subplot(211)
pylab.plot(z, perf.cdf(z))
pylab.plot(z, ptanh.cdf(z))
pylab.legend(['erf', 'tanh'])
pylab.grid(True)
pylab.subplot(212)
pylab.plot(z, perf.pdf(z), 'b')
pylab.plot(z, ptanh.pdf(z), 'g')
pylab.legend(['erf', 'tanh'])
# Show fwhm
arrowprops = dict(arrowstyle='wedge', connectionstyle='arc3', fc='0.6')
bbox = dict(boxstyle='round', fc='0.8')
pylab.annotate('erf FWHM', xy=(w/2, perf.pdf(0)/2),
xytext=(-35, 10), textcoords="offset points",
arrowprops=arrowprops, bbox=bbox)
pylab.annotate('tanh FWHM', xy=(w/2, ptanh.pdf(0)/2),
xytext=(-35, -35), textcoords="offset points",
arrowprops=arrowprops, bbox=bbox)
pylab.grid(True)
开发者ID:reflectometry,项目名称:refl1d,代码行数:34,代码来源:interface.py
示例8: PlotNumberOfTags
def PlotNumberOfTags(corpus):
word_tag_dict = defaultdict(set)
for (word, tag) in corpus:
word_tag_dict[word].add(tag)
# using Counter for efficiency (leaner than FreqDist)
C = Counter(len(val) for val in word_tag_dict.itervalues())
pylab.subplot(211)
pylab.plot(C.keys(), C.values(), '-go', label='Linear Scale')
pylab.suptitle('Word Ambiguity:')
pylab.title('Number of Words by Possible Tag Number')
pylab.box('off') # for better appearance
pylab.grid('on') # for better appearance
pylab.ylabel('Words With This Number of Tags (Linear)')
pylab.legend(loc=0)
# add value tags
for x,y in zip(C.keys(), C.values()):
pylab.annotate(str(y), (x,y + 0.5))
pylab.subplot(212)
pylab.plot(C.keys(), C.values(), '-bo', label='Logarithmic Scale')
pylab.yscale('log') # to make the graph more readable, for the log graph version
pylab.box('off') # for better appearance
pylab.grid('on') # for better appearance
pylab.xlabel('Number of Tags per Word')
pylab.ylabel('Words With This Number of Tags (Log)')
pylab.legend(loc=0)
# add value tags
for x,y in zip(C.keys(), C.values()):
pylab.annotate(str(y), (x,y + 0.5))
pylab.show()
开发者ID:lxmonk,项目名称:nlp122,代码行数:33,代码来源:code2.py
示例9: plot_dens
def plot_dens(x, y, filename, point):
majorLocator = MultipleLocator(1)
majorFormatter = FormatStrFormatter('%d')
minorLocator = MultipleLocator(0.2)
# fig = pl.figure()
fig, ax = plt.subplots()
pl.plot(x, y, 'b-', x, y, 'k.')
fig.suptitle(filename)
# pl.plot(z, R, 'k.')
#fig.set_xlim(0,4.0)
#fig.set_ylim(0,3)
# fig = plt.gcf()
plt.xticks(ticki)
# plt.xticks(range(0,d_max_y,50))
pl.xlim(0,12)
pl.ylim(0,max(y))
pl.xlabel('z [nm]')
pl.ylabel('Density [kg/nm3]')
# pl.grid(b=True, which='both', axis='both', color='r', linestyle='-', linewidth=0.5)
# fig.set_size_inches(18.5,10.5)
pl.annotate('first peak', xy=(point[0], point[1]), xycoords='data', xytext=(-50, 30), textcoords='offset points', arrowprops=dict(arrowstyle="->"))
ax.xaxis.set_major_locator(majorLocator)
ax.xaxis.set_major_formatter(majorFormatter)
#for the minor ticks, use no labels; default NullFormatter
ax.xaxis.set_minor_locator(minorLocator)
ax.xaxis.grid(True, which='minor')
ax.yaxis.grid(True, which='major')
return fig
开发者ID:burbol,项目名称:scripts,代码行数:34,代码来源:Water_PeakSearch.py
示例10: geom_Plot
def geom_Plot(self,plot_Node_Names = 0,Highlights = None):
pp.figure()
pp.title('Network Geometry')
for i in self.nodes:
if i.type == 'Node':
symbol = 'o'
size = 10
elif i.type == 'Reservoir':
symbol = 's'
size = 20
elif i.type == 'Tank':
symbol = (5,2)
size = 20
c = 'k'
if i.Name in Highlights:
size = 40
c = 'r'
pp.scatter([i.xPos],[i.yPos],marker = symbol,s = size,c=c)
if plot_Node_Names != 0:
pp.annotate(i.Name,(i.xPos,i.yPos))
for i in self.pipes:
pp.plot([i.x1,i.x2],[i.y1,i.y2],'k')
for i in self.valves:
pp.plot([i.x1,i.x2],[i.y1,i.y2],'r')
for i in self.pumps:
pp.plot([i.x1,i.x2],[i.y1,i.y2],'g')
pp.axis('equal')
pp.show()
开发者ID:richpaulcol,项目名称:PWG-Transient-Solver,代码行数:32,代码来源:network.py
示例11: display_data
def display_data(word_vectors, words, target_words=None):
target_matrix = word_vectors.copy()
if target_words:
target_words = [line.strip().lower() for line in open(target_words)][:2000]
rows = [words.index(word) for word in target_words if word in words]
target_matrix = target_matrix[rows,:]
else:
rows = np.random.choice(len(word_vectors), size=1000, replace=False)
target_matrix = target_matrix[rows,:]
reduced_matrix = tsne(target_matrix, 2);
Plot.figure(figsize=(200, 200), dpi=100)
max_x = np.amax(reduced_matrix, axis=0)[0]
max_y = np.amax(reduced_matrix, axis=0)[1]
Plot.xlim((-max_x,max_x))
Plot.ylim((-max_y,max_y))
Plot.scatter(reduced_matrix[:, 0], reduced_matrix[:, 1], 20);
for row_id in range(0, len(rows)):
target_word = words[rows[row_id]]
x = reduced_matrix[row_id, 0]
y = reduced_matrix[row_id, 1]
Plot.annotate(target_word, (x,y))
Plot.savefig("word_vectors.png");
开发者ID:aiedward,项目名称:nn4nlp-code,代码行数:25,代码来源:wordemb-vis-tsne.py
示例12: ManetPlot
def ManetPlot():
index_mob=0
index_route=00
plotting_time=0
pl.ion()
fig,ax=pl.subplots()
for index_mob in range(len(time_plot)):
# plot the nodes with the positions given by index_mob of x_plot and yplot
pl.scatter(x_plot[index_mob],y_plot[index_mob],s=100,c='g')
# print x_plot[index_mob],y_plot[index_mob]
for i, txt in enumerate(n):
pl.annotate(txt,(x_plot[index_mob, i]+10,y_plot[index_mob, i]+10))
pl.xlabel('x axis')
pl.ylabel('y axis')
# set axis limits
pl.xlim(0.0, xRange)
pl.ylim(0.0, yRange)
pl.title("Position updation at "+str(time_plot[index_mob]))
# print time_plot[index_mob],route_table_time[index_route],ntemp,route_table[index_route,1:3]
# print_neighbors(neighbor_nodes_time,time_neighb,x_plot[index_mob,:],y_plot[index_mob,:])
pl.show()
pl.pause(.0005)
# show the plot on the screen
pl.clf()
开发者ID:Mishfad,项目名称:aodv_routing,代码行数:26,代码来源:plot_node_movement.py
示例13: draw_results
def draw_results(self, all_results):
## Plot the map
# Define some styles for plots
found_style = {'linewidth':1.5,
'marker':'o',
'markersize':4,
'color':'w'}
executed_style = {'linewidth':4,
'marker':'.',
'markersize':15,
'color':'b'}
# pdb.set_trace()
for r, run_result in enumerate(all_results):
for i, iter_result in enumerate(run_result['iter_results']):
# Plot the executed part
self.plot_plan_line(iter_result['start_state'],
iter_result['plan_executed'],
**executed_style)
pylab.annotate(str(i), xy=iter_result['start_state'], xytext=(5, 5), textcoords='offset points')
# Plot the found plan
self.plot_plan_line(iter_result['start_state'],
iter_result['plan_found'],
**found_style)
pylab.savefig('map_' + str(r) + '_it' + str(i) + '.png')
开发者ID:AndreaCensi,项目名称:surf12adam,代码行数:28,代码来源:diffeo_planner.py
示例14: stringtest
def stringtest():
import Levenshtein
strings = [
"King Crimson",
"King Lear",
"Denis Leary",
"George Bush",
"George W. Bush",
"Barack Hussein Obama",
"Saddam Hussein",
"George Leary",
]
dist = distmatrix(strings, c=lambda x, y: 1 - Levenshtein.ratio(x, y))
p = fastmap(dist, 2)
import pylab
pylab.scatter([x[0] for x in p], [x[1] for x in p], c="r")
for i, s in enumerate(strings):
pylab.annotate(s, p[i])
pylab.title("Levenshtein distance mapped to 2D coordinates")
# pylab.show()
pylab.savefig("fastmap2.png")
开发者ID:fabbasi,项目名称:IDS-scripts,代码行数:27,代码来源:fastmap.py
示例15: _plot
def _plot(self, fits_params, tau, tsys, r2, sec_el, fit, hot_sky, path):
"""
図の出力、保存
"""
fig = pylab.figure()
pylab.grid()
pylab.ylabel("log((Phot-Psky)/Phot)")
pylab.xlabel("secZ")
pylab.plot(sec_el, hot_sky, "o", markersize=7)
pylab.plot(sec_el, fit)
pylab.annotate(
"tau = %.2f, Tsys* = %.2f, R^2 = %.3f" % (tau, tsys, r2),
xy=(0.6, 0.9),
xycoords="axes fraction",
size="small",
)
# if (fits_params[0]["BACKEND"])[-1]=="1" : direction="H"
# elif (fits_params[0]["BACKEND"])[-1]=="2" : direction="V"
# else : pass
# figure_name = str(fits_params[0]["MOLECULE"])+direction+".png"
figure_name = str(fits_params[0]["MOLECULE"]) + ".png"
# file_manager.mkdir(path)
pylab.savefig(path + figure_name)
# file_manager.mkdir('/home/1.85m/data/Qlook/skydip/' + path.split('/')[-1])
# pylab.savefig('/home/1.85m/data/Qlook/skydip/'+ path.split('/')[-1] + '/' + figure_name)
"""
开发者ID:controlmanagement,项目名称:core,代码行数:29,代码来源:operator_skydip.py
示例16: tracePlot
def tracePlot(outpath, base_name, order_num, raw, fit, mask):
pl.figure("Trace Plot", figsize=(6, 5), facecolor='white')
pl.title('trace, ' + base_name + ", order " + str(order_num), fontsize=14)
pl.xlabel('column (pixels)')
pl.ylabel('row (pixels)')
# yrange = offraw.max() - offraw.min()
x = np.arange(raw.shape[0])
pl.plot(x[mask], raw[mask], "ko", mfc="none", ms=1.0, linewidth=1, label="derived")
pl.plot(x, fit, "k-", mfc="none", ms=1.0, linewidth=1, label="fit")
pl.plot(x[np.logical_not(mask)], raw[np.logical_not(mask)],
"ro", mfc="red", mec="red", ms=2.0, linewidth=2, label="ignored")
rms = np.sqrt(np.mean(np.square(raw - fit)))
pl.annotate('RMS residual = ' + "{:.3f}".format(rms), (0.3, 0.8), xycoords="figure fraction")
pl.minorticks_on()
pl.grid(True)
pl.legend(loc='best', prop={'size': 8})
fn = constructFileName(outpath, base_name, order_num, 'trace.png')
pl.savefig(fn)
pl.close()
log_fn(fn)
return
开发者ID:2ichard,项目名称:nirspec_drp,代码行数:31,代码来源:products.py
示例17: construct_gs_hist
def construct_gs_hist(del_bl=8.,num_bl=10,beam_sig=0.09,fq=0.1):
save_tag = 'grid_del_bl_{0:.2f}_num_bl_{1}_beam_sig_{2:.2f}_fq_{3:.3f}'.format(del_bl,num_bl,beam_sig,fq)
save_tag_mc = 'grid_del_bl_{0:.2f}_num_bl_{1}_beam_sig_{2:.2f}_fq_{3}'.format(del_bl,num_bl,beam_sig,fq)
ys = load_mc_data('{0}/monte_carlo/{1}'.format(data_loc,save_tag_mc))
print 'ys ',ys.shape
alms_fg = qgea.generate_sky_model_alms(gsm_fits_file,lmax=3)
alms_fg = alms_fg[:,2]
baselines,Q,lms = load_Q_file(gh='grid',del_bl=del_bl,num_bl=num_bl,beam_sig=beam_sig,fq=fq,lmax=3)
N = total_noise_covar(0.1,baselines.shape[0],'{0}/gsm_matrices/gsm_{1}.npz'.format(data_loc,save_tag))
MQN = return_MQdagNinv(Q,N,num_remov=None)
print MQN
ahat00s = n.array([])
for ii in xrange(ys.shape[1]):
#_,ahat,_ = qgea.test_recover_alms(ys[:,ii],Q,N,alms_fg,num_remov=None)
ahat = uf.vdot(MQN,ys[:,ii])
ahat00s = n.append(n.real(ahat[0]),ahat00s)
#print ahat00s
print ahat00s.shape
_,bins,_ = p.hist(ahat00s,bins=36,normed=True)
# plot best fit line
mu,sigma = norm.fit(ahat00s)
print "mu, sigma = ",mu,', ',sigma
y_fit = mpl.mlab.normpdf(bins,mu,sigma)
p.plot(bins, y_fit, 'r--', linewidth=2)
p.xlabel('ahat_00')
p.ylabel('Probability')
p.title(save_tag)
p.annotate('mu = {0:.2f}\nsigma = {1:.2f}'.format(mu,sigma), xy=(0.05, 0.5), xycoords='axes fraction')
p.savefig('./figures/monte_carlo/{0}.pdf'.format(save_tag))
p.clf()
开发者ID:SaulAryehKohn,项目名称:capo,代码行数:34,代码来源:monte_carlo_analysis.py
示例18: create_plot_2d_speeches
def create_plot_2d_speeches(self, withLabels = True):
if withLabels:
font = { 'fontname':'Tahoma', 'fontsize':0.5, 'verticalalignment': 'top', 'horizontalalignment':'center' }
labels= [ (i['who'], i['date']) for i in self.data ]
pylab.subplots_adjust(bottom =0.1)
pylab.scatter(self.speech_2d[:,0], self.speech_2d[:,1], marker = '.' ,cmap = pylab.get_cmap('Spectral'))
for label, x, y in zip(labels, self.speech_2d[:, 0], self.speech_2d[:, 1]):
pylab.annotate(
label,
xy = (x, y), xytext = None,
ha = 'right', va = 'bottom', **font)
#,textcoords = 'offset points',bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5),
#arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))
pylab.title('U.S. Presidential Speeches(1790-2006)')
pylab.xlabel('X')
pylab.ylabel('Y')
pylab.savefig('plot_with_labels', bbox_inches ='tight', dpi = 1000, orientation = 'landscape', papertype = 'a0')
else:
pylab.subplots_adjust(bottom =0.1)
pylab.scatter(self.speech_2d[:,0], self.speech_2d[:,1], marker = 'o' ,cmap = pylab.get_cmap('Spectral'))
pylab.title('U.S. Presidential Speeches(1790-2006)')
pylab.xlabel('X')
pylab.ylabel('Y')
pylab.savefig('plot_without_labels', bbox_inches ='tight', dpi = 1000, orientation = 'landscape', papertype = 'a0')
pylab.close()
开发者ID:Sophie-Germain,项目名称:U.S-Presidential-Speeches,代码行数:27,代码来源:w2v_tsne.py
示例19: transmission
def transmission(path,g,src,dest):
global disp_count
global bar_colors
global edge_colors
global node_colors
k=0
j=0
list_of_edges = g.edges()
for node in path :
k=path.index(node)
disp_count = disp_count + 1
if k != (len(path)-1):
k=path[k+1]
j=list_of_edges.index((node,k))
initialize_edge_colors(j)
#ec[disp_count].remove(-3000)
pylab.subplot(121)
nx.draw_networkx(g,pos = nx.circular_layout(g),node_color= node_colors,edge_color = edge_colors)
pylab.annotate("Source",node_positions[src])
pylab.annotate("Destination",node_positions[dest])
pylab.title("Transmission")
he=initializeEnergies(disp_count)
print he
pylab.subplot(122)
pylab.bar(left=[1,2,3,4,5],height=[300,300,300,300,300],width=0.5,color = ['w','w','w','w','w'],linewidth=0)
pylab.bar(left=[1,2,3,4,5],height=initializeEnergies(disp_count),width=0.5,color = 'b')
pylab.title("Node energies")
#pylab.legend(["already passed throgh","passing" , "yet to pass"])
pylab.xlabel('Node number')
pylab.ylabel('Energy')
pylab.suptitle('Leach Protocol', fontsize=12)
pylab.pause(2)
else :
return
开发者ID:ApoorvaChandraS,项目名称:wsn-gear-vs-leach,代码行数:35,代码来源:sim_file_leach.py
示例20: graph_file
def graph_file(obj, func_name, param, range, highlights):
## plots the named function on obj, taking param over its range (start, end)
## highlights are pairs of (x_value, "Text_to_show") to annotate on the graph plot
## saves the plot to a file and returns full file name
import numpy, pylab
func = getattr(obj, func_name)
f = numpy.vectorize(func)
x = numpy.linspace(*range)
y = f(x)
pylab.rc('font', family='serif', size=20)
pylab.plot(x, y)
pylab.xlabel(param)
pylab.ylabel(func_name)
hi_pts = [pt for pt, txt in highlights]
pylab.plot(hi_pts, f(hi_pts), 'rD')
for pt, txt in highlights:
pt_y = func(pt)
ann = txt + "\n(%s,%s)" % (pt, pt_y)
pylab.annotate(ann, xy=(pt, pt_y))
import os, time
file = os.path.dirname(__file__) + "/generated_graphs/%s.%s.%s.pdf" % (type(obj).__name__, func_name, time.time())
pylab.savefig(file, dpi=300)
pylab.close()
return file
开发者ID:kdz,项目名称:pystemm,代码行数:28,代码来源:model.py
注:本文中的pylab.annotate函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论