本文整理汇总了Python中matplotlib.pyplot.axvline函数的典型用法代码示例。如果您正苦于以下问题:Python axvline函数的具体用法?Python axvline怎么用?Python axvline使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了axvline函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: plot_scatter
def plot_scatter(points, rects, level_id, fig_area=FIG_AREA, grid_area=GRID_AREA, with_axis=False, with_img=True, img_alpha=1.0):
rect = rects[level_id]
top_lat, top_lng, bot_lat, bot_lng = get_rect_bounds(rect)
plevel = get_points_level(points, rects, level_id)
ax = plevel.plot('lng', 'lat', 'scatter')
plt.xlim(left=top_lng, right=bot_lng)
plt.ylim(top=top_lat, bottom=bot_lat)
if with_img:
img = plt.imread('/data/images/level%s.png' % level_id)
plt.imshow(img, zorder=0, alpha=img_alpha, extent=[top_lng, bot_lng, bot_lat, top_lat])
width, height = get_rect_width_height(rect)
fig_width, fig_height = get_fig_width_height(width, height, fig_area)
plt.gcf().set_size_inches(fig_width, fig_height)
if grid_area:
grid_horiz, grid_vertic = get_grids(rects, level_id, grid_area, fig_area)
for lat in grid_horiz:
plt.axhline(lat, color=COLOR_GRID, lw=GRID_LW)
for lng in grid_vertic:
plt.axvline(lng, color=COLOR_GRID, lw=GRID_LW)
if not with_axis:
ax.set_axis_off()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
return ax
示例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: draw_img_for_viewing_ice
def draw_img_for_viewing_ice(self):
#print "Press 'p' to save PNG."
global colmax
global colmin
fig = P.figure(num=None, figsize=(13.5, 5), dpi=100, facecolor='w', edgecolor='k')
cid1 = fig.canvas.mpl_connect('key_press_event', self.on_keypress_for_viewing)
cid2 = fig.canvas.mpl_connect('button_press_event', self.on_click)
canvas = fig.add_subplot(121)
canvas.set_title(self.filename)
self.axes = P.imshow(self.inarr, origin='lower', vmax = colmax, vmin = colmin)
self.colbar = P.colorbar(self.axes, pad=0.01)
self.orglims = self.axes.get_clim()
canvas = fig.add_subplot(122)
canvas.set_title("Angular Average")
maxAngAvg = (self.inangavg).max()
numQLabels = len(eDD.iceHInvAngQ.keys())+1
labelPosition = maxAngAvg/numQLabels
for i,j in eDD.iceHInvAngQ.iteritems():
P.axvline(j,0,colmax,color='r')
P.text(j,labelPosition,str(i), rotation="45")
labelPosition += maxAngAvg/numQLabels
P.plot(self.inangavgQ, self.inangavg)
P.xlabel("Q (A-1)")
P.ylabel("I(Q) (ADU/srad)")
pngtag = original_dir + "peakfit-gdvn_%s.png" % (self.filename)
P.savefig(pngtag)
print "%s saved." % (pngtag)
P.close()
示例4: mcgehee
def mcgehee():
st = TransferMatrix()
st.add_layer(0, 1.4504)
st.add_layer(110, 1.7704 + 0.01161j)
st.add_layer(35, 1.4621 + 0.04426j)
st.add_layer(220, 2.12 + 0.3166016j)
st.add_layer(7, 2.095 + 2.3357j)
st.add_layer(200, 1.20252 + 7.25439j)
st.add_layer(0, 1.20252 + 7.25439j)
st.set_vacuum_wavelength(600)
st.set_polarization('s')
st.set_field('E')
st.set_incident_angle(0, units='degrees')
st.info()
# Do calculations
result = st.calc_field_structure()
z = result['z']
y = result['field_squared']
# Plot results
plt.figure()
plt.plot(z, y)
for z in st.get_layer_boundaries()[:-1]:
plt.axvline(x=z, color='k', lw=2)
plt.xlabel('Position in Device (nm)')
plt.ylabel('Normalized |E|$^2$ Intensity ($|E(z)/E_0(0)|^2$)')
if SAVE:
plt.savefig('../Images/McGehee structure.png', dpi=300)
plt.show()
示例5: plot_monthly_dollars_by_party
def plot_monthly_dollars_by_party(party, color='blue', start_date=None, end_date=None, election_date=None):
monthly_dollars = monthly_dollars_by_party(party, start_date, end_date)
months, dollars = monthly_dollars.keys(), monthly_dollars.values()
plt.plot(range(len(months)), dollars, 'o-', color=color, label=party)
# label every other month
xtick_locs = range(0, len(months), 2)
xtick_labels = [d.strftime('%B %Y') for d in months[::2]]
plt.xticks(xtick_locs, xtick_labels, rotation=70)
# format for dollars
a = plt.gca()
a.get_yaxis().set_major_formatter(matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))
# show election day
if election_date:
first_date = months[0]
date_diff = election_date - first_date
months_diff = date_diff.days / 30.0
plt.axvline(months_diff, color='black', ls='dashed', label='Election Day')
plt.xlim((0, len(months)-1))
plt.ylabel('Total Monthly Contributions ($)')
plt.title('Total Monthly Contributions')
plt.legend(loc='upper right')
示例6: t90_dist
def t90_dist(self):
""" Plots T90 distribution, gives the mean and median T90 values of the
sample and calculates the number of short, long bursts in the sample """
t90s = []
for i in range(0,len(self.t90s),1):
try:
t90s.append(float(self.t90s[i]))
except ValueError:
continue
t90s = np.array(t90s)
mean_t90 = np.mean(t90s)
median_t90 = np.median(t90s)
print('Mean T90 time =',mean_t90,'s')
print('Median T90 time=',median_t90,'s')
mask = np.ma.masked_where(t90s < 2, t90s)
short_t90s = t90s[mask == False]
long_t90s = t90s[mask != False]
print('Number of Short/Long GRBs =',len(short_t90s),'/',len(long_t90s))
plt.figure()
plt.xlabel('T$_{90}$ (s)')
plt.ylabel('Number of GRBs')
plt.xscale('log')
minimum, maximum, = min(short_t90s), max(long_t90s)
plt.axvline(mean_t90,color='red',linestyle='-')
plt.axvline(median_t90,color='blue',linestyle='-')
plt.hist(t90s,bins= 10**np.linspace(np.log10(minimum),np.log10(maximum),20),color='grey',alpha=0.5)
plt.show()
示例7: bFctV0
def bFctV0(n1, n2, rho, b, V0, modes, delta):
NA = sqrt(n1**2 - n2**2)
pyplot.figure()
sim = Simulator(delta=delta)
sim.setWavelength(Wavelength(k0=(v0 / b / NA)) for v0 in V0)
sim.setMaterials(Fixed, Fixed, Fixed)
sim.setRadii((rho * b,), (b,))
sim.setMaterialsParams((n2,), (n1,), (n2,))
fiber = fixedFiber(0, [rho * b, b], [n2, n1, n2])
for m in modes:
neff = sim.getNeff(m)
bnorm = (neff - n2) / (n1 - n2)
pyplot.plot(V0, bnorm, color=COLORS[m.family], label=str(m))
c = fiber.cutoffV0(m)
pyplot.axvline(c, color=COLORS[m.family], ls='--')
pyplot.xlim((0, V0[-1]))
pyplot.title("$n_1 = {}, n_2 = {}, \\rho = {}$".format(n1, n2, rho))
pyplot.xlabel("Normalized frequency ($V_0$)")
pyplot.ylabel("Normalized propagation constant ($\widetilde{\\beta}$)")
示例8: createHistogram
def createHistogram(df, pic, bins=45, rates=False):
data=mergeMatrix(df, pic)
matrix=sortMatrix(df, pic)
density = gaussian_kde(data)
xs = np.linspace(min(data), max(data), max(data))
density.covariance_factor = lambda : .25
density._compute_covariance()
#xs = np.linspace(min(data), max(data), 1000)
fig,ax1 = plt.subplots()
#plt.xlim([0, 4000])
plt.hist(data, bins=bins, range=[-500, 4000], histtype='stepfilled', color='grey', alpha=0.5)
lims = plt.ylim()
height=lims[1]-2
for i in range(0,len(matrix)):
currentRow = matrix[i][np.nonzero(matrix[i])]
plt.plot(currentRow, np.ones(len(currentRow))*height, '|', color='black')
height -= 2
plt.axvline(x=0, color='red', linestyle='dashed')
#plt.axvline(x=1000, color='black', linestyle='dashed')
#plt.axvline(x=2000, color='black', linestyle='dashed')
#plt.axvline(x=3000, color='black', linestyle='dashed')
if rates:
rates = get_rate(df, pic)
ax1.text(-250, 4, str(rates[0]), size=15, ha='center', va='center', color='green')
ax1.text(500, 4, str(rates[1]), size=15, ha='center', va='center', color='green')
ax1.text(1500, 4, str(rates[2]), size=15, ha='center', va='center', color='green')
ax1.text(2500, 4, str(rates[3]), size=15, ha='center', va='center', color='green')
ax1.text(3500, 4, str(rates[4])+ r' $\frac{\mathsf{Spikes}}{\mathsf{s}}$', size=15, ha='center', va='center', color='green')
plt.ylim([0,lims[1]+5])
plt.xlim([0, 4000])
plt.title('Histogram for ' + str(pic))
ax1.set_xticklabels([-500, 'Start\nStimulus', 500, 1000, 1500, 2000, 2500, 3000, 3500, 4000])
plt.xlabel('Time (ms)')
plt.ylabel('Counts (Spikes)')
print lims
arr_hand = getPic(pic)
imagebox = OffsetImage(arr_hand, zoom=.3)
xy = [3200, lims[1]+5] # coordinates to position this image
ab = AnnotationBbox(imagebox, xy, xybox=(30., -30.), xycoords='data',boxcoords="offset points")
ax1.add_artist(ab)
ax2 = ax1.twinx() #Necessary for multiple y-axes
#Use ax2.plot to draw the hypnogram. Be sure your x values are in seconds
ax2.plot(xs, density(xs) , 'g', drawstyle='steps')
plt.ylim([0,0.001])
plt.yticks([0.0001,0.0002, 0.0003, 0.0004, 0.0005, 0.0006, 0.0007, 0.0008, 0.0009])
ax2.set_yticklabels([1,2,3,4, 5, 6, 7, 8, 9])
plt.ylabel(r'Density ($\cdot \mathsf{10^{-4}}$)', color='green')
plt.gcf().subplots_adjust(right=0.89)
plt.gcf().subplots_adjust(bottom=0.2)
plt.savefig(pic, dpi=150)
示例9: test_airy_2d
def test_airy_2d(display=False):
""" Test 2D airy function vs 1D function; both
should yield the exact same results for a 1D cut across the 2d function.
And we've already tested the 1D above...
"""
fn2d = airy_2d(diameter=1.0, wavelength=1e-6, shape=(511, 511), pixelscale=0.010)
r, fn1d = airy_1d(diameter=1.0, wavelength=1e-6, length=256, pixelscale=0.010)
cut = fn2d[255, 255:].flatten()
print(cut.shape)
if display:
plt.subplot(211)
plt.semilogy(r, fn1d, label='1D')
plt.semilogy(r, cut, label='2D', color='black', ls='--')
plt.legend(loc='upper right')
plt.axvline(0.251643, color='red', ls='--')
plt.ylabel('Intensity relative to peak')
plt.xlabel('Separation in $\lambda/D$')
ax=plt.subplot(212)
plt.plot(r, cut-fn1d)
ax.set_ylim(-1e-8, 1e-8)
plt.ylabel('Difference')
plt.xlabel('Separation in $\lambda/D$')
#print fn1d[0], cut[0]
#print np.abs(fn1d-cut) #< 1e-9
assert np.all( np.abs(fn1d-cut) < 1e-9)
示例10: guiding_electric_field
def guiding_electric_field():
# Create structure
st = TransferMatrix()
st.set_vacuum_wavelength(lam0)
st.add_layer(1.5 * lam0, air)
st.add_layer(lam0, si)
st.add_layer(1.5 * lam0, air)
st.info()
st.set_polarization('TM')
st.set_field('H')
st.set_leaky_or_guiding('guiding')
alpha = st.calc_guided_modes(normalised=True)
plt.figure()
for i, a in enumerate(alpha):
st.set_guided_mode(a)
result = st.calc_field_structure()
z = result['z']
# z = st.calc_z_to_lambda(z)
E = result['field']
# Normalise fields
# E /= max(E)
plt.plot(z, abs(E) ** 2, label=i)
for z in st.get_layer_boundaries()[:-1]:
# z = st.calc_z_to_lambda(z)
plt.axvline(x=z, color='k', lw=1, ls='--')
plt.legend(title='Mode index')
if SAVE:
plt.savefig('../Images/guided fields.png', dpi=300)
plt.show()
示例11: test
def test():
# Create structure
st = LifetimeTmm()
st.set_vacuum_wavelength(lam0)
# st.add_layer(1e3, si)
st.add_layer(1900, sio2)
st.add_layer(100, si)
st.add_layer(20, sio2)
st.add_layer(100, si)
# st.add_layer(1900, sio2)
st.add_layer(1e3, air)
st.info()
st.set_polarization('TM')
st.set_field('H')
st.set_leaky_or_guiding('guiding')
alpha = st.calc_guided_modes(normalised=True)
st.set_guided_mode(alpha[0])
result = st.calc_field_structure()
z = result['z']
z = st.calc_z_to_lambda(z)
E = result['field']
# Normalise fields
# E /= max(E)
plt.figure()
plt.plot(z, abs(E) ** 2)
for z in st.get_layer_boundaries()[:-1]:
z = st.calc_z_to_lambda(z)
plt.axvline(x=z, color='k', lw=1, ls='--')
plt.show()
示例12: psplot
def psplot(pslist, nbins = 0, filename=None, figsize=(12, 8), showlegend=True):
"""
Plots a list of PS objects.
If the PS has a slope, it is plotted as well.
if nbins > 0, I bin the spectra.
add option for linear plot ?
"""
plt.figure(figsize=figsize)
for ps in pslist:
if not np.all(np.isfinite(np.log10(ps.p))):
print "No power to plot (probably flat curve !), skipping this one."
continue
# We bin the points
if nbins > 0:
logf = np.log10(ps.f[1:]) # we remove the first one
logbins = np.linspace(np.min(logf), np.max(logf), nbins+1) # So nbins +1 numbers here.
bins = 10**logbins
bincenters = 0.5*(bins[:-1] + bins[1:]) # nbins centers
logbins[0] -= 1.0
logbins[-1] += 1.0
binindexes = np.digitize(logf, logbins) # binindexes go from 1 to nbins+1
binvals = []
binstds = []
for i in range(1, nbins+1):
vals = ps.p[1:][binindexes == i]
binvals.append(np.mean(vals))
binstds.append(np.std(vals)/np.sqrt(vals.size))
bincenters = np.array(bincenters)
binvals = np.array(binvals)
binstds = np.array(binstds)
plt.loglog(bincenters, binvals, marker=".", linestyle="-", color=ps.plotcolour, label = "%s" % (ps))
else:
plt.loglog(ps.f, ps.p, marker=".", linestyle="None", color=ps.plotcolour, label = "%s" % (ps))
if ps.slope != None:
plt.loglog(ps.slope["f"], ps.slope["p"], marker="None", color=ps.plotcolour, label = "Slope %s = %.3f" % (ps, ps.slope["slope"]))
plt.axvline(ps.slope["fmin"], color = ps.plotcolour, dashes = (5,5))
plt.axvline(ps.slope["fmax"], color = ps.plotcolour, dashes = (5,5))
plt.xlabel("Frequency [1/days]")
plt.ylabel("Power")
if showlegend:
plt.legend()
#plt.text(np.min(10**fitx), np.max(10**pfit), "Log slope : %.2f" % (popt[0]), color="red")
if filename:
plt.save(filename)
else:
plt.show()
示例13: multi_plot_grid
def multi_plot_grid(sig, num = 4, path = None, changes = None):
"""
Plot in a grid structure.
If path "/.../Plot.png" is provided then output plot will be saved into the file.
If the list changes is provided thet vertical red lines will be plotted to mark locations.
"""
n =len(sig)
md = n % num
wdth = n / num
for i in range(1, num+1):
plt.subplot(num/2, num/2, i)
plt.plot(sig)
if changes != None:
for j,e in enumerate(changes):
plt.axvline(x = e, color = "red")
if i == num:
plt.xlim((i-1)*wdth, i * wdth + md)
else:
plt.xlim((i-1)*wdth, i * wdth)
plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))
if path:
plt.savefig(path, dpi = 700)
print "Figure is saved into " + path
else:
plt.show()
示例14: TCP_plot
def TCP_plot(no_ind_plots, label):
#no_ind_plots = 50
## individual plots cannot be more than total patients
if(no_ind_plots>n):
no_ind_plots=n
## want to select the individual plots randomly from those calcualted...
ind_plots = np.random.choice(len(TCPs),no_ind_plots, replace=False)
## individuals (specified number of plots chosen)
for i in ind_plots:
plt.plot(nom_doses,TCPs[i], color = 'grey', alpha = 0.5)
## population
plt.plot(nom_doses,TCP_pop, color='black', linewidth='2', alpha=0.5)
plt.plot(nom_doses,TCP_pop, marker = 'o', ls='none', label=label)
## plot formatting
plt.xlim(0,max(nom_doses))
plt.ylim(0,1.0)
plt.xlabel('Dose (Gy)')
plt.ylabel('TCP')
plt.title('TCPs')
#plt.legend(loc = 'best', fontsize = 'medium', framealpha = 1)
plt.axvline(d_interest, color = 'black', ls='--',)
plt.axhline(TCP_pop[frac_interest-1], color='black', ls='--')
## add labels with TCP at dose of interest
text_string = ('Pop. TCP = ' + str(round(TCP_cure_at_d_interest,2)) + ' % at ' + str(d_interest) + 'Gy')
plt.text(5,0.4,text_string, backgroundcolor='white')
plt.legend(loc = 'lower left',numpoints=1)
plt.show()
开发者ID:mbolt01,项目名称:InitialCode,代码行数:33,代码来源:TCP-updated-multiple-parameter-variations-Re-order-AddOPTrend.py
示例15: make_scatter
def make_scatter(n, ratings):
"""Makes a scatter plot of n vs ratings
"""
# File name
vline = "_cutoff-%s" % args.n if args.n else ""
log = "_log" if args.log else ""
outfile = args.outbase + "_scatter_n-vs-rating%s%s.pdf" % \
(vline, log)
fig, ax = plt.subplots()
ax.scatter(n, jitter(ratings), color="#e34a33", alpha=0.3)
if args.log:
ax.set_xscale("log")
ax.set_xlim([0,np.max(n)])
ax.set_ylim([0,5.5])
ax.set_xlabel("Number of reviews (n)")
ax.set_ylabel("Average rating (stars)")
if args.n: # vline if specified
plt.axvline(args.n, color="black", linestyle="--")
ax.text(args.n + 50, 0.5, "cutoff", fontweight="bold")
fig.savefig(outfile)
print "Scatter plot made at \n%s" % outfile
return