本文整理汇总了Python中matplotlib.pyplot.axhline函数的典型用法代码示例。如果您正苦于以下问题:Python axhline函数的具体用法?Python axhline怎么用?Python axhline使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了axhline函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: display_convw2
def display_convw2(w, s, r, c, fig, title='conv_filters'):
"""w: num_filters X sizeX**2 * num_colors."""
num_f, num_d = w.shape
assert s**2 * 3 == num_d
pvh = np.zeros((s*r, s*c, 3))
for i in range(r):
for j in range(c):
pvh[i*s:(i+1)*s, j*s:(j+1)*s, :] = w[i*c + j, :].reshape(3, s, s).T
mx = pvh.max()
mn = pvh.min()
pvh = 255*(pvh - mn) / (mx-mn)
pvh = pvh.astype('uint8')
plt.figure(fig)
plt.suptitle(title)
plt.imshow(pvh, interpolation="nearest")
scale = 1
xmax = s * c
ymax = s * r
color = 'k'
for x in range(0, c):
plt.axvline(x=x*s/scale, ymin=0, ymax=ymax/scale, color=color)
for y in range(0, r):
plt.axhline(y=y*s/scale, xmin=0, xmax=xmax/scale, color=color)
plt.draw()
return pvh
示例2: plotresult
def plotresult(i=0, j=101, step=1):
import matplotlib.pyplot as mpl
from numpy import arange
res = getevaluation(i, j, step)
x = [k / 100.0 for k in range(i, j, step)]
nbcurve = len(res[0])
nres = [[] for i in xrange(nbcurve)]
mres = []
maxofmin = -1, 0.01
for kindex, kres in enumerate(res):
minv = min(kres.values())
if minv > maxofmin[1]:
maxofmin = kindex, minv
lres = [(i, j) for i, j in kres.items()]
lres.sort(lambda x, y: cmp(x[0], y[0]))
for i, v in enumerate(lres):
nres[i].append(v[1])
mres.append(sum([j for i, j in lres]) / nbcurve)
print maxofmin
for y in nres:
mpl.plot(x, y)
mpl.plot(x, mres, linewidth=2)
mpl.ylim(0.5, 1)
mpl.xlim(0, 1)
mpl.axhline(0.8)
mpl.axvline(0.77)
mpl.xticks(arange(0, 1.1, 0.1))
mpl.yticks(arange(0.5, 1.04, 0.05))
mpl.show()
示例3: main
def main( args ):
hash = get_genes_with_features(args['file'])
for key, featurearray in hash.iteritems():
cluster, branch = key.split()
length = int(featurearray[0][0])
import matplotlib.pyplot as P
x = [e+1 for e in range(length+1)]
y1 = [0] * (length+1)
y2 = [0] * (length+1)
for feature in featurearray:
length, pos, aa, prob = feature[0:4]
if prob > 0.95: y1[pos] = prob
else: y2[pos] = prob
P.bar(x, y1, color='#000000', edgecolor='#000000')
P.bar(x, y2, color='#bbbbbb', edgecolor='#bbbbbb')
P.ylim(ymin=0, ymax=1)
P.xlim(xmin=0, xmax=length)
P.xlabel("position in the ungapped alignment [aa]")
P.ylabel(r'$P (\omega > 1)$')
P.title(cluster + " (branch " + branch + ")")
P.axhline(y=.95, xmin=0, xmax=length, linestyle=":", color="k")
P.savefig(cluster + "." + branch + ".png", format="png")
P.close()
示例4: plot_1d
def plot_1d(xdata, ydata, color, x_axis, y_axis, system, analysis, average = False, t0 = 0, **kwargs):
""" Creates a 1D scatter/line plot:
Usage: plot_1d(xdata, ydata, color, x_axis, y_axis, system, analysis, average = [False|True], t0 = 0)
Arguments:
xdata, ydata: self-explanatory
color: color to be used to plot data
x_axis, y_axis: strings to be used for the axis label
system: descriptor for the system that produced the data
analysis: descriptor for the analysis that produced the data
average: [False|True]; Default is False; if set to True, the function will calc the average, standard dev, and standard dev of mean of the y-data # THERE IS A BUG IF average=True; must read in yunits for this function to work at the moment.
t0: index to begin averaging from; Default is 0
kwargs:
xunits, yunits: string with correct math text describing the units for the x/y data
x_lim, y_lim: list w/ two elements, setting the limits of the x/y ranges of plot
plt_title: string to be added as the plot title
draw_line: int value that determines the line style to be drawn; giving myself space to add more line styles if I decide I need them
"""
# INITIATING THE PLOT...
plt.plot(xdata, ydata, '%s' %(color))
# READING IN KWARG DICTIONARY INTO SPECIFIC VARIABLES
for name, value in kwargs.items():
if name == 'xunits':
x_units = value
x_axis = '%s (%s)' %(x_axis, value)
elif name == 'yunits':
y_units = value
y_axis = '%s (%s)' %(y_axis, value)
elif name == 'x_lim':
plt.xlim(value)
elif name == 'y_lim':
plt.ylim(value)
elif name == 'plt_title':
plt.title(r'%s' %(value), size='14')
elif name == 'draw_line':
draw_line = value
if draw_line == 1:
plt.plot([0,max(ydata)],[0,max(ydata)],'r-',linewidth=2)
else:
print 'draw_line = %s has not been defined in plotting_functions script' %(line_value)
plt.grid(b=True, which='major', axis='both', color='#808080', linestyle='--')
plt.xlabel(r'%s' %(x_axis), size=12)
plt.ylabel(r'%s' %(y_axis), size=12)
# CALCULATING THE AVERAGE/SD/SDOM OF THE Y-DATA
if average != False:
avg = np.sum(ydata[t0:])/len(ydata[t0:])
SD = stdev(ydata[t0:])
SDOM = SD/sqrt(len(ydata[t0:]))
plt.axhline(avg, xmin=0.0, xmax=1.0, c='r')
plt.figtext(0.680, 0.780, '%s\n%6.4f $\\pm$ %6.4f %s \nSD = %4.3f %s' %(analysis, avg, SDOM, y_units, SD, y_units), bbox=dict(boxstyle='square', ec='r', fc='w'), fontsize=12)
plt.savefig('%s.%s.plot1d.png' %(system,analysis),dpi=300)
plt.close()
示例5: plot_profile
def plot_profile(frame, index):
T = sc[:,'w_xy'].keys()[frame]
data = sc[T,'w_xy'][index,:]
x = sc[0.0,'z_z'][-sc[T,'w_xy'].shape[0]:]
plt.imshow(sc[T,'w_xy'])
plt.axhline(index, color='k')
plt.figure()
plt.plot(x,data[:])
plt.xlabel("y")
plt.ylabel("w")
plt.figure()
scalex = np.sqrt(np.abs(data[1]/x[1]) * p['viscosity']) / p['viscosity']
scaley = 1./np.sqrt(np.abs(data[1]/x[1]) * p['viscosity'])
plt.plot(scalex*x[:50],scaley*data[:50], 'x-')
plt.grid(True)
plt.xlabel("y+")
plt.ylabel("w+")
plt.figure()
scalex = np.sqrt(np.abs(data[-1]/(x[-1]-1)) * p['viscosity']) / p['viscosity']
scaley = 1./np.sqrt(np.abs(data[-1]/(x[-1]-1)) * p['viscosity'])
plt.plot(scalex*(x[-50:]-1),scaley*data[-50:], 'x-')
plt.grid(True)
plt.xlabel("y+")
plt.ylabel("w+")
示例6: getMonthlyReturns
def getMonthlyReturns(self, lotSizeInUSD, commissionPerPip):
prevMonth = 0
profit = 0
deals = 0
monthlyReturns = []
for p in self.getClosedPositions():
if prevMonth == 0:
prevMonth = p.openTime.month
profit += (p.closePrice - p.order.price) * p.order.orderType * lotSizeInUSD - commissionPerPip
deals += 1
if p.openTime.month != prevMonth:
monthlyReturns.append([profit, deals])
prevMonth = p.openTime.month
profit = 0
deals = 0
result = np.array(monthlyReturns)
import matplotlib.pyplot as plt
plt.figure(1)
plt.subplot(211)
plt.axhline(y=0)
plt.plot(result[:,0])
plt.subplot(212)
plt.axhline(y=0)
plt.plot(result[:,1])
plt.show()
return result
示例7: test_blc2
def test_blc2(oversample=2, verbose=True, wavelength=2e-6, angle=0, kind='circular', sigma=1.0, loc = 0.3998):
import scipy
x = np.linspace(-5, 5, 401)
sigmar = sigma*x
if kind == 'circular':
trans = (1- (2*scipy.special.jn(1,sigmar)/sigmar)**2)**2
else:
trans = (1- (np.sin(sigmar)/sigmar)**2)**2
plt.clf()
plt.plot(x, trans)
plt.axhline(0.5, ls='--', color='k')
plt.axvline(loc, ls='--', color='k')
#plt.gca().set_xbound(loc*0.98, loc*1.02)
wg = np.where(sigmar > 0.01)
intfn = scipy.interpolate.interp1d(x[wg], trans[wg])
print "Value at %.4f :\t%.4f" % (loc, intfn(loc))
# figure out the FWHM
# cut out the portion of the curve from the origin to the first positive maximum
wp = np.where(x > 0)
xp = x[wp]
transp = trans[wp]
wm = np.argmax(transp)
wg = np.where(( x>0 )& ( x<xp[wm]))
interp = scipy.interpolate.interp1d(trans[wg], x[wg])
print "For sigma = %.4f, HWHM occurs at %.4f" % (sigma, interp(0.5))
示例8: wfplot2
def wfplot2(wflist,bounds):
# improved ploting, it can plot more than one wavefunction, also it can change the plot range,
# if the bounds parameter is -1 it plots the wavefunctions in their full range. It also shows the axis x line.
# usage: wfplot2([ynL],[0,10]) (NOTE THE BRAKETS) to plot ynL in the interval (0,10) or wfplot2([ynL],-1) to plot ynL in its full range, or
# wfplot2([ynL,ynL2],-1) to plot two functions in te full range.
if bounds == -1:
plt.axhline(0,color='black')
for element in wflist:
wfplot(element)
return plt.show()
elif len(bounds) == 2:
plt.axhline(0,color='black')
for element in wflist:
xmin = min(simm(bounds[0],element[:,0]))
xmax = max(simm(bounds[1],element[:,0]))
xaux = element[:,0][xmin:xmax]
yaux = element[:,1][xmin:xmax]
plt.plot(np.array(xaux),np.array(yaux))
return plt.show()
else:
print 'invalid bounds'
示例9: _sp
def _sp(data):
"""
Generate plots of convergence criteria, and energy vs. optimization cycles
:job: ccdata object, or file
:returns: TODO
"""
# TODO scfenergies, scfvalues, scftargets vs. scf cycles
print("\n\n")
#print("Optimization Converged: ", data.optdone)
criteria = [0, 0, 0]
criteria[0] = [x[0] for x in data.scfvalues]
criteria[1] = [x[1] for x in data.scfvalues]
criteria[2] = [x[2] for x in data.scfvalues]
idx = np.arange(len(criteria[0]))
# Plot Geometry Optimization Criteria for Convergence over opt cycles
plt.plot(idx, criteria[0], label='Criteria 1')
plt.plot(idx, criteria[1], label='Criteria 2')
plt.plot(idx, criteria[2], label='Criteria 3')
# Plot target criteria for convergence
plt.axhline(y=data.scftargets[0])
plt.yscale('log')
plt.title("SCF Convergence Analysis")
plt.xlabel("SCF Cycle")
plt.legend()
print(idx, criteria, data.scftargets)
plt.show()
示例10: analyze_edge_velocities
def analyze_edge_velocities(df):
from numpy import arange
import article2_time_averaged_routines as tar
import pandas as pd
import matplotlib.pyplot as plt
reload(tar)
# This function was once used to evaluate the selection of
# U_e based on different parameters
conditions = [
'vorticity_integration_rate_of_change',
#'u_rms_rate_of_change',
#'v_rms_rate_of_change',
#'u_rate_of_change',
]
thresholds = arange(1,100,0.1)[::-1]
U_e_df = pd.DataFrame()
for c in conditions:
U_e = []
for t in thresholds:
U_e.append(tar.get_edge_velocity(df, condition = c, threshold = t))
U_e_df[c] = U_e
U_e_df.plot()
plt.axhline( df.u.max() )
plt.show()
return U_e_df
示例11: plot_adsorbed_circles
def plot_adsorbed_circles(adsorbed_x, adsorbed_y, radius, width, reference_indices=[]):
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
# Plot each run
fig = plt.figure()
ax = fig.add_subplot(111)
for p in range(len(adsorbed_x)):
if len(np.where(reference_indices == p)[0]) > 0:
ax.add_patch(Circle((adsorbed_x[p], adsorbed_y[p]), radius,
edgecolor='black', facecolor='black'))
else:
ax.add_patch(Circle((adsorbed_x[p], adsorbed_y[p]), radius,
edgecolor='black', facecolor='white'))
ax.set_aspect(1.0)
plt.axhline(y=0, color='k')
plt.axhline(y=width, color='k')
plt.axvline(x=0, color='k')
plt.axvline(x=width, color='k')
plt.axis([-0.1*width, width*1.1, -0.1*width, width*1.1])
plt.xlabel("non-dimensional x")
plt.ylabel("non-dimensional y")
return ax
示例12: _double_hit_check
def _double_hit_check(x):
# first PSD
W, fr = PSD(x, dt=dt)
# second PSD: look for oscillations in PSD
W2, fr2 = PSD(W, dt=fr[1])
upto = int(0.01 * len(x))
max_impact = np.max(W2[:upto])
max_after_impact = np.max(W2[upto:])
if plot_figure:
import matplotlib.pyplot as plt
plt.subplot(121)
l = int(0.002*len(x))
plt.plot(1000*dt*np.arange(l), x[:l])
plt.xlabel('t [ms]')
plt.ylabel('F [N]')
plt.subplot(122)
plt.semilogy((W2/np.max(W2))[:5*upto])
plt.axhline(limit, color='r')
plt.axvline(upto, color='g')
plt.xlabel('Double freq')
plt.ylabel('')
plt.show()
if max_after_impact / max_impact > limit:
return True
else:
return False
示例13: adjust_axes
def adjust_axes(ax, title, header_ticks, header_list, axis_num, cols, axesfontsize):
'''
A small helper function that adjusts the axes on the plots
'''
frame = plt.gca()
axes_font = {'fontsize':axesfontsize}
title_font = {'fontsize':18}
plt.text(0.1,3, title, **title_font)
plt.axhline()
if (axis_num <= cols) and (axis_num % 2 == 0):
frame.xaxis.set_ticks_position('top')
frame.xaxis.set_label_position('top')
frame.xaxis.tick_top()
ax.set_xticks(header_ticks)
ax.set_xticklabels(header_list, **axes_font)
else:
frame.axes.get_xaxis().set_visible(False)
if (((axis_num - 1) / cols) % 2 == 0) and axis_num % cols == 1:
ax.set_yticks((-4,-2,0,2,4))
ax.set_yticklabels([-4,-2,0,2,4], **axes_font)
else:
frame.axes.get_yaxis().set_visible(False)
示例14: display_w
def display_w(w, s, r, c, fig, vmax=None, vmin=None, dataset='mnist', title='weights'):
if dataset == 'norb':
numvis = 4096
else:
numvis = w.shape[0]
numhid = w.shape[1]
sc = s
sr = numvis/s
if isinstance(w, np.ndarray):
vh = w.T[:,:sr*sc].reshape(sr*numhid, sc)
else:
vh = w.asarray().T[:,:sr*sc].reshape(sr*numhid, sc)
pvh = np.zeros((sr*r, sc*c))
for i in range(r):
for j in range(c):
pvh[i*sr:(i+1)*sr , j*sc:(j+1)*sc] = vh[ (i*c+j)*sr : (i*c+j+1)*sr ,:]
plt.figure(fig)
plt.clf()
plt.title(title)
plt.imshow(pvh, cmap = plt.cm.gray, interpolation = 'nearest', vmax=vmax, vmin=vmin)
scale = 1
xmax = sc*c
ymax = sr*r
color = 'k'
if r > 1:
for x in range(0,c):
plt.axvline(x=x*sc/scale, ymin=0,ymax=ymax/scale, color = color)
if c > 1:
for y in range(0,r):
plt.axhline(y=y*sr/scale, xmin=0,xmax=xmax/scale, color = color)
plt.draw()
return pvh
示例15: hpd_beta
def hpd_beta(y, n, h=.1, a=1, b=1, plot=False, **plot_kwds):
apost = y + a
bpost = n - y + b
if apost > 1 and bpost > 1:
mode = (apost - 1)/(apost + bpost - 2)
else:
raise Exception("mode at 0 or 1: HPD not implemented yet")
post = stats.beta(apost, bpost)
dmode = post.pdf(mode)
lt = opt.bisect(lambda x: post.pdf(x) / dmode - h, 0, mode)
ut = opt.bisect(lambda x: post.pdf(x) / dmode - h, mode, 1)
coverage = post.cdf(ut) - post.cdf(lt)
if plot:
plt.figure()
plotf(post.pdf)
plt.axhline(h*dmode)
plt.plot([ut, ut], [0, post.pdf(ut)])
plt.plot([lt, lt], [0, post.pdf(lt)])
plt.title(r'$p(%s < \theta < %s | y)$' %
tuple(np.around([lt, ut], 2)))
return lt, ut, coverage, h