本文整理汇总了Python中matplotlib.pylab.axis函数的典型用法代码示例。如果您正苦于以下问题:Python axis函数的具体用法?Python axis怎么用?Python axis使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了axis函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main_k_nearest_neighbour
def main_k_nearest_neighbour(k):
X, y = make_blobs(n_samples=100,
n_features=2,
centers=2,
cluster_std=1.0,
center_box=(-10.0, 10.0))
h = .4
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
z = np.c_[xx.ravel(), yy.ravel()]
z_f = []
for i_z in z:
z_f.append(k_nearest_neighbour(X, y, i_z, k, False))
zz = np.array(z_f).reshape(xx.shape)
plt.figure()
plt.contourf(xx, yy, zz, cmap=plt.cm.Paired)
plt.axis('tight')
plt.scatter(X[:, 0], X[:, 1], c=y)
plt.show()
示例2: ZipByDemoCuisine
def ZipByDemoCuisine(askNum ,Zipcodes, recorddict):
for zips in Zipcodes:
if askNum == zips.Zip:
print "This is located in " + str(zips.Hood) + "!"
labels = ['White', 'Black', 'AI', 'Asian', 'NH/PI', 'Other', 'Multiple', 'Hispanic']
sizes = [zips.White, zips.Black, zips.AI_AN, zips.Asian, zips.NHOPI, zips.OthRace, zips.MultRaces, zips.Hispanic]
colors = ['red', 'orange', 'yellow', 'green', 'lightskyblue', 'darkblue','pink', 'purple' ]
explode = (0, 0, 0, 0, 0, 0, 0, 0)
plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=False, startangle=140)
plt.axis('equal')
plt.show()
xlist = []
ylist = []
x = Counter(recorddict[askNum])
for i in x.most_common(10):
xlist.append(i[0])
ylist.append(int(i[1]))
#i[0] = category
#i[1] = number of category
labels = xlist
sizes = ylist
colors = ['red', 'orange', 'yellow', 'green', 'lightskyblue', 'darkblue', 'pink', 'white', 'silver', 'purple']
explode = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=False, startangle=140)
plt.axis('equal')
plt.show()
示例3: __call__
def __call__(self, **params):
p = ParamOverrides(self, params)
fig = plt.figure(figsize=(5, 5))
# This one-liner works in Octave, but in matplotlib it
# results in lines that are all connected across rows and columns,
# so here we plot each line separately:
# plt.plot(x,y,"k-",transpose(x),transpose(y),"k-")
# Here, the "k-" means plot in black using solid lines;
# see matplotlib for more info.
isint = plt.isinteractive() # Temporarily make non-interactive for
# plotting
plt.ioff()
for r, c in zip(p.y[::p.skip], p.x[::p.skip]):
plt.plot(c, r, "k-")
for r, c in zip(np.transpose(p.y)[::p.skip],np.transpose(p.x)[::p.skip]):
plt.plot(c, r, "k-")
# Force last line avoid leaving cells open
if p.skip != 1:
plt.plot(p.x[-1], p.y[-1], "k-")
plt.plot(np.transpose(p.x)[-1], np.transpose(p.y)[-1], "k-")
plt.xlabel('x')
plt.ylabel('y')
# Currently sets the input range arbitrarily; should presumably figure out
# what the actual possible range is for this simulation (which would presumably
# be the maximum size of any GeneratorSheet?).
plt.axis(p.axis)
if isint: plt.ion()
self._generate_figure(p)
return fig
示例4: part2
def part2(w):
f = plt.figure()
for i in range(16):
f.add_subplot(4,4,i+1)
plt.axis('off')
plt.imshow(np.reshape(normalize(w[1:,i]), (20,20)), cmap = matplotlib.cm.Greys_r)
plt.savefig('3.png')
示例5: experiment_plot
def experiment_plot( ctr, trials, success ):
"""
Pass in the ctr, trials and success returned
by the `experiment` function and plot
the Cumulative Number of Turns For Each Arm and
the CTR's Convergence Plot side by side
"""
T, K = trials.shape
n = np.arange(T) + 1
fig = plt.figure( figsize = ( 14, 7 ) )
plt.subplot(121)
for i in range(K):
plt.loglog( n, trials[ :, i ], label = "arm {}".format(i + 1) )
plt.legend( loc = "upper left" )
plt.xlabel("Number of turns")
plt.ylabel("Number of turns/arm")
plt.title("Cumulative Number of Turns For Each Arm")
plt.subplot(122)
for i in range(K):
plt.semilogx( n, np.zeros(T) + ctr[i], label = "arm {}'s CTR".format( i + 1 ) )
plt.semilogx( n, ( success[ :, 0 ] + success[ :, 1 ] ) / n, label = "CTR at turn t" )
plt.axis([ 0, T, 0, 1 ] )
plt.legend( loc = "upper left" )
plt.xlabel("Number of turns")
plt.ylabel("CTR")
plt.title("CTR's Convergence Plot")
return fig
示例6: plot
def plot(self, isec=None, ifig=1, coordsys='rotor'):
import matplotlib.pylab as plt
if coordsys == 'rotor':
afs = self.afsorg
elif coordsys == 'mold':
afs = self.afs
plt.figure(ifig)
if isec is not None:
ni = [isec]
else:
ni = range(self.ni)
for i in ni:
plt.title('r = %3.3f' % (self.z[i]))
af = afs[i]
plt.plot(af.points[:, 0], af.points[:, 1], 'b-')
DP = np.array([af.interp_s(af.s_to_01(s)) for s in self.DPs[i, :]])
width = np.diff(self.DPs[i, :])
valid = np.ones(DP.shape[0])
valid[1:] = width > self.min_width
for d in DP:
plt.plot(d[0], d[1], 'ro')
for d in DP[self.cap_DPs, :]:
plt.plot(d[0], d[1], 'mo')
for web_ix in self.web_def:
if valid[web_ix].all():
plt.plot(DP[[web_ix[0], web_ix[1]]][:, 0],
DP[[web_ix[0], web_ix[1]]][:, 1], 'g')
plt.axis('equal')
示例7: compareAnimals
def compareAnimals(animals, precision):
'''
:param animals:动物列表
:param (int) precision: 精度
:return : 表格,包含任意两个动物之间的欧式距离
'''
columnLabels = []
for a in animals:
columnLabels.append(a.getName())
rowLabels = columnLabels[:]
tableVals = []
#循环计算任意两个动物间的欧氏距离
for a1 in animals:
row =[]
for a2 in animals:
if a1 == a2:
row.append('--')
else:
distance = a1.distance(a2)
row.append(str(round(distance, precision)))
tableVals.append(row)
#生成表格
table = plt.table(rowLabels=rowLabels,
colLabels=columnLabels,
cellText=tableVals,
cellLoc='center',
loc='center',
colWidths=[0.2]*len(animals))
table.scale(1, 2.5)
plt.axis('off')
plt.savefig('chapter19_1.png', dpi=100)
plt.show()
示例8: scatter
def scatter(title, file_name, x_array, y_array, size_array, x_label, \
y_label, x_range, y_range, print_pdf):
'''
Plots the given x value array and y value array with the specified
title and saves with the specified file name. The size of points on
the map are proportional to the values given in size_array. If
print_pdf value is 1, the image is also written to pdf file.
Otherwise it is only written to png file.
'''
rc('text', usetex=True)
rc('font', family='serif')
plt.clf() # clear the ploting window, a must.
plt.scatter(x_array, y_array, s = size_array, c = 'b', marker = 'o', alpha = 0.4)
if x_label != None:
plt.xlabel(x_label)
if y_label != None:
plt.ylabel(y_label)
plt.axis ([0, x_range, 0, y_range])
plt.grid(True)
plt.suptitle(title)
Plotter.print_to_png(plt, file_name)
if print_pdf:
Plotter.print_to_pdf(plt, file_name)
示例9: parametric_plot
def parametric_plot(func):
"""
Plot the example curves
"""
MAXX = 100.0
x = np.linspace(0, MAXX, 1000)
pylab.figure()
for mu in np.linspace(0, 100, 8):
lamb = 4.0
pylab.plot(x, func(x, mu, lamb), linewidth=3.0)
#pylab.axvline(mu, linestyle='--')
pylab.grid(1)
pylab.axis([0, MAXX, 0, 1])
pylab.figure()
for c, mu in [('r', 0.0), ('b', 50.0)]:
for lamb in np.array([0.1, 0.5, 1.0, 2.0, 4.0]): # 1.0, 4.0, 10.0, 20, 50]:
pylab.plot(x, func(x, mu, lamb), linewidth=3,
c=c)
#pylab.axvline(mu, linestyle='--')
pylab.grid(1)
pylab.axis([0, MAXX, 0, 1])
pylab.show()
示例10: generic_plot_sequence
def generic_plot_sequence(r, plotter, space, sequence,
axis0=None, annotation=None):
axis = plotter.axis_for_sequence(space, sequence)
if axis[0] == axis[1]:
dx = 1
# dy = 1
axis = (axis[0] - dx, axis[1] + dx, axis[2], axis[3])
axis = enlarge(axis, 0.15)
if axis0 is not None:
axis = join_axes(axis, axis0)
for i, x in enumerate(sequence):
caption = space.format(x)
caption = None
with r.plot('S%d' % i, caption=caption) as pylab:
plotter.plot(pylab, axis, space, x)
if annotation is not None:
annotation(pylab, axis)
xlabel, ylabel = plotter.get_xylabels(space)
try:
if xlabel:
pylab.xlabel(xlabel)
if ylabel:
pylab.ylabel(ylabel)
except UnicodeDecodeError as e:
print xlabel, xlabel.__repr__(), ylabel, ylabel.__repr__(), e
if (axis[0] != axis[1]) or (axis[2] != axis[3]):
pylab.axis(axis)
示例11: imshow_
def imshow_(x, **kwargs):
if x.ndim == 2:
plt.imshow(x, interpolation="nearest", **kwargs)
elif x.ndim == 1:
plt.imshow(x[:,None].T, interpolation="nearest", **kwargs)
plt.yticks([])
plt.axis("tight")
示例12: plot_fits
def plot_fits(direction_rates,fit_curve,title):
"""
This function takes the x-values and the y-values in units of spikes/s
(found in the two columns of direction_rates and fit_curve) and plots the
actual values with circles, and the curves as lines in both linear and
polar plots.
"""
curve_xs = np.arange(direction_rates[0,0], direction_rates[-1,0])
fit_ys2 = normal_fit(curve_xs,fit_curve[0],fit_curve[1],fit_curve[2])
plt.subplot(2,2,3)
plt.plot(direction_rates[:,0],direction_rates[:,1],'o',hold=True)
plt.plot(curve_xs,fit_ys2,'-')
plt.xlabel('Direction of Motions (Degrees)')
plt.ylabel('Firing Rates (Spikes/sec)')
plt.title(title)
plt.axis([0, 360, 0, 40])
plt.xticks(direction_rates[:,0])
fit_ys = normal_fit(direction_rates[:,0],fit_curve[0],fit_curve[1],fit_curve[2])
plt.subplot(2,2,4,polar=True)
spkiecount = np.append(direction_rates[:,1],direction_rates[0,1])
plt.polar(np.arange(0,361,45)*np.pi/180,spkiecount,'o',label='Firing Rate (spike/s)')
plt.hold(True)
spkiecount_y = np.append(fit_ys,fit_ys[0])
plt.plot(np.arange(0,361,45)*np.pi/180,spkiecount_y,'-')
plt.legend(loc=8)
plt.title(title)
fit_ys2 = np.transpose(np.vstack((curve_xs,fit_ys2)))
return(fit_ys2)
示例13: draw
def draw(self, description=None, ofile="test.png"):
plt.clf()
for f in self.funcs:
f()
plt.axis("off")
ax = plt.gca()
ax.set_aspect("equal", "datalim")
f = plt.gcf()
f.set_size_inches(12.8, 7.2)
if description is not None:
plt.text(0.025, 0.05, description, transform=f.transFigure)
if self.xlim is not None:
plt.xlim(*self.xlim)
if self.ylim is not None:
plt.ylim(*self.ylim)
plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0)
# dpi = 100 for 720p, 150 for 1080p
plt.savefig(ofile, dpi=150)
示例14: plot_p_leading_order
def plot_p_leading_order(frame):
mat = scipy.io.loadmat('sound-speed_2D-wave.mat')
T=5; nt=T/0.5
pp=mat['U'][nt,:,:]
xx=mat['xx']
yy=mat['yy']
fig=pl.figure(figsize=(8, 3.5))
#pl.title("t= "+str(sol.state.t),fontsize=20)
pl.xticks(size=20); pl.yticks(size=20)
pl.xlabel('x',fontsize=20); pl.ylabel('y',fontsize=20)
#pl.pcolormesh(xx,yy,p_subxy,cmap=cm.OrRd)
pl.pcolormesh(xx,yy,pp,cmap='RdBu_r')
pl.autoscale(tight=True)
cb = pl.colorbar(ticks=[0.5,1,1.5,2]);
#pl.clim(ticks=[0.5,1,1.5,2])
imaxes = pl.gca(); pl.axes(cb.ax)
pl.yticks(fontsize=20); pl.axes(imaxes)
#pl.xticks(fontsize=20); pl.axes(imaxes)
#pl.axis('equal')
pl.axis('tight')
fig.tight_layout()
pl.savefig('./_plots_to_paper/sound-speed_LO_t'+str(frame)+'_pcolor.png')
pl.close()
示例15: rec_test
def rec_test(file_name, sino_start, sino_end):
print "\n#### Processing " + file_name
sino_start = sino_start + 200
sino_end = sino_start + 2
print "Test reconstruction of slice [%d]" % sino_start
# Read HDF5 file.
prj, flat, dark = tomopy.io.exchange.read_aps_32id(file_name, sino=(sino_start, sino_end))
# Manage the missing angles:
theta = tomopy.angles(prj.shape[0])
prj = np.concatenate((prj[0 : miss_angles[0], :, :], prj[miss_angles[1] + 1 : -1, :, :]), axis=0)
theta = np.concatenate((theta[0 : miss_angles[0]], theta[miss_angles[1] + 1 : -1]))
# normalize the prj
prj = tomopy.normalize(prj, flat, dark)
# reconstruct
rec = tomopy.recon(prj, theta, center=best_center, algorithm="gridrec", emission=False)
# Write data as stack of TIFs.
tomopy.io.writer.write_tiff_stack(rec, fname=output_name)
print "Slice saved as [%s_00000.tiff]" % output_name
# show the reconstructed slice
pl.gray()
pl.axis("off")
pl.imshow(rec[0])