本文整理汇总了Python中matplotlib.pyplot.vlines函数的典型用法代码示例。如果您正苦于以下问题:Python vlines函数的具体用法?Python vlines怎么用?Python vlines使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了vlines函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: plot
def plot(learned_q, imitated_q):
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
plt.ion()
plt.figure(figsize=(16,9)) # Change this if figure is too big (i.e. laptop)
gs = gridspec.GridSpec(1, 2, width_ratios=[1,2])
while True:
plt.subplot(gs[0])
plt.cla()
plt.title('Learned.')
plt.legend(plt.plot(learned_q.get()), ['level1', 'envelope1', 'pitch1', 'centroid1'])
plt.draw()
plt.subplot(gs[1])
plt.cla()
plt.title('Listening + imitation.')
input_data, sound = imitated_q.get()
plt.plot(np.vstack( [input_data, sound] ))
ylim = plt.gca().get_ylim()
plt.vlines(input_data.shape[0], ylim[0], ylim[1])
plt.gca().annotate('imitation starts', xy=(input_data.shape[0],0),
xytext=(input_data.shape[0] + 10, ylim[0] + .1))
plt.gca().set_ylim(ylim)
plt.draw()
plt.tight_layout()
示例2: plot_percolation_data
def plot_percolation_data(gvals, m, M):
for var in gvals:
plt.title(var)
if len(gvals[var].shape) == 1 and var != 'p':
plt.vlines([m,M], 0, np.max(gvals[var]))
plt.scatter(gvals['p'], gvals[var])
plt.show()
示例3: plotOEM4strainsT
def plotOEM4strainsT(oemfilestrain1,strain1label,oemfilestrain2,strain2label,oemfilestrain3,strain3label,oemfilestrain4,strain4label,chromosome,showorigins,showreptime,reptimefile=''):
# if showreptime is true, then grab all rep times for chromosome and bin the bases in earlyreptimebases and latereptimebass.
if showreptime:
with open(reptimefile) as f:
reptimeforchrom = [line.strip().split('\t')[1:] for line in f.readlines() if line.strip().split('\t')[0]==chromosome]
earlyreptimebases = [int(i[0]) for i in reptimeforchrom if float(i[1])<=30]
latereptimebases = [int(i[0]) for i in reptimeforchrom if float(i[1])>30]
# Plot OEM for WT with origins if showorigins is TRUE, otherwise plot oem but don't show confirmed or likely orgins
if showorigins:
oem.plotOEM(oemfilestrain1,chromosome,True,411,strain1label,'green')
plt.subplots_adjust(hspace=0.5)
oem.plotOEM(oemfilestrain2,chromosome,True,412,strain2label,'blue')
plt.subplots_adjust(hspace=0.5)
oem.plotOEM(oemfilestrain3,chromosome,True,413,strain3label,'red')
plt.subplots_adjust(hspace=0.5)
oem.plotOEM(oemfilestrain4,chromosome,True,414,strain4label,'#FF7F00')
else:
oem.plotOEM(oemfilestrain1,chromosome,False,411,strain1label,'green')
plt.subplots_adjust(hspace=0.5)
oem.plotOEM(oemfilestrain2,chromosome,False,412,strain2label,'blue')
plt.subplots_adjust(hspace=0.5)
oem.plotOEM(oemfilestrain3,chromosome,False,413,strain3label,'red')
plt.subplots_adjust(hspace=0.5)
oem.plotOEM(oemfilestrain4,chromosome,False,414,strain4label,'#FF7F00')
# if showreptime is true, plot vertical lines to indicate where the early and late replicating bases are
if showreptime:
for base in earlyreptimebases:
plt.vlines(base,-1,1,colors='red')
for base in latereptimebases:
plt.vlines(base,-1,1,colors='black')
plt.show()
示例4: _expand_dendrogram
def _expand_dendrogram(cNode,swc_tree,off_x,off_y,radius,transform='plain') :
global max_width,max_height # middle name d.i.r.t.y.
'''
Gold old fashioned recursion... sys.setrecursionlimit()!
'''
place_holder_h = H_SPACE
max_degree = swc_tree.degree_of_node(cNode)
required_h_space = max_degree * place_holder_h
start_x = off_x-(required_h_space/2.0)
if(required_h_space > max_width) :
max_width = required_h_space
if swc_tree.is_root(cNode) :
print 'i am expanding the root'
cNode.children.remove(swc_tree.get_node_with_index(2))
cNode.children.remove(swc_tree.get_node_with_index(3))
for cChild in cNode.children :
l = _path_between(swc_tree,cChild,cNode,transform=transform)
r = cChild.content['p3d'].radius
cChild_degree = swc_tree.degree_of_node(cChild)
new_off_x = start_x + ( (cChild_degree/2.0)*place_holder_h )
new_off_y = off_y+(V_SPACE*2)+l
r = r if radius else 1
plt.vlines(new_off_x,off_y+V_SPACE,new_off_y,linewidth=r,colors=C)
if((off_y+(V_SPACE*2)+l) > max_height) :
max_height = off_y+(V_SPACE*2)+l
_expand_dendrogram(cChild,swc_tree,new_off_x,new_off_y,radius=radius,transform=transform)
start_x = start_x + (cChild_degree*place_holder_h)
plt.hlines(off_y+V_SPACE,off_x,new_off_x,colors=C)
示例5: plot_area_vs_energy
def plot_area_vs_energy(self, filename=None, show_save_energy=True):
"""
Plot effective area vs. energy.
"""
import matplotlib.pyplot as plt
energy_hi = self.energy_hi.value
effective_area = self.effective_area.value
plt.plot(energy_hi, effective_area)
if show_save_energy:
plt.vlines(self.energy_thresh_hi.value, 1E3, 1E7, 'k', linestyles='--')
plt.text(self.energy_thresh_hi.value - 1, 3E6,
'Safe energy threshold: {0:3.2f}'.format(
self.energy_thresh_hi),
ha='right')
plt.vlines(self.energy_thresh_lo.value, 1E3, 1E7, 'k', linestyles='--')
plt.text(self.energy_thresh_lo.value + 0.1, 3E3,
'Safe energy threshold: {0:3.2f}'.format(self.energy_thresh_lo))
plt.xlim(0.1, 100)
plt.ylim(1E3, 1E7)
plt.loglog()
plt.xlabel('Energy [TeV]')
plt.ylabel('Effective Area [m^2]')
if filename is not None:
plt.savefig(filename)
log.info('Wrote {0}'.format(filename))
示例6: funComputeRatioFromExperiment
def funComputeRatioFromExperiment(dataRatioRGBY, dataRatioRGBL, valLevelBasis, valLevelTarget, dataTargetY, dataBasisY, titleText, figureName):
'''
The function first first display the results.
Then it does some computations because computations are always good.
'''
# do some interpolation
interpInput, interpY = funInterpolationRatioDifferenceCurves(vecSearchLevel, dataRatioRGBY)
interpInput, interpTargetY = funInterpolationRatioDifferenceCurves(vecSearchLevel, dataTargetY)
interpInput, interpBasisY = funInterpolationRatioDifferenceCurves(vecSearchLevel, dataBasisY)
# figure to show the search of equivalent intensity between the patches
fig = plt.figure()
yMin = 0
yMax = 4.2*np.max(interpTargetY)
#print yMax
# plot the differences and minimum
plt.plot(interpInput, interpY[0,:],'r-', label="Y difference Red ")
plt.plot(interpInput, interpY[1,:],'g-', label="Y difference Green")
plt.plot(interpInput, interpY[2,:],'b-', label="Y difference Blue")
# plot the measured intensity
plt.plot(interpInput, interpBasisY[0,:],'r--', label="Y Red + basis ")
plt.plot(interpInput, interpBasisY[1,:],'g--', label="Y Green + basis")
plt.plot(interpInput, interpBasisY[2,:],'b--', label="Y Blue + basis")
# plot the target patch who should stay stable
plt.plot(interpInput, interpTargetY[0,:],'k-', label="Y target for red ")
plt.plot(interpInput, interpTargetY[1,:],'k--',label="Y target for green")
plt.plot(interpInput, interpTargetY[2,:],'k-', label="Y target for blue")
# plot the minimum
minDiffInterpRGB, indRGB = funGetSomeMinimumSingleCurve(interpY)
plt.plot(indRGB[0], minDiffInterpRGB[0],'r^')
plt.plot(indRGB[1], minDiffInterpRGB[1],'g^')
plt.plot(indRGB[2], minDiffInterpRGB[2],'b^')
plt.vlines(indRGB[0],0,minDiffInterpRGB[0], colors='r',linestyles='--')
plt.vlines(indRGB[1],0,minDiffInterpRGB[1], colors='g',linestyles='--')
plt.vlines(indRGB[2],0,minDiffInterpRGB[2], colors='b',linestyles='--')
# plot the experiment information
plt.vlines(valLevelBasis[0], yMin, yMax, colors='k', linestyles='--', label='Basis')
plt.vlines(valLevelTarget, yMin, yMax, colors='k', linestyles='--', label='Target')
plt.text(valLevelBasis[0], yMax*0.9,'Basis = '+repr(valLevelBasis[0]), ha="left",bbox = dict(boxstyle='round', fc="w", ec="k"))
plt.text(valLevelTarget, yMax*0.8,'Target = '+repr(valLevelTarget), ha="left",bbox = dict(boxstyle='round', fc="w", ec="k"))
plt.ylabel('Difference in Y')
plt.xlabel('Digital input')
plt.xlim(0,255)
plt.title('Difference Curve for Ratio')
plt.ylim(yMin, yMax)
plt.title(titleText)
#plt.legend(loc=2)
plt.draw()
plt.savefig(figureName)
ratioRGB = np.zeros([3])
ratioRGB[0], ratioRGB[1], ratioRGB[2] = indRGB[0], indRGB[1], indRGB[2]
return ratioRGB
示例7: _plotKmerFixed
def _plotKmerFixed(min_limit, max_limit, kmer, output_name):
"""Old kmerplot, kept just in case...
"""
Kmer_histogram = pd.io.parsers.read_csv("histogram.hist", 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
示例8: plot_unique_by_date
def plot_unique_by_date(alignment_summaries, metadata):
plt.figure(figsize=(8, 5.5))
df_meta = pd.DataFrame.from_csv(metadata)
df_meta['Date Produced'] = pd.to_datetime(df_meta['Date Produced'])
alndata = []
for summary in alignment_summaries:
alndata.append(simpleseq.sam.get_alignment_metadata(summary))
unique = pd.Series(np.array([s['uniq_rate'] for s in alndata]),
index=alignment_summaries)
# plot unique alignments
index = df_meta.index.intersection(unique.index)
order = df_meta.loc[index].sort(columns='Date Produced', ascending=False).index
left = np.arange(len(index))
height = unique.ix[order]
width = 0.9
plt.barh(left, height, width)
plt.yticks(left + 0.5, order, fontsize=10)
ymin, ymax = 0, len(left)
plt.ylim((ymin, ymax))
plt.xlabel('percentage')
plt.title('comparative alignment summary')
plt.ylabel('time (descending)')
# plot klein in-drop line
plt.vlines(unique['Klein_in_drop'], ymin, ymax, color='indianred', linestyles='--')
sns.despine()
plt.tight_layout()
示例9: plotRaster
def plotRaster(xsg, ax=None, height=1.):
"""Creates raster plot from a merged or unmerged XSG dictionary.
Note that the dictionary has to have the key 'spikeTimes', which is
generated by detectSpikes(). The value of this key is a single numpy array
with spike loctions in samples (or a list of such arrays).
Note that we plot these based on the size of the traces themselves.
This works because we split up our acquisitions, but in general,
we might want to only plot regions of the raster. plt.xlim() should
be able to be used post-hoc for this.
:param: - xsg - a merged or unmerged XSG dictionary with a 'spikeTimes' entry
:param: - ax - optional, a matplotlib axis to plot onto
:param: - height - optional, spacing for the rasters
"""
if ax is None:
ax = plt.gca() # otherwise it'll plot on the top figure
try:
if type(xsg['spikeTimes']) is list:
for trial, trace in enumerate(xsg['spikeTimes']):
plt.vlines(trace, trial, trial+height)
plt.ylim(len(xsg['spikeTimes']), 0)
plt.xlim(0,float(xsg['ephys']['chan0'].shape[0]) / xsg['sampleRate'][0] * 1000.0)
else:
plt.vlines(xsg['spikeTimes'], 0, height)
plt.ylim((0,1))
plt.xlim(0,float(xsg['ephys']['chan0'].shape[0]) / xsg['sampleRate'] * 1000.0)
plt.xlabel('time (ms)')
plt.ylabel('trials')
except:
print 'No spike times found!'
示例10: plot
def plot(self):
global TESTING, UNITS, HEIGHTS
'''Prepares the data using self.prepare_data and then
graphs the data on a plot.'''
self.prepare_data()
plt.plot(HEIGHTS, self.data)
plt.hlines(self.significant_shear, 0, HEIGHTS[-1])
plt.vlines(self.significant_shear_height, -1, 2)
print 'Significant shear at image {0}'.format(self.x_significant_shear)
if not TESTING:
print 'Theoretical significant shear at height {0} {1}'.format(self.significant_shear_height, UNITS)
plt.ylim([-1, 2])
plt.xlim([HEIGHTS[0], HEIGHTS[-1]])
plt.xlabel('Height ({0})'.format(UNITS))
plt.ylabel('Coverage')
plt.title(self.dp_path.split('/')[-1])
try:
os.mkdir('{0}/res'.format(self.dp_path))
except:
pass
plt.savefig('{0}/res/results.png'.format(self.dp_path))
with open('{0}/res/results.txt'.format(self.dp_path), 'w') as f:
global MODE
f.write('{0}\nMODE {1}\n'.format(str(self.significant_shear_height), MODE))
示例11: estPath
def estPath(values):
"""estimates path
Args:
values: dict of x and y
Returns:
alphas: regularization lambdas
coefs: coef matrix for features and alphas
"""
X,y = values["x"], values["y"]
alphas, _, coefs = linear_model.lars_path(X, y, method='lasso', verbose=True)
return alphas,coefs
print alphas
print coefs
print coefs[:,1]
exit(1)
xx = np.sum(np.abs(coefs.T), axis=1)
xx /= xx[-1]
plt.plot(xx, coefs.T)
ymin, ymax = plt.ylim()
plt.vlines(xx, ymin, ymax, linestyle='dashed')
plt.xlabel('|coef| / max|coef|')
plt.ylabel('Coefficients')
plt.title('LASSO Path')
plt.axis('tight')
plt.show()
plt.savefid("larspath.png")
示例12: plot_assumption_free
def plot_assumption_free(scores, data, bins=50):
"""
Plots the scores from the analysis using the assumption free algorithm.
"""
plt.figure()
plt.subplot(2, 1, 1)
(data.acc / data.acc.max()).plot()
(data.hr / data.hr.max()).plot()
data.ratio_log.plot()
plt.legend(loc='best')
plt.subplot(2, 1, 2)
plt.plot(data.index[:len(scores)], scores)
scores = [x for x in scores if abs(x) > 10 ** -10]
s_mean, sigma = norm.fit(scores)
plt.figure()
plt.hist(scores, bins=50, normed=True)
plt.plot(bins, norm.pdf(bins, loc=s_mean, scale=sigma))
vlin = linspace(s_mean - 3 * sigma, s_mean + 3 * sigma, 13)
step = int(256 / ((len(vlin) - 1) / 2))
colors = linspace(0, 1, 256)[::step][:(len(vlin) - 1) / 2]
colors = [(c, 0, 0) for c in colors]
colors += [(1, 1, 1)]
colors += [(0, c, 0) for c in reversed(colors)]
plt.vlines(vlin.tolist()[1:], 0, 1, colors[1:])
示例13: plot_result
def plot_result(self, list_of_res, extra_txt='', dir_path='', big_figure=True, gui=False):
if not gui or self.show:
if big_figure:
plt.figure(figsize=(10, 14))
else:
plt.figure()
cpt = 1
color = ['b', 'r', 'g', 'm', 'c', 'y', 'k']
for key in list_of_res:
plt.subplot(len(list_of_res.keys()), 1, cpt)
plt.plot(list_of_res[key], color[cpt%len(color)], label=key)
plt.ylabel(key, rotation=0)
plt.ylim(-0.2, 1.2)
for i in range(len(list_of_res['gnd_truth'])):
if list_of_res['gnd_truth'][i-1] != list_of_res['gnd_truth'][i]:
plt.vlines(i, -0.2, len(list_of_res)*1.2+0.2, 'b', '--')
cpt += 1
plt.tight_layout()
if self.save:
plt.savefig(dir_path + 'result' + extra_txt + self.ext_img, dpi=100)
if self.show:
plt.show()
else:
if gui:
plt.clf()
else:
plt.close()
示例14: analyse_given_data_set
def analyse_given_data_set(data):
# Confirm that data has been read and output properties of file
number_of_players = len(data)
print "Data file read with %s players" % number_of_players
# Calculating mean of guesses
first_guess_mean = sum([e[1] for e in data]) / number_of_players
print "Mean of the guess: %s so 2/3rds of mean is: %s" % (first_guess_mean, 2 * first_guess_mean / 3)
first_guess_distance = [abs(e[1] - 2 * first_guess_mean / 3)for e in data]
winning_first_guess = data[first_guess_distance.index(min(first_guess_distance))][1]
print "Winning guess: %s" % winning_first_guess
# Display winner
print "The winning user name(s) are/is:"
for e in data:
if e[1] == winning_first_guess:
print "\t" + e[0]
print "\t\t" + e[0] + " guessed " + e[4] + " time(s) with the last guess on the " + e[3] + " (with url: " + e[2] + ")"
# Plot histograms of guesses using matplotlib
plt.figure()
plt.hist([e[1] for e in data], bins=20, label='Guess', normed='True')
plt.title("Two thirds of the average game ($N=%s$)." % number_of_players)
plt.xlabel("Guess")
plt.ylabel("Probability")
max_y = plt.ylim()[1]
plt.vlines(winning_first_guess, 0, max_y, label='Winning Guess: %s' % winning_first_guess, color='blue')
plt.ylim(0, max_y)
plt.xlim(0, 100)
plt.legend()
plt.savefig("Results_for_webapp.png")
开发者ID:drvinceknight,项目名称:two_thirds_of_the_average_game,代码行数:32,代码来源:analyse_data_from_app_engine.py
示例15: plot_zrtt_treshold
def plot_zrtt_treshold(data, output_path):
threshold = 1
gateways, zrtts = [], []
for hop in data:
ip, pais, zrtt = hop
gateways.append(ip+"\n"+pais)
zrtts.append(float(zrtt))
gateways.reverse()
zrtts.reverse()
fig = plt.figure()
y_pos = np.arange(len(gateways))
plt.barh(y_pos, zrtts, align='center', alpha=0.4)
plt.yticks(y_pos, gateways, horizontalalignment='right', fontsize=9)
plt.title('ZRTTs para cada hop')
plt.xlabel('ZRTT')
plt.ylabel('Hop')
# Line at y=0
plt.vlines(0, -1, len(gateways), alpha=0.4)
# ZRTT threshold
plt.vlines(threshold, -1, len(gateways), linestyle='--', color='b', alpha=0.4)
plt.text(threshold, len(gateways) - 1, 'Umbral', rotation='vertical',
verticalalignment='top', horizontalalignment='right')
fig.set_size_inches(6, 9)
plt.tight_layout()
plt.savefig(output_path, dpi=1000, box_inches='tight')