本文整理汇总了Python中matplotlib.backends.backend_pdf.PdfPages.close方法的典型用法代码示例。如果您正苦于以下问题:Python PdfPages.close方法的具体用法?Python PdfPages.close怎么用?Python PdfPages.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.backends.backend_pdf.PdfPages
的用法示例。
在下文中一共展示了PdfPages.close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: validation_report
# 需要导入模块: from matplotlib.backends.backend_pdf import PdfPages [as 别名]
# 或者: from matplotlib.backends.backend_pdf.PdfPages import close [as 别名]
def validation_report(self):
"provides a series of graphs to review a source's light curve. Prints to PDF file."
#100MeV
plot1 = self.flux_at_energy(self.flux_energy_list, 0, '100 Mev')
#1000MeV
plot2 = self.flux_at_energy(self.flux_energy_list, 5,'1000 Mev')
#6309MeV
plot3 = self.flux_at_energy(self.flux_energy_list, 9,'6309 Mev')
#beginning time
plot4 = self.flux_at_time(self.flux_energy_list, 0,'Start Time')
#middle time
plot5a = self.flux_at_time(self.flux_energy_list, int((self.ntstep)/4),'Quarter Time')
plot5b = self.flux_at_time(self.flux_energy_list, int((self.ntstep)/2),'Middle Time')
plot5c = self.flux_at_time(self.flux_energy_list, int(3.0*(self.ntstep)/4),'Three Quarter Time')
#end time
plot6 = self.flux_at_time(self.flux_energy_list, self.ntstep-1,'End Time')
from matplotlib.backends.backend_pdf import PdfPages
file_name='simulator_plots'+self.timestr+'.pdf'
print file_name
pp = PdfPages(file_name)
pp.savefig(plot1)
pp.savefig(plot2)
pp.savefig(plot3)
pp.savefig(plot4)
pp.savefig(plot5a)
pp.savefig(plot5b)
pp.savefig(plot5c)
pp.savefig(plot6)
pp.close()
示例2: main
# 需要导入模块: from matplotlib.backends.backend_pdf import PdfPages [as 别名]
# 或者: from matplotlib.backends.backend_pdf.PdfPages import close [as 别名]
def main():
data = scipy.io.loadmat('data.mat')
x1 = data['x1'][0]
x2 = data['x2'][0]
n = len(x1)
kl = [1, 7, 14, 28] # k = 14 may be an optimal
x = np.arange(-6, 6.05, 0.05)
fig = plt.figure()
plt.rcParams['font.size'] = 10
for i in range(len(kl)):
k = kl[i]
p1 = np.zeros(len(x))
p2 = np.zeros(len(x))
for j in range(len(x)):
r1 = sorted(abs(x1 - x[j]))
r2 = sorted(abs(x2 - x[j]))
p1[j] = float(k) / (n * 2 * r1[k-1])
p2[j] = float(k) / (n * 2 * r2[k-1])
plt.subplot(2, 2, i+1)
plt.plot(x, p1, label=r'$p(\mathbf{x} \mid c_1)$')
plt.plot(x, p2, label=r'$p(\mathbf{x} \mid c_2)$')
plt.legend(framealpha=0, fontsize=7)
plt.title(r'$k = %d$' % k)
plt.xlabel(r'$x$')
plt.ylabel(r'$p(\mathbf{x} \mid c_i)$')
plt.tight_layout()
pp = PdfPages('knn.pdf')
pp.savefig(fig)
pp.close()
plt.clf()
示例3: make_lick_individual
# 需要导入模块: from matplotlib.backends.backend_pdf import PdfPages [as 别名]
# 或者: from matplotlib.backends.backend_pdf.PdfPages import close [as 别名]
def make_lick_individual(targetSN, w1, w2):
""" Make maps for the kinematics. """
filename = "lick_corr_sn{0}.tsv".format(targetSN)
binimg = pf.getdata("voronoi_sn{0}_w{1}_{2}.fits".format(targetSN, w1, w2))
intens = "collapsed_w{0}_{1}.fits".format(w1, w2)
extent = calc_extent(intens)
bins = np.loadtxt(filename, usecols=(0,), dtype=str).tolist()
bins = np.array([x.split("bin")[1] for x in bins]).astype(int)
data = np.loadtxt(filename, usecols=np.arange(25)+1).T
labels = [r'Hd$_A$', r'Hd$_F$', r'CN$_1$', r'CN$_2$', r'Ca4227', r'G4300',
r'Hg$_A$', r'Hg$_F$', r'Fe4383', r'Ca4455', r'Fe4531', r'C4668',
r'H$_\beta$', r'Fe5015', r'Mg$_1$', r'Mg$_2$', r'Mg$_b$', r'Fe5270',
r'Fe5335', r'Fe5406', r'Fe5709', r'Fe5782', r'Na$_D$', r'TiO$_1$',
r'TiO$_2$']
mag = "[mag]"
ang = "[\AA]"
units = [ang, ang, mag, mag, ang, ang,
ang, ang, ang, ang, ang, ang,
ang, ang, mag, mag, ang, ang,
ang, ang, ang, ang, ang, mag,
mag]
lims = [[None, None], [None, None], [None, None], [None, None],
[None, None], [None, None], [None, None], [None, None],
[None, None], [None, None], [None, None], [None, None],
[None, None], [None, None], [None, None], [None, None],
[None, None], [None, None], [None, None], [None, None],
[None, None], [None, None], [None, None], [None, None],
[None, None], [None, None], [None, None], [None, None]]
pdf = PdfPages("figs/lick_sn{0}.pdf".format(targetSN))
fig = plt.figure(1, figsize=(6.25,5))
plt.subplots_adjust(bottom=0.12, right=0.97, left=0.09, top=0.96)
plt.minorticks_on()
ax = plt.subplot(111)
ax.minorticks_on()
plot_indices = np.arange(12,22)
for i, vector in enumerate(data):
if i not in plot_indices:
continue
print "Making plot for {0}...".format(labels[i])
kmap = np.zeros_like(binimg)
kmap[:] = np.nan
for bin,v in zip(bins, vector):
idx = np.where(binimg == bin)
kmap[idx] = v
vmin = lims[i][0] if lims[i][0] else np.median(vector) - 2 * vector.std()
vmax = lims[i][1] if lims[i][1] else np.median(vector) + 2 * vector.std()
m = plt.imshow(kmap, cmap="inferno", origin="bottom", vmin=vmin,
vmax=vmax, extent=extent, aspect="equal")
make_contours()
plt.minorticks_on()
plt.xlabel("X [kpc]")
plt.ylabel("Y [kpc]")
plt.xlim(extent[0], extent[1])
plt.ylim(extent[2], extent[3])
cbar = plt.colorbar(m)
cbar.set_label("{0} {1}".format(labels[i], units[i]))
pdf.savefig()
plt.clf()
pdf.close()
return
示例4: makeStackedBarGraph
# 需要导入模块: from matplotlib.backends.backend_pdf import PdfPages [as 别名]
# 或者: from matplotlib.backends.backend_pdf.PdfPages import close [as 别名]
def makeStackedBarGraph(coords_list, bar_labels_list, stack_label_list, title, axis_labels, file_name):
bar_width = 0.2
step = 2000
inds = np.arange(len(bar_labels_list))
fig = mpl.figure.Figure(figsize=(15,10))
canvas = FigureCanvas(fig)
fig.suptitle(title)
fig.subplots_adjust(wspace = 0.5, hspace = 0.5)
# for color bar
# colorRange, colorTable = orr.generateColorRange(stack_label_list, step=step)
# norm = Normalize(vmax = max(stack_label_list), vmin = min(stack_label_list), clip = True)
# cmap_xvalues = norm(xrange(min(stack_label_list), max(stack_label_list), step))
# cmap_xvalues[0] = 0.
# cmap_xvalues[-1] = 1
# cmap_list = [(val, c) for val, c in zip(cmap_xvalues, orr.generateColorRange(stack_label_list, raw=True, step=step)[1])]
# cmap = LinearSegmentedColormap.from_list('mycmap', cmap_list)
# sm = ScalarMappable(norm=norm, cmap = cmap)
# sm.set_array(stack_label_list)
colorRange, colorTable = orr.generateColors(stack_label_list, [0], step=step)
ax = fig.add_subplot(2,2,1)
ax.set_title(title, fontsize=28)
ax.set_xlabel(axis_labels[0], fontsize=24)
ax.set_ylabel(axis_labels[1], fontsize=24)
pre = coords_list[0][1]
bars = []
bottom = np.zeros((len(coords_list[0][1]),))
for i, (coords, stack_label) in enumerate(zip(coords_list, stack_label_list)):
# if i == 0:
# bar = ax.bar(inds, coords[1], color=colorTable[colorRange.index(coords[0])], align='center', linewidth=0)
# else:
# bar = ax.bar(inds, coords[1], color=colorTable[colorRange.index(coords[0])], align='center', bottom = bottom, linewidth=0)
if i == 0:
bar = ax.bar(inds, coords[1], color=colorTable[i], align='center', linewidth=0)
else:
bar = ax.bar(inds, coords[1], color=colorTable[i], align='center', bottom = bottom, linewidth=0)
bars.append(bar)
bottom = bottom + np.array(coords[1])
ax.set_xticks(inds)
ax.set_xticklabels(bar_labels_list, rotation=45, ha='right')
ax.tick_params(axis='both', which='both', labelsize=18)
ax.legend(bars, stack_label_list, loc=1, bbox_to_anchor=(1.2, 1), ncol=1, markerscale=0.2, fontsize=6)
# fig.colorbar(sm)
pdf = PdfPages(file_name)
pdf.savefig(fig)
pdf.close()
print('Graphing Resource usage: {}kb'.format(getattr(resource.getrusage(resource.RUSAGE_SELF), 'ru_maxrss') / 1000))
示例5: wrfile
# 需要导入模块: from matplotlib.backends.backend_pdf import PdfPages [as 别名]
# 或者: from matplotlib.backends.backend_pdf.PdfPages import close [as 别名]
def wrfile(self):
((sff,eff,dis,his),wh) = self._sf()
pp = PdfPages('SF of %s_%s.pdf' %(wh,self.nm))
plt.figure()
plt.clf()
plt.errorbar(dis,sff,yerr=eff,markersize=4,fmt='o',ecolor='b',c='b',elinewidth=1.5,capsize=4)
plt.xlabel('distance (pixel)')
plt.ylabel('angle difference')
plt.xlim(0,max(dis)+1)
plt.ylim(0,90.)
plt.title('%s: Structure Function for %s (Order %s)' %(self.nm,wh,int(self.od)))
pp.savefig()
bn = 5.
for i in range(len(dis)):
if dis[i] > 0:
hist,bins = np.histogram(np.array(his[i]),range=(0.,90.),
bins=90/bn,density=True) # 5 deg per bin, prob. density func.
center = (bins[:-1] + bins[1:])/2
plt.clf()
plt.bar(center, hist, align='center',width=bn)
plt.xlim(0,90)
plt.xlabel('Angle difference (deg)')
plt.ylabel('Normalized number of pairs in each bin (%s deg)' %bn)
plt.title("Histogram at scale %s (pixel)" %round(dis[i],2))
pp.savefig()
pp.close()
示例6: plot_distributions
# 需要导入模块: from matplotlib.backends.backend_pdf import PdfPages [as 别名]
# 或者: from matplotlib.backends.backend_pdf.PdfPages import close [as 别名]
def plot_distributions(distributions, bucket_pct, axes, out_file):
x_max, y_max = axes
pp = PdfPages(out_file)
variances = sorted(distributions)
subsamples = sorted(distributions[variances[-1]])
if x_max == 0.:
x_max = distributions[0][-1]
bucket_width = x_max * bucket_pct
bucket_boundaries = np.arange(0, x_max + bucket_width / 2., bucket_width)
x_axis_points = np.arange(bucket_width / 2., x_max, bucket_width)
for i,v in enumerate(variances):
plt.figure(i)
plt.xlabel("regret distribution")
if v == 0:
plt.title("true game")
cum_dist = np.array([bisect(distributions[0], b) for b in \
bucket_boundaries])
plt.plot(x_axis_points, (cum_dist[1:] - cum_dist[:-1]) / \
float(cum_dist[-1]), label="true game")
else:
plt.title("$\sigma \\approx$" +str(v))
for s in subsamples:
cum_dist = np.array([bisect(distributions[v][s], b) for b in \
bucket_boundaries])
plt.plot(x_axis_points, (cum_dist[1:] - cum_dist[:-1]) / \
float(cum_dist[-1]), label=str(s)+" samples")
plt.legend(loc="upper right", prop={'size':6})
if y_max != 0.:
plt.axis([0, x_max, 0, y_max])
pp.savefig()
pp.close()
示例7: plot_data_dict_1D
# 需要导入模块: from matplotlib.backends.backend_pdf import PdfPages [as 别名]
# 或者: from matplotlib.backends.backend_pdf.PdfPages import close [as 别名]
def plot_data_dict_1D(self, results_path, file_n, data, timepoints):
print 'plotting now...'
pp = PdfPages(results_path+'/'+file_n)
#nBins = 50
cc = 0
xmin, xmax = -1, 7
x_grid = linspace(xmin, xmax, 1000)
for tp in timepoints:
dat = log10(1+data[tp][:,0])
dat[isneginf(dat)] = 0
print dat
kde = st.gaussian_kde(dat, bw_method=0.2)
pdf = kde.evaluate(x_grid)
ax = plt.subplot(4, 5, cc + 1)
ax.plot(x_grid, pdf, color='blue', alpha=0.5, lw=3)
ax.set_xlim([-1, 7])
#plt.hist( data[tp], nBins )
#plt.xscale('log')
cc += 1
pp.savefig()
plt.close()
pp.close()
示例8: compare_board_estimations
# 需要导入模块: from matplotlib.backends.backend_pdf import PdfPages [as 别名]
# 或者: from matplotlib.backends.backend_pdf.PdfPages import close [as 别名]
def compare_board_estimations(esti_extrinsics, board, board_dim, \
actual_boards, save_name=None):
"""
Plots true and estimated boards on the same figure
Args:
esti_extrinsics: dictionary, keyed by image number, values are Extrinsics
board:
board_dim: (board_width, board_height)
actual_boards: list of dictionaries
save_name: filename, string
"""
if save_name:
pp = PdfPages(save_name)
plt.clf()
for i in xrange(len(actual_boards)):
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
act_board = actual_boards[i]
aX, aY, aZ = util.board_dict2array(act_board, board_dim)
ax.plot_wireframe(aX, aY, aZ, color='b')
if i in esti_extrinsics:
esti_loc = esti_extrinsics[i].trans_vec
esti_board = util.move_board(board, esti_loc)
eX, eY, eZ = util.board_dict2array(esti_board, board_dim)
ax.plot_wireframe(eX, eY, eZ, color='r')
if pp:
pp.savefig()
else:
plt.show()
if pp:
pp.close()
示例9: anal2pdf
# 需要导入模块: from matplotlib.backends.backend_pdf import PdfPages [as 别名]
# 或者: from matplotlib.backends.backend_pdf.PdfPages import close [as 别名]
def anal2pdf():
pp = PdfPages('../../datafiles/jul14/analplots.pdf')
fnames = [
'../../datafiles/jul14/vsweep_10_1.h5',
'../../datafiles/jul14/vsweep_10_1b.h5',
'../../datafiles/jul14/vsweep_10_2.h5',
'../../datafiles/jul14/vsweep_10_3.h5',
'../../datafiles/jul14/vsweep_10_4.h5',
'../../datafiles/jul14/vsweep_10_5.h5',
'../../datafiles/jul14/vsweep_10_6.h5']
for fn in fnames:
anal_vsweep(fn)
figure(1)
suptitle('Voltage sweep, 5096MHz, raw phase(Y), time_samples(X)')
f=gcf()
f.savefig(pp,format='pdf')
figure(3)
suptitle('Voltage sweep, 5096MHz, radians(Y) vs mV(X)')
f=gcf()
f.savefig(pp,format='pdf')
pp.close()
示例10: complexAll
# 需要导入模块: from matplotlib.backends.backend_pdf import PdfPages [as 别名]
# 或者: from matplotlib.backends.backend_pdf.PdfPages import close [as 别名]
def complexAll(self, f1=0., f2=0., amax=.16, nrows=1, ncols=1, antList=allAnts ) :
pyplot.ioff()
pp = PdfPages( 'ComplexLeaks.pdf' )
scale = 10./math.sqrt(ncols*nrows)
if f1 == 0. :
[f1, f2] = LkSet.xlimits( self ) # default is to find freq limits in the data
print "frequency limits: %.3f - %.3f GHz" % (f1,f2)
ymin = -1.*amax
ymax = amax
npanel = 0
for ant in antList :
npanel = npanel + 1
if npanel > nrows * ncols :
npanel = 1
pyplot.clf()
p = pyplot.subplot(nrows, ncols, npanel, aspect='equal') # DL,DR in one panel
p.tick_params( axis='both', which='major', labelsize=scale )
p.axis( [ymin, ymax, ymin, ymax] )
p.grid(True)
for Leak in self.LeakList :
if Leak.ant == ant :
print "plotting DR and DL for antenna %d" % ant
Leak.plotComplex( p, f1, f2 )
#pyplot.title("C%d DR (circles, solid) and DL (diamonds, dashed)" % ant, fontdict={'fontsize': scale})
if (npanel == nrows*ncols) or (ant == antList[-1] ) :
pyplot.savefig( pp, format='pdf' )
pp.close()
示例11: write_pressure_graph
# 需要导入模块: from matplotlib.backends.backend_pdf import PdfPages [as 别名]
# 或者: from matplotlib.backends.backend_pdf.PdfPages import close [as 别名]
def write_pressure_graph(self):
P.xlabel("Temperature")
P.ylabel("Pressure")
P.title("Pressure per Temperature")
P.axis([0.0,self.temp_points[-1]+10., 0.0,self.pressure_points[-1]+1])
ax = P.gca()
ax.set_autoscale_on(False)
popt,pcov = curve_fit(fit,self.temp_points,self.pressure_points)
y_fit = [popt[0]*x+popt[1] for x in self.temp_points]
y_fit.insert(0, popt[1])
fit_x_points = self.temp_points[:]
fit_x_points.insert(0,0.)
pp = PdfPages(str(SCREEN_SIZE)+"_"+str(N)+".pdf")
P.plot(self.temp_points, self.pressure_points, "o", fit_x_points, y_fit, "--")
#P.savefig()
#P.plot(
#pp.savefig()
#print(self.pressure_points)
#print(y_fit)
#print(fit_x_points)
#print(y_fit)
pp.savefig()
pp.close()
示例12: readCurvesFromFileCallback
# 需要导入模块: from matplotlib.backends.backend_pdf import PdfPages [as 别名]
# 或者: from matplotlib.backends.backend_pdf.PdfPages import close [as 别名]
def readCurvesFromFileCallback():
# Ask for input file
_filename = askForInputFile(fileFilter="*.cur")
if _filename == "":
return
# Load data from file
[_readCurves, _readVoltages] = loadDataFromFile(_filename)
for i in range(0, len(_readVoltages)):
_voltages = []
_currents = []
for j in range(0, len(_readCurves[i])):
_voltages.extend([_readCurves[i][j][0]])
_currents.extend([_readCurves[i][j][1]])
# Plot read data
onlyFilename = _filename.split("/")[-1]
plotCurves(_readCurves, _readVoltages, onlyFilename, interpolate=True)
# Ask if wants to save plot to PDF file
d = YesNoDialog(rootWindowHandler, 'Save plot to PDF file?', 'Yes', 'No')
rootWindowHandler.wait_window(d.top)
if not yesNoReturnedValue:
return
_fileTypes = '*.*'
_filename = askForOutputFilename(_fileTypes)
if _filename == "":
return
_filename = fixExtensionOfFilename(_filename, 'pdf')
pp = PdfPages(_filename)
plot.savefig(pp, format='pdf')
pp.close()
print 'Saved curves to PDF file: "%s"' % _filename
示例13: plot_weights_nircam
# 需要导入模块: from matplotlib.backends.backend_pdf import PdfPages [as 别名]
# 或者: from matplotlib.backends.backend_pdf.PdfPages import close [as 别名]
def plot_weights_nircam():
inst = webbpsf.NIRCam()
filtlist_W = [f for f in inst.filter_list if f[-1] == 'W']
filtlist_M = [f for f in inst.filter_list if f[-1] == 'M']
filtlist_N = [f for f in inst.filter_list if f[-1] == 'N' or f[-1] =='2']
#filtlist_C = [f for f in inst.filter_list if f[-1] == 'C']
from matplotlib.backends.backend_pdf import PdfPages
pdf=PdfPages('weights_nircam.pdf')
plotweights('nircam', filtlist=filtlist_W)
Mstar = pysynphot.Icat('ck04models',3500,0.0,2.0)
plotweights('nircam', filtlist=filtlist_W, overplot=True, ls='--', source=Mstar)
pdf.savefig()
plotweights('nircam', filtlist=filtlist_M)
Mstar = pysynphot.Icat('ck04models',3500,0.0,2.0)
plotweights('nircam', filtlist=filtlist_M, overplot=True, ls='--', source=Mstar)
pdf.savefig()
plotweights('nircam', filtlist=filtlist_N)
Mstar = pysynphot.Icat('ck04models',3500,0.0,2.0)
plotweights('nircam', filtlist=filtlist_N, overplot=True, ls='--', source=Mstar)
pdf.savefig()
pdf.close()
示例14: plot_miri_comparison
# 需要导入模块: from matplotlib.backends.backend_pdf import PdfPages [as 别名]
# 或者: from matplotlib.backends.backend_pdf.PdfPages import close [as 别名]
def plot_miri_comparison():
inst = webbpsf.MIRI()
filtlist_W = [f for f in inst.filter_list if f[-1] == 'W']
filtlist_C = [f for f in inst.filter_list if f[-1] != 'W']
from matplotlib.backends.backend_pdf import PdfPages
pdf=PdfPages('weights_miri_comparison.pdf')
for filts in [filtlist_W, filtlist_C]:
try:
os.unlink('/Users/mperrin/software/webbpsf/data/MIRI/filters')
except:
pass
os.symlink('/Users/mperrin/software/webbpsf/data/MIRI/real_filters', '/Users/mperrin/software/webbpsf/data/MIRI/filters')
plotweights('miri', filtlist=filts)
os.unlink('/Users/mperrin/software/webbpsf/data/MIRI/filters')
os.symlink('/Users/mperrin/software/webbpsf/data/MIRI/fake_filters', '/Users/mperrin/software/webbpsf/data/MIRI/filters')
plotweights('miri', filtlist=filts, overplot=True, ls='--')
P.draw()
pdf.savefig()
pdf.close()
示例15: err_histogram
# 需要导入模块: from matplotlib.backends.backend_pdf import PdfPages [as 别名]
# 或者: from matplotlib.backends.backend_pdf.PdfPages import close [as 别名]
def err_histogram(output, basedir='.',bins=10, field='MLWA', err='dMLWA', suffix='coef',
label=r'$\delta\tau_{L,\mathrm{fit}}/\tau_L$',exclude=exclude, ymax=90):
ratio_list = []
for p in range(6):
coef = '{}/NGC_891_P{}_bin30_allz2.{}.fits'.format(basedir,p+1,suffix)
print coef
c = pyfits.open(coef)[1].data
tmp = c[err]
if field == 'TAUV':
tmp *= 1.086
else:
tmp /= c[field]
tmp = np.delete(tmp,np.array(exclude[p]) - 1)
ratio_list.append(tmp)
ratio = np.hstack(ratio_list)
ratio = ratio[ratio == ratio]
ratio = ratio[np.where(ratio < 0.8)[0]]
ax = plt.figure().add_subplot(111)
ax.set_xlabel(label)
ax.set_ylabel(r'$N$')
ax.hist(ratio, bins=bins, histtype='step', color='k')
ax.set_xlim(0,0.52)
ax.set_xticks([0,0.1,0.2,0.3,0.4,0.5])
ax.set_ylim(0,ymax)
ax.set_yticks(range(0,int(ymax/10)*10+10,int(int(ymax/10)/4)*10))
pp = PDF(output)
pp.savefig(ax.figure)
pp.close()
plt.close(ax.figure)
return