def make_canonical_plot(NMP_lim=(39,76),LID_lim=(99,154),
c1AKE=config.angles['1AKE'],
c4AKE=config.angles['4AKE'],
xray=True):
"""Scale current figure to default limits and plot the positions of 1AKE and 4AKE.
The points for the end states are taken from txt/x-ray_angles.txt.
If xray=True then add locations of the X-ray structures; this is
the same as running plot_xary_structures().
"""
import pylab
if xray:
plot_xray_structures()
pylab.plot([c1AKE[0],c4AKE[0]], [c1AKE[1],c4AKE[1]], 'sw', ms=12, alpha=0.8)
pylab.xlim(NMP_lim)
pylab.ylim(LID_lim)
python类xlim()的实例源码
def plot(self, outpath=''):
pylab.figure(figsize = (17,10))
diff = self.f2-self.f3
pylab.subplot(2,1,1)
pylab.plot(range(self.lengthSeq), self.f2, 'r-', label = "f2")
pylab.plot(range(self.lengthSeq), self.f3, 'g-', label = "f3")
pylab.xlim([0., self.lengthSeq])
pylab.tick_params(axis='both', which='major', labelsize=25)
pylab.subplot(2,1,2)
diff2 = diff/self.f3
diff2 /= np.max(diff2)
pylab.plot(range(self.lengthSeq), diff2, 'b-', label = "Rescaled (by max) difference / f3")
pylab.xlabel("Temps (en images)", fontsize = 25)
pylab.tick_params(axis='both', which='major', labelsize=25)
pylab.xlim([0., self.lengthSeq])
#pylab.legend(loc= 2, prop = {'size':15})
pylab.savefig(outpath)
pylab.close()
def plotAgainstGFP_hist2d(self):
fig1 = pylab.figure(figsize = (20, 15))
print len(self.GFP)
for i in xrange(min(len(data.cat), 4)):
print len(self.GFP[self.categories == i])
vect = []
pylab.subplot(2,2,i+1)
pop = self.GFP[self.categories == i]
print "cat", i, "n pop", len(self.GFP[(self.categories == i) & (self.GFP > -np.log(12.5))])
H, xedges, yedges = np.histogram2d(self.angles[self.categories == i], self.GFP[self.categories == i], bins = 10)
hist = pylab.hist2d(self.GFP[self.categories == i], self.angles[self.categories == i], bins = 10, cmap = pylab.cm.Reds, normed = True)
pylab.clim(0.,0.035)
pylab.colorbar()
pylab.title(data.cat[i])
pylab.xlabel('GFP score')
pylab.ylabel('Angle (degree)')
pylab.xlim([-4.2, -1])
pylab.show()
def bootstrap_extradata(self, nBoot, extradataA, nbins = 20):
pops =[]
meanpop = [[] for i in data.cat]
pylab.figure(figsize = (14,14))
for i in xrange(min(4, len(extradataA))):
#pylab.subplot(2,2,i+1)
if i ==0:
pylab.title("Bootstrap on means", fontsize = 20.)
pop = extradataA[i]# & (self.GFP > 2000)]#
for index in xrange(nBoot):
newpop = np.random.choice(pop, size=len(pop), replace=True)
#meanpop[i].append(np.mean(newpop))
pops.append(newpop)
pylab.legend()
#pylab.title(cat[i])
pylab.xlabel("Angle(degree)", fontsize = 15)
pylab.xlim([0., 90.])
for i in xrange(len(extradataA)):
for j in xrange(i+1, len(extradataA)):
statT, pvalue = scipy.stats.ttest_ind(pops[i], pops[j], equal_var=False)
print "cat{0} & cat{1} get {2} ({3})".format(i,j, pvalue,statT)
pylab.savefig("/users/biocomp/frose/frose/Graphics/FINALRESULTS-diff-f3/mean_nBootstrap{0}_bins{1}_GFPsup{2}_FLO_{3}.png".format(nBoot, nbins, 'all', randint(0,999)))
def view_waveforms_clusters(data, halo, threshold, templates, amps_lim, n_curves=200, save=False):
nb_templates = templates.shape[1]
n_panels = numpy.ceil(numpy.sqrt(nb_templates))
mask = numpy.where(halo > -1)[0]
clust_idx = numpy.unique(halo[mask])
fig = pylab.figure()
square = True
center = len(data[0] - 1)//2
for count, i in enumerate(xrange(nb_templates)):
if square:
pylab.subplot(n_panels, n_panels, count + 1)
if (numpy.mod(count, n_panels) != 0):
pylab.setp(pylab.gca(), yticks=[])
if (count < n_panels*(n_panels - 1)):
pylab.setp(pylab.gca(), xticks=[])
subcurves = numpy.where(halo == clust_idx[count])[0]
for k in numpy.random.permutation(subcurves)[:n_curves]:
pylab.plot(data[k], '0.5')
pylab.plot(templates[:, count], 'r')
pylab.plot(amps_lim[count][0]*templates[:, count], 'b', alpha=0.5)
pylab.plot(amps_lim[count][1]*templates[:, count], 'b', alpha=0.5)
xmin, xmax = pylab.xlim()
pylab.plot([xmin, xmax], [-threshold, -threshold], 'k--')
pylab.plot([xmin, xmax], [threshold, threshold], 'k--')
#pylab.ylim(-1.5*threshold, 1.5*threshold)
ymin, ymax = pylab.ylim()
pylab.plot([center, center], [ymin, ymax], 'k--')
pylab.title('Cluster %d' %i)
if nb_templates > 0:
pylab.tight_layout()
if save:
pylab.savefig(os.path.join(save[0], 'waveforms_%s' %save[1]))
pylab.close()
else:
pylab.show()
del fig
def align_subplots(
N,
M,
xlim=None,
ylim=None,
):
"""make all of the subplots have the same limits, turn off unnecessary ticks"""
# find sensible xlim,ylim
if xlim is None:
xlim = [np.inf, -np.inf]
for i in range(N * M):
pb.subplot(N, M, i + 1)
xlim[0] = min(xlim[0], pb.xlim()[0])
xlim[1] = max(xlim[1], pb.xlim()[1])
if ylim is None:
ylim = [np.inf, -np.inf]
for i in range(N * M):
pb.subplot(N, M, i + 1)
ylim[0] = min(ylim[0], pb.ylim()[0])
ylim[1] = max(ylim[1], pb.ylim()[1])
for i in range(N * M):
pb.subplot(N, M, i + 1)
pb.xlim(xlim)
pb.ylim(ylim)
if i % M:
pb.yticks([])
else:
removeRightTicks()
if i < M * (N - 1):
pb.xticks([])
else:
removeUpperTicks()
def align_subplot_array(axes, xlim=None, ylim=None):
"""
Make all of the axes in the array hae the same limits, turn off unnecessary ticks
use pb.subplots() to get an array of axes
"""
# find sensible xlim,ylim
if xlim is None:
xlim = [np.inf, -np.inf]
for ax in axes.flatten():
xlim[0] = min(xlim[0], ax.get_xlim()[0])
xlim[1] = max(xlim[1], ax.get_xlim()[1])
if ylim is None:
ylim = [np.inf, -np.inf]
for ax in axes.flatten():
ylim[0] = min(ylim[0], ax.get_ylim()[0])
ylim[1] = max(ylim[1], ax.get_ylim()[1])
(N, M) = axes.shape
for (i, ax) in enumerate(axes.flatten()):
ax.set_xlim(xlim)
ax.set_ylim(ylim)
if i % M:
ax.set_yticks([])
else:
removeRightTicks(ax)
if i < M * (N - 1):
ax.set_xticks([])
else:
removeUpperTicks(ax)
def plot_facade_cuts(self):
facade_sig = self.facade_edge_scores.sum(0)
facade_cuts = find_facade_cuts(facade_sig, dilation_amount=self.facade_merge_amount)
mu = np.mean(facade_sig)
sigma = np.std(facade_sig)
w = self.rectified.shape[1]
pad=10
gs1 = pl.GridSpec(5, 5)
gs1.update(wspace=0.5, hspace=0.0) # set the spacing between axes.
pl.subplot(gs1[:3, :])
pl.imshow(self.rectified)
pl.vlines(facade_cuts, *pl.ylim(), lw=2, color='black')
pl.axis('off')
pl.xlim(-pad, w+pad)
pl.subplot(gs1[3:, :], sharex=pl.gca())
pl.fill_between(np.arange(w), 0, facade_sig, lw=0, color='red')
pl.fill_between(np.arange(w), 0, np.clip(facade_sig, 0, mu+sigma), color='blue')
pl.plot(np.arange(w), facade_sig, color='blue')
pl.vlines(facade_cuts, facade_sig[facade_cuts], pl.xlim()[1], lw=2, color='black')
pl.scatter(facade_cuts, facade_sig[facade_cuts])
pl.axis('off')
pl.hlines(mu, 0, w, linestyle='dashed', color='black')
pl.text(0, mu, '$\mu$ ', ha='right')
pl.hlines(mu + sigma, 0, w, linestyle='dashed', color='gray',)
pl.text(0, mu + sigma, '$\mu+\sigma$ ', ha='right')
pl.xlim(-pad, w+pad)
def generate_plot(self,filename,title='',xlabel='',ylabel='',xlim=None,ylim=None):
logger = logging.getLogger("plotting")
logger.debug('MultipleSeriesPlot.generate_plot')
# a plot with one or more time series sharing a common x axis:
# e.g., the training error and the validation error plotted against epochs
# sort the data series and make sure they are consistent
self.sort_and_validate()
# if there is a plot already in existence, we will clear it and re-use it;
# this avoids creating extraneous figures which will stay in memory
# (even if we are no longer referencing them)
if self.plot:
self.plot.clf()
else:
# create a plot
self.plot = plt.figure()
splt = self.plot.add_subplot(1, 1, 1)
splt.set_title(title)
splt.set_xlabel(xlabel)
splt.set_ylabel(ylabel)
if xlim:
pylab.xlim(xlim)
if ylim:
pylab.ylim(ylim)
for series_name,data_points in self.data.items():
xpoints=numpy.asarray([seq[0] for seq in data_points])
ypoints=numpy.asarray([seq[1] for seq in data_points])
line, = splt.plot(xpoints, ypoints, '-', linewidth=2)
logger.debug('set_label for %s' % series_name)
line.set_label(series_name)
splt.legend()
# TO DO - better filename configuration for plots
self.plot.savefig(filename)
def __init__(self):
pylab.ion()
self.com_real = []
self.com_ref = []
self.support_areas = []
self.xlabel = "$y$ (m)"
self.ylabel = "$x$ (m)"
self.xlim = (-0.6, 0.1)
self.ylim = (0. - 0.05, 1.4 + 0.05)
self.zmp_real = []
self.zmp_ref = []
def plot_com(self):
pylab.plot(
[-p[1] for p in self.com_real], [p[0] for p in self.com_real],
'g-', lw=2)
pylab.plot(
[-p[1] for p in self.com_ref], [p[0] for p in self.com_ref],
'k--', lw=1)
pylab.legend(('$p_G$', '$p_G^{ref}$'), loc='upper right')
pylab.grid(False)
pylab.xlim(self.xlim)
pylab.ylim(self.ylim)
pylab.xlabel(self.xlabel)
pylab.ylabel(self.ylabel)
pylab.title("COM trajectory")
def plot_zmp(self):
pylab.plot(
[-p[1] for p in self.zmp_real], [p[0] for p in self.zmp_real],
'r-', lw=2)
pylab.plot(
[-p[1] for p in self.zmp_ref], [p[0] for p in self.zmp_ref],
'k--', lw=1)
pylab.legend(('$p_Z$', '$p_Z^{ref}$'), loc='upper right')
pylab.grid(False)
pylab.xlim(self.xlim)
pylab.ylim(self.ylim)
pylab.xlabel(self.xlabel)
pylab.ylabel(self.ylabel)
pylab.title("ZMP trajectory")
def plot_support_areas(self, indices=None):
if indices is None:
indices = range(len(self.support_areas))
for i in indices:
vertices, rays = self.support_areas[i]
vertices_3d = _convert_cone2d_to_vertices(vertices, rays)
vertices = [[-v[1], v[0]] for v in vertices_3d]
plot_polygon(vertices, color='g', fill=None, lw=2)
pylab.xlim(self.xlim)
pylab.ylim(self.ylim)
retirement.py 文件源码
项目:MITx-6.00.1x-Introduction-to-Computer-Science-and-Programming-Using-Python
作者: tiagomestreteixeira
项目源码
文件源码
阅读 18
收藏 0
点赞 0
评论 0
def displayRetirementWithMonthsAndRates(monthlies, rates, terms):
plt.figure('retireBoth')
plt.clf()
plt.xlim(30 * 12, 40 * 12)
for monthly in monthlies:
for rate in rates:
xvals, yvals = retire(monthly, rate, terms)
plt.plot(xvals, yvals,
label='retire:' + str(monthly) + ':' + str(int(rate * 100)))
plt.legend(loc='upper left')
def test_dT_impact(xvals, f, nmpc, sim, start=0.1, end=0.8, step=0.02, ymax=200,
sample_size=100, label=None):
"""Used to generate Figure XX of the paper."""
c = raw_input("Did you remove iter/time caps in IPOPT settings? [y/N] ")
if c.lower() not in ['y', 'yes']:
print "Then go ahead and do it."
return
stats = [Statistics() for _ in xrange(len(xvals))]
fails = [0. for _ in xrange(len(xvals))]
pylab.ion()
pylab.clf()
for (i, dT) in enumerate(xvals):
f(dT)
for _ in xrange(sample_size):
nmpc.on_tick(sim)
if 'Solve' in nmpc.nlp.return_status:
stats[i].add(nmpc.nlp.solve_time)
else: # max CPU time exceeded, infeasible problem detected, ...
fails[i] += 1.
yvals = [1000 * ts.avg if ts.avg is not None else 0. for ts in stats]
yerr = [1000 * ts.std if ts.std is not None else 0. for ts in stats]
pylab.bar(
xvals, yvals, width=step, yerr=yerr, color='y', capsize=5,
align='center', error_kw={'capsize': 5, 'elinewidth': 5})
pylab.xlim(start - step / 2, end + step / 2)
pylab.ylim(0, ymax)
pylab.grid(True)
if label is not None:
pylab.xlabel(label, fontsize=24)
pylab.ylabel('Comp. time (ms)', fontsize=20)
pylab.tick_params(labelsize=16)
pylab.twinx()
yfails = [100. * fails[i] / sample_size for i in xrange(len(xvals))]
pylab.plot(xvals, yfails, 'ro', markersize=12)
pylab.plot(xvals, yfails, 'r--', linewidth=3)
pylab.xlim(start - step / 2, end + step / 2)
pylab.ylabel("Failure rate [%]", fontsize=20)
pylab.tight_layout()
def generate_plot(self,filename,title='',xlabel='',ylabel='',xlim=None,ylim=None):
logger = logging.getLogger("plotting")
logger.debug('MultipleSeriesPlot.generate_plot')
# a plot with one or more time series sharing a common x axis:
# e.g., the training error and the validation error plotted against epochs
# sort the data series and make sure they are consistent
self.sort_and_validate()
# if there is a plot already in existence, we will clear it and re-use it;
# this avoids creating extraneous figures which will stay in memory
# (even if we are no longer referencing them)
if self.plot:
self.plot.clf()
else:
# create a plot
self.plot = plt.figure()
splt = self.plot.add_subplot(1, 1, 1)
splt.set_title(title)
splt.set_xlabel(xlabel)
splt.set_ylabel(ylabel)
if xlim:
pylab.xlim(xlim)
if ylim:
pylab.ylim(ylim)
for series_name,data_points in self.data.iteritems():
xpoints=numpy.asarray([seq[0] for seq in data_points])
ypoints=numpy.asarray([seq[1] for seq in data_points])
line, = splt.plot(xpoints, ypoints, '-', linewidth=2)
logger.debug('set_label for %s' % series_name)
line.set_label(series_name)
splt.legend()
# TO DO - better filename configuration for plots
self.plot.savefig(filename)
def generate_plot(self,filename,title='',xlabel='',ylabel='',xlim=None,ylim=None):
logger = logging.getLogger("plotting")
logger.debug('MultipleSeriesPlot.generate_plot')
# a plot with one or more time series sharing a common x axis:
# e.g., the training error and the validation error plotted against epochs
# sort the data series and make sure they are consistent
self.sort_and_validate()
# if there is a plot already in existence, we will clear it and re-use it;
# this avoids creating extraneous figures which will stay in memory
# (even if we are no longer referencing them)
if self.plot:
self.plot.clf()
else:
# create a plot
self.plot = plt.figure()
splt = self.plot.add_subplot(1, 1, 1)
splt.set_title(title)
splt.set_xlabel(xlabel)
splt.set_ylabel(ylabel)
if xlim:
pylab.xlim(xlim)
if ylim:
pylab.ylim(ylim)
for series_name,data_points in self.data.iteritems():
xpoints=numpy.asarray([seq[0] for seq in data_points])
ypoints=numpy.asarray([seq[1] for seq in data_points])
line, = splt.plot(xpoints, ypoints, '-', linewidth=2)
logger.debug('set_label for %s' % series_name)
line.set_label(series_name)
splt.legend()
# TO DO - better filename configuration for plots
self.plot.savefig(filename)
4(improved-14).py 文件源码
项目:computational_physics_N2014301020117
作者: yukangnineteen
项目源码
文件源码
阅读 23
收藏 0
点赞 0
评论 0
def show_results(self):
pl.plot(self.t, self.n_A1, 'b--', label='A1: Time Constant = 1')
pl.plot(self.t, self.n_B1, 'g', label='B1: Time Constant = 2')
pl.plot(self.t, self.n_A2, 'k--', label='A2: Time Constant = 1')
pl.plot(self.t, self.n_B2, 'c', label='B2: Time Constant = 2')
pl.plot(self.t, self.n_A3, 'm--', label='A3: Time Constant = 1')
pl.plot(self.t, self.n_B3, 'y', label='B3: Time Constant = 2')
pl.title('Double Decay Probelm - Nuclei with Different Time Constans')
pl.xlim(0.0, 5.0)
pl.ylim(0.0, 100.0)
pl.xlabel('time ($s$)')
pl.ylabel('Number of Nuclei')
pl.legend(loc='upper right', shadow=True, fontsize='small')
4(improved-13).py 文件源码
项目:computational_physics_N2014301020117
作者: yukangnineteen
项目源码
文件源码
阅读 30
收藏 0
点赞 0
评论 0
def show_results(self):
pl.plot(self.t, self.n_A, 'b--', label='Number of Nuclei A: Time Constant = 1')
pl.plot(self.t, self.n_B, 'g', label='Number of Nuclei B: Time Constant = 2')
pl.title('Double Decay Probelm - Nuclei with Different Time Constans')
pl.xlim(0.0, 5.0)
pl.ylim(0.0, 100.0)
pl.xlabel('time ($s$)')
pl.ylabel('Number of Nuclei')
pl.legend(loc='best', shadow=True)
4(improved-1).py 文件源码
项目:computational_physics_N2014301020117
作者: yukangnineteen
项目源码
文件源码
阅读 31
收藏 0
点赞 0
评论 0
def show_results(self):
pl.plot(self.t, self.n_A, 'b--', label='Number of Nuclei A')
pl.plot(self.t, self.n_B, 'g', label='Number of Nuclei B')
pl.title('Double Decay Probelm-Situation 1')
pl.xlim(0.0, 5.0)
pl.ylim(0.0, 100.0)
pl.xlabel('time ($s$)')
pl.ylabel('Number of Nuclei')
pl.legend(loc='best', shadow=True)