本文整理汇总了Python中matplotlib.gridspec.GridSpec.tight_layout方法的典型用法代码示例。如果您正苦于以下问题:Python GridSpec.tight_layout方法的具体用法?Python GridSpec.tight_layout怎么用?Python GridSpec.tight_layout使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.gridspec.GridSpec
的用法示例。
在下文中一共展示了GridSpec.tight_layout方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: nbo_vs_year
# 需要导入模块: from matplotlib.gridspec import GridSpec [as 别名]
# 或者: from matplotlib.gridspec.GridSpec import tight_layout [as 别名]
def nbo_vs_year(self):
"""
Plot percent of structures, with different NBO per 1000 atoms levels,
from "good" pdb structures (all PDB files with a single model, no unknown
atom types and good CRYST1 records) VS. year
Second sub plot: the total of "good" structures deposited VS. year
"""
plt.close('all')
# figure parameters
# plt.ion() # enables interactive mode
max_y = 105
fontsize = 20
fig = plt.figure(figsize=(8,10))
gs = GridSpec(2,1,height_ratios=[2,1])
# first subplot
ax1 = plt.subplot(gs[0,0])
ax2 = plt.subplot(gs[1,0])
lines = []
line_type = ['.:','.-','.--']
n = len(line_type)
for i,pd in enumerate(self.plot_data_list):
lt = line_type[i%n]
l, = ax1.plot(pd.years,pd.percent,lt)
lines.append(l)
ax1.set_ylabel('Percent of PDB structures',fontsize=fontsize)
ax1.text(min(self.years)+0.5,max_y-4,'a.',fontsize=fontsize)
ax1.tick_params(axis='both',labelsize=fontsize - 2)
ax1.axes.get_xaxis().set_visible(False)
ax1.set_yticks([5,10,40,70,100])
ax1.set_ylim([0,max_y])
ax1.set_xlim([self.start_year,self.end_year])
# legend
labels = ['NBO per 1000 atom > {}']*len(self.nbo_per_1000_atoms)
labels = [x.format(y) for x,y in zip(labels,self.nbo_per_1000_atoms)]
if self.sym:
legend_pos = [0.96,0.70]
else:
legend_pos = [0.54,0.30]
ax1.legend(
lines,labels,
bbox_to_anchor=legend_pos,
loc=1,borderaxespad=0.0)
# Second subplot
ax2.plot(self.years,self.n_total,'.:g')
ax2.set_xlim([self.start_year,self.end_year])
ax2.set_xlabel('Year',fontsize=fontsize)
ax2.set_ylabel('Number of structures',fontsize=fontsize)
ax2.text(min(self.years)+0.5,max(self.n_total)-5,'b.',fontsize=fontsize)
ax2.tick_params(axis='both',labelsize=fontsize - 2)
ax2.set_xticks([self.start_year,1990,2000,self.end_year])
ax2.set_yscale('log')
ax2.set_yticks([10,100,1000])
#
gs.tight_layout(fig)
gs.update(hspace=0)
s = 'all'*(not self.sym) + 'sym'*self.sym
fig_name = 'nbo_vs_year_{}.png'.format(s)
plt.savefig(fig_name)
fig.show()
示例2: plot_flux_decomposition
# 需要导入模块: from matplotlib.gridspec import GridSpec [as 别名]
# 或者: from matplotlib.gridspec.GridSpec import tight_layout [as 别名]
def plot_flux_decomposition(ss, tm, name=None, source_code=None):
f = plt.figure(figsize=(18, 6))
gs = GridSpec(2, 3, wspace=0.5, hspace=0.5)
ax1 = plt.subplot(gs[0, 0])
ax2 = plt.subplot(gs[0, 1])
ax3 = plt.subplot(gs[0, 2])
ax4 = plt.subplot(gs[1, 0])
ax5 = plt.subplot(gs[1, 1])
ax6 = plt.subplot(gs[1, 2])
first_surface = int(len(ss) / 2)
ax1.scatter(range(first_surface), ss[0:first_surface], s=80, c="r")
ax1.set_title("First part of steady state eigenvector")
ax1.set_ylabel("Population")
ax2.scatter(range(first_surface), [tm[i][i + first_surface] for i in range(first_surface)], s=80, c="r")
ax2.set_title("Transition probabilities (unbound to bound)")
ax2.set_ylabel("Probability")
ax3.scatter(range(first_surface), [ss[i] * tm[i][i + first_surface] for i in range(first_surface)], s=80, c="r")
ax3.set_title("Steady state eigenvector * transition probabilities (unbound to bound)")
ax3.set_ylabel("Population * Probability")
ax4.scatter(range(first_surface, 2 * first_surface), ss[first_surface : 2 * first_surface], s=80, c="b")
ax4.set_title("Second part of steady state eigenvector")
ax4.set_ylabel("Population")
ax5.scatter(range(first_surface), [tm[i + first_surface][i] for i in range(first_surface)], s=80, c="b")
ax5.set_title("Transition probabilities (bound to unbound)")
ax5.set_ylabel("Probability")
ax6.scatter(
range(first_surface, 2 * first_surface),
[ss[i] * tm[i + first_surface][i] for i in range(first_surface)],
s=80,
c="b",
)
ax6.set_title("Steady state eigenvector * transition probabilities (bound to unbound)")
ax6.set_ylabel("Population * Probability")
st = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
sts = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
if name:
if source_code is not None:
text = st + " " + name + " in " + source_code
else:
text = st + " " + name
f.text(0.0, 0.0, text, fontsize=12, color="black", ha="left", va="bottom", alpha=0.5)
else:
f.text(0.0, 0.0, st, fontsize=12, color="black", ha="left", va="bottom", alpha=0.5)
gs.tight_layout(f, rect=[0, 0, 1, 1])
plt.savefig("Figures/flux-decomposition-{}-{}".format(sts, name), dpi=150)
# plt.show()
plt.close()
示例3: plot_steady_state
# 需要导入模块: from matplotlib.gridspec import GridSpec [as 别名]
# 或者: from matplotlib.gridspec.GridSpec import tight_layout [as 别名]
def plot_steady_state(unbound, bound, pdf_unbound, pdf_bound, ss, name=None, source_code=None):
f = plt.figure(figsize=(12, 12))
gs = GridSpec(2, 2, wspace=0.5, hspace=0.5)
ax1 = plt.subplot(gs[0, 0])
ax2 = plt.subplot(gs[0, 1])
ax3 = plt.subplot(gs[1, 0])
ax4 = plt.subplot(gs[1, 1])
ax1.scatter(range(len(unbound)), unbound, s=80, c="r")
ax1.plot(range(len(unbound)), unbound, lw=2, c="r")
ax2.scatter(range(len(bound)), bound, s=80, c="b")
ax2.plot(range(len(bound)), bound, lw=2, c="b")
ax1.set_title("Unbound energy surface")
ax2.set_title("Bound energy surface")
bins = int(len(ss) / 2)
ax3.plot(range(len(unbound)), ss[0:bins], lw=2, c="r")
ax3.scatter(range(len(unbound)), ss[0:bins], s=80, c="r")
ax3.plot(range(len(pdf_unbound)), pdf_unbound, lw=4, ls="--", c="k")
ax3.set_title("Boltzmann and forward s.s.")
ax4.plot(range(len(bound)), ss[bins : 2 * bins], lw=2, c="b")
ax4.scatter(range(len(bound)), ss[bins : 2 * bins], s=80, c="b")
ax4.plot(range(len(pdf_bound)), pdf_bound, lw=4, ls="--", c="k")
ax4.set_title("Boltzmann and forward s.s.")
ax4.set_xlabel("Reaction coordinate ($\phi$)")
ax3.set_xlabel("Reaction coordinate ($\phi$)")
ax1.set_ylabel("Energy (a.u.)")
ax2.set_ylabel("Energy (a.u.)")
ax3.set_ylabel("Population")
ax4.set_ylabel("Population")
ax1.set_ylim([-15, 20])
ax2.set_ylim([-15, 20])
ax3.set_ylim([0, 0.6])
ax4.set_ylim([0, 0.6])
st = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
sts = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
if name:
if source_code is not None:
text = st + " " + name + " in " + source_code
else:
text = st + " " + name
f.text(0.0, 0.0, text, fontsize=12, color="black", ha="left", va="bottom", alpha=0.5)
else:
f.text(0.0, 0.0, st, fontsize=12, color="black", ha="left", va="bottom", alpha=0.5)
gs.tight_layout(f, rect=[0, 0, 1, 1])
# plt.show()
plt.savefig("Figures/steady-state-{}-{}".format(sts, name), dpi=150)
plt.close()
示例4: plot_flux
# 需要导入模块: from matplotlib.gridspec import GridSpec [as 别名]
# 或者: from matplotlib.gridspec.GridSpec import tight_layout [as 别名]
def plot_flux(
flux_unbound, unbound_scale, flux_bound, bound_scale, flux_between, between_scale, name=None, source_code=None
):
f = plt.figure(figsize=(12, 12))
gs = GridSpec(2, 2, wspace=0.5, hspace=0.5)
ax1 = plt.subplot(gs[0, 0])
ax2 = plt.subplot(gs[0, 1])
ax3 = plt.subplot(gs[1, 0])
# ax1.scatter(range(len(flux_unbound)), flux_unbound, s=80, c='r')
ax1.plot(range(len(flux_unbound)), flux_unbound * 10 ** unbound_scale, lw=2, c="r")
# ax2.scatter(range(len(flux_bound)), flux_bound, s=80, c='b')
ax2.plot(range(len(flux_bound)), flux_bound * 10 ** bound_scale, lw=2, c="b")
ax1.set_title("Unbound energy surface")
ax2.set_title("Bound energy surface")
# ax3.scatter(range(len(flux_between)), flux_between, s=80, c='k')
ax3.autoscale(enable=False, axis="y")
ax3.plot(range(len(flux_between)), flux_between * 10 ** between_scale, lw=4, ls="-", c="k")
ax3.set_title("Flux between surfaces")
ax3.set_xlabel("Reaction coordinate ($\phi$)")
ax1.set_ylabel("Flux ($\\times 10^{{{}}}$)".format(unbound_scale), size=20)
ax2.set_ylabel("Flux ($\\times 10^{{{}}}$)".format(bound_scale), size=20)
ax3.set_ylabel("Flux ($\\times 10^{{{}}}$)".format(between_scale), size=20)
st = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
sts = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
if name:
if source_code is not None:
text = st + " " + name + " in " + source_code
else:
text = st + " " + name
f.text(0.0, 0.0, text, fontsize=12, color="black", ha="left", va="bottom", alpha=0.5)
else:
f.text(0.0, 0.0, st, fontsize=12, color="black", ha="left", va="bottom", alpha=0.5)
gs.tight_layout(f, rect=[0, 0, 1, 1])
plt.savefig("Figures/flux-{}-{}.png".format(sts, name), dpi=150)
# plt.show()
plt.close()
示例5: GridSpec
# 需要导入模块: from matplotlib.gridspec import GridSpec [as 别名]
# 或者: from matplotlib.gridspec.GridSpec import tight_layout [as 别名]
fig = plt.figure(figsize=(8,2.5))
gs1 = GridSpec(1, 4)
p1 = fig.add_subplot(gs1[0])
p2 = fig.add_subplot(gs1[1])
p3 = fig.add_subplot(gs1[2])
p4 = fig.add_subplot(gs1[3])
p1.pie([ss, sd, sh], autopct='%1.1f%%', pctdistance=1.4, colors=["lightgrey", "grey", "darkgrey"])
p1.set_title("Structural")
p1.axis("equal")
p2.pie([bs, bd, bh], autopct='%1.1f%%', pctdistance=1.4, colors=["lightgrey", "grey", "darkgrey"])
p2.set_title("Behavioural")
p2.axis("equal")
p3.pie([cs, cd, ch], autopct='%1.1f%%', pctdistance=1.4, colors=["lightgrey", "grey", "darkgrey"])
p3.set_title("Creationnal")
p3.axis("equal")
gs1.tight_layout(fig)
p, _ , _=p4.pie([cs, cd, ch], autopct='%1.1f%%', colors=["lightgrey", "grey", "darkgrey"])
p4.axis("equal")
p4.set_visible(False)
lgd = fig.legend(p, ["Static", "Dynamic", "Hybrid"], loc="right")
fig.savefig("../img/analysis_v_pattern.png")
#plt.savefig("../img/creationnal.png", bbox_extra_artists=(lgd,), bbox_inches='tight')
示例6: fit_continuum
# 需要导入模块: from matplotlib.gridspec import GridSpec [as 别名]
# 或者: from matplotlib.gridspec.GridSpec import tight_layout [as 别名]
def fit_continuum(self, data):
"""
Use the data and the mask to estimate and fit the continuum levels.
:param collapsed_data: data-cube in 3D array.
:return: array containing the fitted polynomium.
"""
collapsed_data = np.mean(data, axis=0)
norm = ImageNormalize(vmin=collapsed_data.min(), vmax=collapsed_data.max(), stretch=LogStretch())
fig = plt.figure(figsize=(8, 6))
fig.suptitle('Draw a rectangle using the mouse. \nPress <ENTER> to ' +
'accept it and carry on or "Q" to leave.')
gs = GridSpec(3, 3, height_ratios=[1, 12, 3], width_ratios=[1, 10, 1])
ax1 = plt.subplot(gs[4])
im1 = ax1.imshow(collapsed_data, origin='lower', interpolation='nearest',
cmap='hot_r', norm=norm)
ax1.grid()
self.ax2 = plt.subplot(gs[7])
self.ax2.xaxis.set_ticklabels([])
self.ax2.yaxis.set_ticklabels([])
self.RS = MyRectangleSelector(ax1, self.line_select_callback, drawtype='box',
useblit=True, button=[1], minspanx=5,
minspany=5, spancoords='pixels',
rectprops = dict(facecolor='green',
edgecolor = 'green',
alpha=0.5, fill=True))
self.RS.set_active(True)
self.RS.connect_event('button_press_event', self.on_mouse_click)
self.RS.connect_event('button_release_event', lambda e: self.on_mouse_release(e, data))
self.RS.connect_event('key_press_event', self.on_key_press)
gs.tight_layout(fig)
plt.show()
x1 = min(self.x1, self.x2)
x2 = max(self.x1, self.x2)
y1 = min(self.y1, self.y2)
y2 = max(self.y1, self.y2)
if x1 == x2:
log.warning('x1 and x2 are the same. Using the whole image width.')
x1 = 0
x2 = -1
if y1 == y2:
log.warning('y1 and y2 are the same. Using the whole image height.')
y1 = 0
y2 = -1
data = data[:, y1:y2, x1:x2]
data = data.mean(axis=1)
data = data.mean(axis=1)
median, std = np.median(data), np.std(data)
c = np.where(np.abs(data - median) < std, True, False)
x = np.arange(data.size)
p = np.polyfit(x[c], data[c], 3)
y = np.polyval(p, x)
return y
示例7: run
# 需要导入模块: from matplotlib.gridspec import GridSpec [as 别名]
# 或者: from matplotlib.gridspec.GridSpec import tight_layout [as 别名]
def run(self, show=False):
# Load data
filename = self.filename
d = pyfits.getdata(filename)
h = pyfits.getheader(filename)
path, filename = os.path.split(filename)
# Get wavelength calibration
z = np.arange(h['naxis3'])
w = h['CRVAL3'] + h['CDELT3'] * (z - h['CRPIX3'])
# Convert wavelength from nm to Angstrom
# if w.all() < 1000.:
# w *= 10
# Signal-to-noise clipping
s = d.sum(axis=2)
s = s.sum(axis=1)
gauss_p, _ = self.fit_gaussian(z, s)
log.debug("Gaussian parameters ---")
log.debug("p[0] = %.2f" % gauss_p[0])
log.debug("p[1] = %.2f" % gauss_p[1])
log.debug("p[2] = %.2f" % gauss_p[2])
log.debug("p[3] = %.2f" % gauss_p[3])
lor_p = self.fit_lorentzian(z, s)
log.debug("Lorentzian parameters ---")
log.debug("p[0] = %.2f" % lor_p[0])
log.debug("p[1] = %.2f" % lor_p[1])
log.debug("p[2] = %.2f" % lor_p[2])
log.debug("p[3] = %.2f" % lor_p[3])
fwhm = np.abs(gauss_p[2] * 2 * np.sqrt(2 * np.log(2)))
filter_ = np.where(np.abs(z - gauss_p[1]) < fwhm, True, False)
if show:
plt.plot(z, self.gaussian(gauss_p, z), 'r-', lw=2, label='Gaussian Fit')
plt.plot(z, self.lorentzian(lor_p, z), 'b-', lw=2, label='Lorentzian Fit')
plt.plot(z, s, 'ko')
plt.plot(z[filter_], s[filter_], 'ro')
plt.title('Cube collapsed in XY and fits.')
plt.grid()
plt.legend(loc='best')
plt.gcf().canvas.mpl_connect('key_press_event', self.on_key_press)
plt.show()
signal = d[filter_].mean(axis=0)
noise = d[np.logical_not(filter_)].mean(axis=0)
snr = signal / noise
snr = ndimage.median_filter(snr, 3)
snr_mask = np.where(snr > 2, True, False)
snr_laplacian = ndimage.morphological_laplace(snr * snr_mask, size=3)
snr_mask *= np.where(np.abs(snr_laplacian) < 5.0, True, False)
snr_mask = ndimage.binary_opening(snr_mask, iterations=5)
snr_mask = ndimage.binary_closing(snr_mask, iterations=5)
if show:
fig1 = plt.figure(figsize=(20, 5))
plt.title('Signal-to-Noise Ratio')
gs = GridSpec(1, 3)
ax1 = plt.subplot(gs[0])
ax1.set_title('SNR')
im1 = ax1.imshow(snr, cmap='cubehelix', interpolation='nearest',
origin='lower', vmin=0)
div1 = make_axes_locatable(ax1)
cax1 = div1.append_axes("right", size="5%", pad=0.05)
cbar1 = plt.colorbar(mappable=im1, cax=cax1, use_gridspec=True,
orientation='vertical')
ax2 = plt.subplot(gs[1])
ax2.set_title('Mask')
im2 = ax2.imshow(np.where(snr_mask, 1, 0), cmap='gray',
interpolation='nearest', origin='lower',
vmin=0, vmax=1)
div2 = make_axes_locatable(ax2)
cax2 = div2.append_axes("right", size="5%", pad=0.05)
cbar2 = plt.colorbar(mappable=im2, cax=cax2, use_gridspec=True,
orientation='vertical')
cmap = plt.get_cmap('cubehelix')
cmap.set_bad('w', 1.0)
ax3 = plt.subplot(gs[2])
ax3.set_title('Masked')
im3 = ax3.imshow(np.ma.masked_where(~snr_mask, snr), cmap=cmap, interpolation='nearest',
origin='lower', vmin=0)
div3 = make_axes_locatable(ax3)
cax3 = div3.append_axes("right", size="5%", pad=0.05)
cbar3 = plt.colorbar(mappable=im3, cax=cax3, use_gridspec=True, orientation='vertical')
plt.gcf().canvas.mpl_connect('key_press_event', self.on_key_press)
gs.tight_layout(fig1)
plt.show()
pyfits.writeto(filename.replace('.','.SNR.'), snr, h, clobber=True)
pyfits.writeto(filename.replace('.','.SNR_LAPLACIAN.'), snr_laplacian, h, clobber=True)
#.........这里部分代码省略.........
示例8: plot_flux_single_annotated
# 需要导入模块: from matplotlib.gridspec import GridSpec [as 别名]
# 或者: from matplotlib.gridspec.GridSpec import tight_layout [as 别名]
def plot_flux_single_annotated(surface, flux, scaling=None, name=None, source_code=None):
fig = plt.figure(figsize=(12, 12))
gs = GridSpec(1, 1, wspace=0.5, hspace=0.5)
ax1 = plt.subplot(gs[0, 0])
bins = len(surface)
ax1.scatter(range(len(surface)), surface, s=80, c="k")
if not scaling:
scaling = 10 ** 3
rng = range(bins)
for i in range(bins - 1):
if flux[i, 1] < 0:
plt.annotate(
"",
xy=(flux[i, 0], surface[i]),
xycoords="data",
xytext=(flux[i + 1, 0], surface[i + 1]),
textcoords="data",
arrowprops=dict(
arrowstyle="->, head_width=0.5",
color="b",
shrinkA=10,
shrinkB=10,
linewidth=abs(flux[i, 1]) * scaling,
),
)
else:
plt.annotate(
"",
xy=(flux[i + 1, 0], surface[i + 1]),
xycoords="data",
xytext=(flux[i, 0], surface[i]),
textcoords="data",
arrowprops=dict(
arrowstyle="->, head_width=0.5",
color="b",
shrinkA=10,
shrinkB=10,
linewidth=abs(flux[i, 1]) * scaling,
),
)
ax1.set_title("Flux visualized")
ax1.set_xlabel("Reaction coordinate ($\phi$)")
ax1.set_ylabel("Energy (a.u.)")
st = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
sts = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
if name:
if source_code is not None:
text = st + " " + name + " in " + source_code
else:
text = st + " " + name
fig.text(0.0, 0.0, text, fontsize=12, color="black", ha="left", va="bottom", alpha=0.5)
else:
f.text(0.0, 0.0, st, fontsize=12, color="black", ha="left", va="bottom", alpha=0.5)
gs.tight_layout(fig, rect=[0, 0, 1, 1])
# plt.savefig(name+'-flux-cat-bin-{}.png'.format(k_cat_bin), dpi=150)
plt.show()
plt.close()
示例9: plot_flux_annotated
# 需要导入模块: from matplotlib.gridspec import GridSpec [as 别名]
# 或者: from matplotlib.gridspec.GridSpec import tight_layout [as 别名]
def plot_flux_annotated(
unbound, bound, flux_unbound, flux_bound, flux_between, k_cat_bin, scaling=None, name=None, source_code=None
):
fig = plt.figure(figsize=(6, 6))
gs = GridSpec(1, 1, wspace=0.5, hspace=0.5)
ax1 = plt.subplot(gs[0, 0])
bins = len(unbound)
ax1.scatter(range(len(bound)), bound, s=80, c="b")
ax1.scatter(range(len(unbound)), unbound, s=80, c="r")
if not scaling:
scaling = 10 ** 3
rng = range(bins)
for i in range(bins - 1):
if flux_bound[i, 1] < 0:
af.right_to_left_bound_arrow(plt, flux_bound[i, 1], i, rng, unbound, bound, scaling)
else:
af.left_to_right_bound_arrow(plt, flux_bound[i, 1], i, rng, unbound, bound, scaling)
for i in range(bins - 1):
if flux_unbound[i, 1] < 0:
af.right_to_left_unbound_arrow(plt, flux_unbound[i, 1], i, rng, unbound, bound, scaling)
else:
af.left_to_right_unbound_arrow(plt, flux_unbound[i, 1], i, rng, unbound, bound, scaling)
for i in range(bins):
# DRS: This is correct. Verified for group meeting 2015-10-05.
if flux_between[i, 1] < 0:
af.bound_to_unbound_arrow(plt, flux_between[i, 1], i, rng, unbound, bound, scaling)
else:
af.unbound_to_bound_arrow(plt, flux_between[i, 1], i, rng, unbound, bound, scaling)
max_flux = max(abs(flux_between[:, 1]))
max_index = np.where(abs(flux_between[:, 1]) == max_flux)[0]
ax1.set_title("Flux visualized")
ax1.set_xlabel("Reaction coordinate ($\phi$)")
ax1.set_ylabel("Energy (a.u.)")
bbox_props = dict(fc="white", alpha=0.65)
ax1.annotate(
af.format_decimal(decimal.Decimal(max_flux)),
xy=(max_index, unbound[max_index]),
xycoords="data",
xytext=(+100, +120),
textcoords="offset points",
fontsize=22,
bbox=bbox_props,
arrowprops=dict(arrowstyle="->", facecolor="black", color="black", connectionstyle="arc3,rad=0.4", linewidth=2),
)
ax1.annotate(
af.format_decimal(decimal.Decimal(flux_between[k_cat_bin, 1])),
xy=(k_cat_bin, bound[k_cat_bin]),
xycoords="data",
xytext=(+100, -40),
textcoords="offset points",
fontsize=22,
bbox=bbox_props,
arrowprops=dict(
arrowstyle="->", facecolor="black", color="black", connectionstyle="arc3,rad=-0.4", linewidth=2
),
)
st = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
sts = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
if name:
if source_code is not None:
text = st + " " + name + " in " + source_code
else:
text = st + " " + name
fig.text(0.0, 0.0, text, fontsize=12, color="black", ha="left", va="bottom", alpha=0.5)
else:
f.text(0.0, 0.0, st, fontsize=12, color="black", ha="left", va="bottom", alpha=0.5)
gs.tight_layout(fig, rect=[0, 0, 1, 1])
# plt.savefig('Figures/flux-annotated-{}-{}.png'.format(sts, name), dpi=150)
plt.show()
plt.close()
示例10: run
# 需要导入模块: from matplotlib.gridspec import GridSpec [as 别名]
# 或者: from matplotlib.gridspec.GridSpec import tight_layout [as 别名]
#.........这里部分代码省略.........
if show:
fig1 = plt.figure(figsize=(20, 5))
plt.title('Signal-to-Noise Ratio')
gs = GridSpec(1, 3)
ax1 = plt.subplot(gs[0])
ax1.set_title('SNR')
im1 = ax1.imshow(snr, cmap='cubehelix', interpolation='nearest',
origin='lower', vmin=3, vmax=20)
div1 = make_axes_locatable(ax1)
cax1 = div1.append_axes("right", size="5%", pad=0.05)
cbar1 = plt.colorbar(mappable=im1, cax=cax1, use_gridspec=True,
orientation='vertical')
ax2 = plt.subplot(gs[1])
ax2.set_title('Mask')
im2 = ax2.imshow(np.where(snr_mask, 1, 0), cmap='gray',
interpolation='nearest', origin='lower',
vmin=0, vmax=1)
div2 = make_axes_locatable(ax2)
cax2 = div2.append_axes("right", size="5%", pad=0.05)
cbar2 = plt.colorbar(mappable=im2, cax=cax2, use_gridspec=True,
orientation='vertical')
cmap = plt.get_cmap('cubehelix')
cmap.set_bad('w', 1.0)
ax3 = plt.subplot(gs[2])
ax3.set_title('Masked')
im3 = ax3.imshow(np.ma.masked_where(~snr_mask, snr), cmap=cmap, interpolation='nearest',
origin='lower', vmin=0)
div3 = make_axes_locatable(ax3)
cax3 = div3.append_axes("right", size="5%", pad=0.05)
cbar3 = plt.colorbar(mappable=im3, cax=cax3, use_gridspec=True, orientation='vertical')
plt.gcf().canvas.mpl_connect('key_press_event', self.on_key_press)
gs.tight_layout(fig1)
plt.show()
pyfits.writeto(filename.replace('.','.SNR.'), snr, h, clobber=True)
pyfits.writeto(filename.replace('.','.SNR_LAPLACIAN.'), snr_laplacian, h, clobber=True)
# Adjust continuum
continuum = self.fit_continuum(d)
# Subtract continuum
continuum = np.reshape(continuum, (continuum.size, 1, 1))
continuum = np.repeat(continuum, d.shape[1], axis=1)
continuum = np.repeat(continuum, d.shape[2], axis=2)
d -= continuum
del continuum
# Integrate along the planetary nebulae
d = d * snr_mask
d = d.sum(axis=2)
d = d.sum(axis=1)
d = d / np.float(h['EXPTIME'])
gauss_pw, _ = self.fit_gaussian(w, d)
gauss_pc, _ = self.fit_gaussian(z, d)
log.info("Gaussian parameters ---")
log.info("p[0] = %.4f ADU/s" % gauss_pw[0])
log.info("p[1] = %.4f A = %.4f channels" % (gauss_pw[1], gauss_pc[1]))
log.info("p[2] = %.4f A = %.4f channels" % (gauss_pw[2], gauss_pc[2]))
log.info("p[3] = %.4f ADU/s" % gauss_pw[3])
# total_flux = (gauss_pc[0] - gauss_pc[3]) * np.sqrt(2 * np.pi) \
# * gauss_pc[2]
# log.info("Total flux = (a - d) * sqrt(2pi) * c")
# log.info(" %.5E ADU/s" % total_flux)
fwhm = np.abs(gauss_pw[2] * 2 * np.sqrt(2 * np.log(2)))
filter_ = np.where(np.abs(w - gauss_pw[1]) < fwhm, True, False)
# d = d - d[~filter_].mean()
if show:
plt.plot(w, self.gaussian(gauss_pw, w), 'r-', lw=2, label='Gaussian Fit')
# plt.plot(w, self.lorentzian(lor_p, w), 'b-', lw=2, label='Lorentzian Fit')
plt.plot(w[~filter_], d[~filter_], 'ko')
plt.plot(w[filter_], d[filter_], 'ro')
plt.title('Spectral profile of the masked area.')
plt.xlabel(u'Wavelenght [$\AA$]')
plt.ylabel(u'Integrated Count Level [ADU/s]')
plt.grid()
plt.legend(loc='best')
plt.gcf().canvas.mpl_connect('key_press_event', self.on_key_press)
plt.show()
integrated_flux = (gauss_pc[0] - gauss_pc[3]) \
* (gauss_pc[2] * np.sqrt(2 * np.pi))
log.info("Total flux: %.4E adu/s" % (integrated_flux))
snr_mask = np.where(snr_mask, 1, 0)
pyfits.writeto(
os.path.join(path, filename.replace('.fits', '.mask.fits')),
snr_mask, h, clobber=True)
return