本文整理汇总了Python中matplotlib.gridspec.GridSpec类的典型用法代码示例。如果您正苦于以下问题:Python GridSpec类的具体用法?Python GridSpec怎么用?Python GridSpec使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了GridSpec类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: get_stereo_rose
def get_stereo_rose(self):
"""
Resets the figure and returns a stereonet and rose diagram axis.
When the view in the main window is changed to stereonet and rose
diagram, the figure is reset. The current settings are applied and
two subplots for the stereonet and rose diagram are created. The
axis of the stereonet and rose diagram are returned. This method is
called by the MainWindow "redraw_plot"-method.
"""
self.fig.clf()
self.fig.patch.set_facecolor(self.props["canvas_color"])
self.fig.set_dpi(self.props["pixel_density"])
gridspec = GridSpec(2, 5)
sp_stereo = gridspec.new_subplotspec((0, 0),
rowspan=2, colspan=2)
sp_cbar = gridspec.new_subplotspec((1, 2), rowspan=1, colspan=1)
sp_rose = gridspec.new_subplotspec((0, 3),
rowspan=2, colspan=2)
ax_stereo = self.fig.add_subplot(sp_stereo,
projection=self.get_projection())
ax_rose = self.fig.add_subplot(sp_rose, projection="northpolar")
ax_cbar = self.fig.add_subplot(sp_cbar)
ax_cbar.axis("off")
ax_cbar.set_aspect(8)
return ax_stereo, ax_rose, ax_cbar
开发者ID:gbtami,项目名称:innstereo,代码行数:27,代码来源:plot_control.py
示例2: plot_fd
def plot_fd(fd_file, fd_radius, mean_fd_dist=None, figsize=DINA4_LANDSCAPE):
fd_power = _calc_fd(fd_file, fd_radius)
fig = plt.Figure(figsize=figsize)
FigureCanvas(fig)
if mean_fd_dist:
grid = GridSpec(2, 4)
else:
grid = GridSpec(1, 2, width_ratios=[3, 1])
grid.update(hspace=1.0, right=0.95, left=0.1, bottom=0.2)
ax = fig.add_subplot(grid[0, :-1])
ax.plot(fd_power)
ax.set_xlim((0, len(fd_power)))
ax.set_ylabel("Frame Displacement [mm]")
ax.set_xlabel("Frame number")
ylim = ax.get_ylim()
ax = fig.add_subplot(grid[0, -1])
sns.distplot(fd_power, vertical=True, ax=ax)
ax.set_ylim(ylim)
if mean_fd_dist:
ax = fig.add_subplot(grid[1, :])
sns.distplot(mean_fd_dist, ax=ax)
ax.set_xlabel("Mean Frame Displacement (over all subjects) [mm]")
mean_fd = fd_power.mean()
label = r'$\overline{{\text{{FD}}}}$ = {0:g}'.format(mean_fd)
plot_vline(mean_fd, label, ax=ax)
return fig
开发者ID:poldracklab,项目名称:mriqc,代码行数:33,代码来源:viz_utils.py
示例3: nbo_vs_year
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()
开发者ID:youdar,项目名称:work,代码行数:60,代码来源:collecting_overlap_data.py
示例4: create_canvas
def create_canvas(self): # pragma: no cover
self.fig = Figure()
canvas = FigureCanvas(self.fig)
self.ui.mainLayout.addWidget(canvas)
canvas.setFocusPolicy(QtCore.Qt.StrongFocus)
# Add subplots
gridspec = GridSpec(2, 4)
self.map_ax = self.fig.add_subplot(
gridspec.new_subplotspec((0, 0), rowspan=2, colspan=2)
)
self.spectrum_ax = self.fig.add_subplot(
gridspec.new_subplotspec((0, 2), rowspan=1, colspan=2)
)
self.hist_ax = self.fig.add_subplot(
gridspec.new_subplotspec((1, 2), rowspan=1, colspan=1)
)
self.edge_ax = self.fig.add_subplot(
gridspec.new_subplotspec((1, 3), rowspan=1, colspan=1)
)
# Create the colorbar on the histogram axes
self.cbar = plots.draw_histogram_colorbar(ax=self.hist_ax,
cmap="viridis",
norm=Normalize(0, 1))
self.cbar.ax.set_xlabel("Map Value")
# Adjust the margins
self.fig.tight_layout(pad=0)
self.fig.canvas.draw_idle()
开发者ID:m3wolf,项目名称:xanespy,代码行数:27,代码来源:qt_map_view.py
示例5: main
def main():
matplotlib.rc('font', size=12)
fig = plt.figure(figsize=(16,9))
gs = GridSpec(2, 1, height_ratios=[20, 1])#, 20])
gs.update(hspace=0., wspace=0.)
ax1 = plt.subplot(gs[0])
label_ax = plt.subplot(gs[1])
[ax.set_xlim(0, 599) for ax in (ax1, label_ax)]
ax1.set_ylim(0, 350)
# New way
regiondict = dict(zip(range(1,600), ['MA']*(133-1) + ['CA']*(364-133) + ['p2']*(378-364) + ['NC']*(433-378) + ['p1']*(449-433) + ['p6']*(501-449) + ['PR']*(600-501)))
N_lines = 50
muts = get_muts('gag-gag') + get_muts('gag-pr')
muts = [mut for mut in muts if regiondict[mut[1]] != regiondict[mut[0]]]
muts.sort(key=lambda x: x[-1], reverse=True)
min_mi = muts[N_lines-1][2]
counter = 0
for mut in muts[:N_lines]:
r1, r2 = regiondict[mut[0]], regiondict[mut[1]]
c = 'r' if r2 == 'PR' else 'b'
ax1.add_patch(make_circ(*mut, ec=c))
counter += 1
print counter
r = range(1)
proxy1 = plt.Line2D(r, r, color='b', markerfacecolor='none', lw=3)
proxy2 = plt.Line2D(r, r, color='r', markerfacecolor='none', lw=3)
ax1.legend((proxy1, proxy2), ('Gag-Gag', 'Gag-PR'))
# Add x-axis boxes
locs = [(132, 'MA'), (363, 'CA'), (377, 'p2'), (432, 'NC'), (448, 'p1'), (500, 'p6'),
(599, 'PR')]
x_start = 0
colors = ('#AAAAAA', '#EEEEEE')
for i, (junc, name) in enumerate(locs):
color = colors[i%2]
width = junc - x_start
rect = patches.Rectangle((x_start, 0), width, 1, color=color)
label_ax.add_patch(rect)
label_ax.text(x_start + width/2., 1/2., name, ha='center', va='center')
x_start = junc
label_ax.set_xlim(0, 599)
label_ax.set_xticks([1]+range(50, 650, 50))
label_ax.set_xticklabels([1]+range(50, 500, 50)+[1]+range(50, 150, 50))
[plt.setp(ax.get_xticklabels(), visible=False) for ax in (ax1, )]
[plt.setp(ax.get_yticklabels(), visible=False) for ax in (ax1, label_ax)]
[ax.tick_params(top=False, left=False, right=False, bottom=False) for ax in (ax1, label_ax)]
ax1.tick_params(bottom=True)
ax1.set_xticks(np.arange(0, 599, 10))
label_ax.set_xlabel('Sequence position')
plt.show()
开发者ID:wflynny,项目名称:miseq-analysis,代码行数:60,代码来源:circular_correlation_map.py
示例6: initialize_figure
def initialize_figure(start_hour, stop_hour):
f = plt.figure(figsize=(17, 21))
font_1 = font_0.copy()
font_1.set_size('20')
font_1.set_weight('bold')
plt.suptitle(u"Schemat wyznaczania HRA dla pojedynczego 24-godzinnego nagrania odstępów RR.",
fontproperties=font_1, y=0.995, fontsize=25)
empty_ratio = 0.2
height_ratios = [
0.5, #1 24-tachogram
0.3, #2 plot 24h -> 2h pass
0.9, #3 2-hour tachogram
empty_ratio, #4 empty
0.45, #5 5-min window arrow plot
#empty_ratio, #6
0.9, #7 2-hour windowed tachogram
empty_ratio, #8 empty plot
0.55, #9 calculate descriptors arrow plot
empty_ratio, #10 empty plot
0.9, #11 2-hour windowed tachogram with asymmetry signs
2.0 #12 schema for binomial test
]
num_rows = len(height_ratios)
num_cols = 1
row_number = 0
gs1 = GridSpec(num_rows, num_cols, height_ratios=height_ratios) #[3, 0.3, 3, 0.5, 4])
gs1.update(left=0.04, right=0.99, wspace=0.1, hspace=0.0, bottom=0.04, top=0.98)
return f, gs1
开发者ID:TEAM-HRA,项目名称:hra_suite,代码行数:33,代码来源:schema_for_single_recording.py
示例7: plot_ext_laws
def plot_ext_laws(self):
wave = np.arange(900, 20000)
f0 = np.ones(wave.shape[0])
for law in ['calz', 'ccm', 'allen', 'prevot', 'seaton', 'fitz']:
getattr(self, law)(wave, f0, 1.)
self.wild(wave)
fig = plt.figure()
gs = GridSpec(1,1)
gs.update(left=0.12, right=0.95, top=0.95, bottom=0.12)
ax = fig.add_subplot(gs[0])
ax.semilogx(wave, self.calz_klam, 'c', lw=1.5, label='Calzetti')
# ax.semilogx(wave, self.ccm_klam, 'k', label='Cardelli')
ax.semilogx(wave, self.allen_klam, 'r', lw=1.5, label='Allen')
ax.semilogx(wave, self.prevot_klam, 'g', lw=1.5, label='Prevot')
ax.semilogx(wave, self.seaton_klam, 'm', lw=1.5, label='Seaton')
ax.semilogx(wave, self.fitz_klam, 'b', lw=1.5, label='Fitzpatrick')
ax.legend(frameon=False)
for axis in ['top', 'bottom', 'left', 'right']:
ax.spines[axis].set_linewidth(1.5)
ax.set_ylabel(r'$k(\lambda)$', fontsize=20)
ax.set_xlabel(r'$\lambda [\AA]$', fontsize=20)
ax.set_xlim(9e2, 2.5e4)
ax.set_ylim(0, 20)
plt.savefig('extlaw.pdf')
开发者ID:micaelabagley,项目名称:synthsrc,代码行数:31,代码来源:attenuation.py
示例8: create_canvas
def create_canvas(self):
# Add the canvas to the UI
self.fig = Figure()
canvas = FigureCanvas(self.fig)
self.ui.mainLayout.addWidget(canvas)
# Add subplots
gridspec = GridSpec(2, 4)
self.img_ax = self.fig.add_subplot(
gridspec.new_subplotspec((0, 0), rowspan=2, colspan=2)
)
self.spectrum_ax = self.fig.add_subplot(
gridspec.new_subplotspec((0, 2), rowspan=1, colspan=2)
)
self.hist_ax = self.fig.add_subplot(
gridspec.new_subplotspec((1, 2), rowspan=1, colspan=1)
)
self.edge_ax = self.fig.add_subplot(
gridspec.new_subplotspec((1, 3), rowspan=1, colspan=1)
)
# Create the colorbar on the histogram axes
self.cbar = plots.draw_histogram_colorbar(ax=self.hist_ax,
cmap="viridis",
norm=Normalize(0, 1))
self.cbar.ax.set_xlabel("Intensity")
# Adjust the margins
self.fig.tight_layout(pad=0)
self.fig.canvas.draw_idle()
开发者ID:m3wolf,项目名称:xanespy,代码行数:27,代码来源:qt_frame_view.py
示例9: get_stereo_two_rose
def get_stereo_two_rose(self):
"""
Resets the figure and returns a stereonet two rose diagrams axis.
When the view in the main window is changed to this setting, this
function is called and sets up a plot with a stereonet and two
rose diagram axis. One axis is for azimuth, the other one for
dip.
"""
self.fig.clf()
self.fig.patch.set_facecolor(self.props["canvas_color"])
self.fig.set_dpi(self.props["pixel_density"])
gridspec = GridSpec(2, 4)
sp_stereo = gridspec.new_subplotspec((0, 0),
rowspan=2, colspan=2)
sp_cbar = gridspec.new_subplotspec((1, 2), rowspan=1, colspan=1)
sp_rose = gridspec.new_subplotspec((0, 3),
rowspan=1, colspan=1)
sp_drose = gridspec.new_subplotspec((1, 3),
rowspan=1, colspan=1)
ax_stereo = self.fig.add_subplot(sp_stereo,
projection=self.get_projection())
ax_rose = self.fig.add_subplot(sp_rose, projection="northpolar")
ax_drose = self.fig.add_subplot(sp_drose, projection="dippolar")
ax_cbar = self.fig.add_subplot(sp_cbar)
ax_cbar.axis("off")
ax_cbar.set_aspect(8)
return ax_stereo, ax_rose, ax_drose, ax_cbar
开发者ID:gbtami,项目名称:innstereo,代码行数:28,代码来源:plot_control.py
示例10: __init__
def __init__(self, main_window, settings, data, add_layer_dataset, add_feature, redraw_main):
"""
Initializes the RotationDialog class.
Requires the main_window object, the settings object (PlotSettings
class) and the data rows to initialize. All the necessary widgets are
loaded from the Glade file. A matplotlib figure is set up and added
to the scrolledwindow. Two axes are set up that show the original and
rotated data.
"""
self.builder = Gtk.Builder()
self.builder.set_translation_domain(i18n().get_ts_domain())
script_dir = os.path.dirname(__file__)
rel_path = "gui_layout.glade"
abs_path = os.path.join(script_dir, rel_path)
self.builder.add_objects_from_file(abs_path,
("dialog_rotation", "adjustment_rotation_dipdir",
"adjustment_rotation_dip", "adjustment_rotation_angle"))
self.dialog = self.builder.get_object("dialog_rotation")
self.dialog.set_transient_for(main_window)
self.settings = settings
self.data = data
self.trans = self.settings.get_transform()
self.add_layer_dataset = add_layer_dataset
self.add_feature = add_feature
self.redraw_main = redraw_main
self.adjustment_rotation_dipdir = self.builder.get_object("adjustment_rotation_dipdir")
self.adjustment_rotation_dip = self.builder.get_object("adjustment_rotation_dip")
self.adjustment_rotation_angle = self.builder.get_object("adjustment_rotation_angle")
self.spinbutton_rotation_dipdir = self.builder.get_object("spinbutton_rotation_dipdir")
self.spinbutton_rotation_dip = self.builder.get_object("spinbutton_rotation_dip")
self.spinbutton_rotation_angle = self.builder.get_object("spinbutton_rotation_angle")
self.scrolledwindow_rotate = self.builder.get_object("scrolledwindow_rotate")
self.fig = Figure(dpi=self.settings.get_pixel_density())
self.canvas = FigureCanvas(self.fig)
self.scrolledwindow_rotate.add_with_viewport(self.canvas)
gridspec = GridSpec(1, 2)
original_sp = gridspec.new_subplotspec((0, 0),
rowspan=1, colspan=1)
rotated_sp = gridspec.new_subplotspec((0, 1),
rowspan=1, colspan=1)
self.original_ax = self.fig.add_subplot(original_sp,
projection=self.settings.get_projection())
self.rotated_ax = self.fig.add_subplot(rotated_sp,
projection=self.settings.get_projection())
self.canvas.draw()
self.redraw_plot()
self.dialog.show_all()
self.builder.connect_signals(self)
if sys.platform == "win32":
translate_gui(self.builder)
开发者ID:gbtami,项目名称:innstereo,代码行数:57,代码来源:rotation_dialog.py
示例11: gridplot
def gridplot (grid, loc, rowspan=1, colspan=1):
'''
Returns a matplotlib.gridspec.SubplotSpec for a subplot.
The resulting object can then be added to a matplotlib.figure
using the add_subplot() method.
'''
gridspec = GridSpec (grid[0], grid[1])
subplotspec = gridspec.new_subplotspec(loc, rowspan, colspan)
return subplotspec
开发者ID:codedump,项目名称:paul,代码行数:9,代码来源:mpltrix.py
示例12: plot_flux_decomposition
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()
开发者ID:slochower,项目名称:torsion-transition-matrix,代码行数:57,代码来源:plots.py
示例13: make_figure
def make_figure(self, type):
self.fig.clf()
if type == 'gd':
pass
elif type == 'mc':
gs = GridSpec(1, 1)
gs.update(hspace=0.7, wspace=0.8)
self.splts = [self.fig.add_subplot(gs[int(i/3), int(i%3)]) for i in range(1*1)] # grid nxn
else:
pass
开发者ID:thuongnht,项目名称:Python3,代码行数:10,代码来源:Panel_Plotting.py
示例14: plot_steady_state
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()
开发者ID:slochower,项目名称:torsion-transition-matrix,代码行数:55,代码来源:plots.py
示例15: plot_standard
def plot_standard(corr="acorr"):
os.chdir(tables_dir)
ref = np.loadtxt("stars_lick_val_{0}.txt".format(corr)).T
obs = np.loadtxt("stars_lick_obs_{0}.txt".format(corr)).T
bands = np.loadtxt("bands_matching_standards.txt", usecols=(0), dtype=str).tolist()
bands2, units, error = np.loadtxt("bands.txt", usecols=(0,9,10), dtype=str).T
idx = [list(bands2).index(x) for x in bands]
idx2 = np.array([list(bands).index(x) for x in bands2])
error = error[idx]
units = units[idx]
units = [x.replace("Ang", "\AA") for x in units]
fig = plt.figure(1, figsize=(20,12))
gs = GridSpec(5,5)
gs.update(left=0.03, right=0.988, top=0.98, bottom=0.06, wspace=0.2,
hspace=0.4)
offsets, errs = [], []
for i in range(25):
ax = plt.subplot(gs[i])
plt.locator_params(axis="y", nbins=6)
plt.locator_params(axis="x", nbins=6)
ax.minorticks_on()
# ax.plot(obs[i], ref[i] - obs[i], "ok")
ax.axhline(y=0, ls="--", c="k")
diff = ref[i] - obs[i]
diff, c1, c2 = sigmaclip(diff[np.isfinite(diff)], 2.5, 2.5)
ax.hist(diff, bins=8, color="0.7", histtype='stepfilled')
ylim = plt.ylim()
xlim = plt.xlim()
xlim = np.max(np.abs(xlim))
ax.set_ylim(0, ylim[1] + 2)
ax.set_xlim(-xlim, xlim)
mean = np.nanmean(diff)
N = len(diff)
err = np.nanstd(diff) / np.sqrt(N)
lab = "${0:.2f}\pm{1:.2f}$".format(mean, err)
ax.axvline(x=mean, ls="-", c="r", label=lab)
ax.axvline(x=0, ls="--", c="k")
# ax.axhline(y=float(error[i]))
# ax.axhline(y=-float(error[i]))
# ax.set_xlabel("{0} ({1})".format(bands[i].replace("_", " "), units[i]))
ax.legend(loc=1,prop={'size':12})
ax.set_xlabel("$\Delta$ {0} ({1})".format(bands[i].replace("_", " "),
units[i]))
ax.set_ylabel("Frequency")
offsets.append(mean)
errs.append(err)
offsets = np.array(offsets)[idx2]
errs = np.array(errs)[idx2]
output = os.path.join(home, "plots/lick_stars_{0}.png".format(corr))
plt.savefig(output)
with open(os.path.join(tables_dir, "lick_offsets.txt"), "w") as f:
f.write("# Index Additive Correction\n")
np.savetxt(f, np.column_stack((np.array(bands)[idx2],offsets, errs)),
fmt="%s")
开发者ID:kadubarbosa,项目名称:groups,代码行数:54,代码来源:run_lector.py
示例16: kplot
def kplot(curcode,startdatetime,show_log,title="none",ymarks=[]):
df='%Y-%m-%d %H:%M:%S'
dt=datetime.strptime(startdatetime,df)
# fig,ax = plt.subplots(nrows=3,ncols=1, figsize=(12,5),facecolor='#D3D3D3')
fig = plt.figure(figsize=(12,5),facecolor='#D3D3D3')
fig.suptitle(title)
gs1 = GridSpec(8, 8)
gs1.update(left=0.05, right=0.95, wspace=0.05)
ax1 = plt.subplot(gs1[0:5, :])
ax2 = plt.subplot(gs1[6:8, 0:3])
ax3 = plt.subplot(gs1[6:8, 4:8])
#day
ax2.set_title("days")
days_range=30
table=curcode+"_1day"
kdatas=kdb.query(table,(dt-timedelta(days=days_range)).strftime(df),(dt+timedelta(days=days_range)).strftime(df))
while len(kdatas) < 60:
days_range +=5
kdatas=kdb.query(table,(dt-timedelta(days=days_range)).strftime(df),(dt+timedelta(days=days_range)).strftime(df))
kaxplot(ax2,dt.replace(hour=0,minute=0,second=0),'%m-%d',kdatas,ymarks)
#hour
ax1.set_title("hours")
hours_range=60
table=curcode+"_1hour"
kdatas=kdb.query(table,(dt-timedelta(hours=hours_range)).strftime(df),(dt+timedelta(hours=hours_range)).strftime(df))
while len(kdatas) < 120:
hours_range +=10
kdatas=kdb.query(table,(dt-timedelta(hours=hours_range)).strftime(df),(dt+timedelta(hours=hours_range)).strftime(df))
kaxplot(ax1,dt.replace(minute=0,second=0),'%Y-%m-%d %H',kdatas,ymarks)
#min
ax3.set_title("minutes")
mins_range=50
table=curcode+"_1min"
kdatas=kdb.query(table,(dt-timedelta(minutes=mins_range)).strftime(df),(dt+timedelta(minutes=mins_range)).strftime(df))
while len(kdatas) < 100:
mins_range +=10
kdatas=kdb.query(table,(dt-timedelta(minutes=mins_range)).strftime(df),(dt+timedelta(minutes=mins_range)).strftime(df))
kaxplot(ax3,dt.replace(second=0),'%H:%M',kdatas,ymarks)
#show or log
if show_log == "show" :
plt.show()
else:
if not os.path.exists(show_log):
os.makedirs(show_log)
plt.savefig(show_log+startdatetime.replace(":","%")+".png")
plt.close('all')
开发者ID:wulitu1984,项目名称:alpha,代码行数:52,代码来源:kplot.py
示例17: plot_series
def plot_series(data, order='co', fig=None, subplot_spec=None):
'''
Parameters
----------
data : ndarray
shape (26=ntask, nbin)
order : string, optional
one of 'co' or 'oc', for center-out or out-center data order
determines mapping of data to polygons
defaults to center-out
fig : matplotlib Figure instance
an existing figure to use, optional
subplotspec : matplotlib SubplotSpec instance, optional
an existing subplotspec to use, i.e. subset of a gridspec
'''
if not ((np.rank(data) == 2) & (data.shape[0] == 26)):
raise ValueError('data has wrong shape; should be (26, nbin),'
'actually is %s' % (str(data.shape)))
if order == 'co':
mapping = get_targ_co_dir_mapping()
elif order == 'oc':
mapping = get_targ_oc_dir_mapping()
else:
raise ValueError('`order` not recognized')
if (fig != None) & (not isinstance(fig, Figure)):
raise ValueError('`fig` must be an instance of Figure')
if (fig == None):
fig = plt.figure()
if (subplot_spec != None):
if not isinstance(subplot_spec, SubplotSpec):
raise ValueError('subplot_spec must be instance of '
'SubplotSpec')
ntask, nbin = data.shape
clim = (np.nanmin(data), np.nanmax(data))
if subplot_spec == None:
gs = GridSpec(nbin + 1,1, height_ratios=[1,] * nbin + [0.5,])
gs.update(left=0.02, right=0.98, top=0.98, bottom=0.05)
else:
gs = GridSpecFromSubplotSpec(\
nbin + 1,1, subplot_spec=subplot_spec, \
height_ratios=[1,] * nbin + [0.5,])
for i in xrange(nbin):
ax = fig.add_subplot(gs[i], projection='split_lambert')
plot_gem(data[:,i], order=order, ax=ax, clim=clim)
cbax = fig.add_subplot(gs[-1], aspect=.25)
cb = plt.colorbar(ax.collections[0], cbax, orientation='horizontal')
clim = cb.get_clim()
cb.set_ticks(clim)
cb.set_ticklabels(['%0.1f' % x for x in clim])
return fig
开发者ID:amcmorl,项目名称:motorlab,代码行数:51,代码来源:gems.py
示例18: plot
def plot(self, *args, **kwargs):
g_idx = self.myc['g_idx']
neuron_idx = self.myc['neuron_idx']
l, b, r, t = self.myc['bbox_rect']
fig = self._get_final_fig(self.myc['fig_size'])
gs = GridSpec(2, 2)
gs.update(left=l, right=r, bottom=b, top=t, hspace=0)
# E-->I outgoing
ax = fig.add_subplot(gs[0, 0])
self.plotOutgoing(g_idx, "E", neuron_idx, ax=ax, xlabel='', ylabel='',
use_title=False)
ax.set_xticks([])
# I-->E input
ax = fig.add_subplot(gs[0, 1])
self.plotIncoming(g_idx, "E", neuron_idx, ax=ax, ylabel='', xlabel='',
use_title=False)
ax.set_xticks([])
ax.set_yticks([])
# I-->E outgoing
ax = fig.add_subplot(gs[1, 0])
self.plotOutgoing(g_idx, "I", neuron_idx, ax=ax, use_title=False,
xlabel='', ylabel='')
# E-->I input
ax = fig.add_subplot(gs[1, 1])
self.plotIncoming(g_idx, "I", neuron_idx, ax=ax, xlabel='', ylabel='',
use_title=False)
ax.set_yticks([])
fname = self.get_fname("/connections_pcolor_grid.pdf")
plt.savefig(fname, dpi=300, transparent=True)
plt.close()
# Add an extra colorbar
fig = self._get_final_fig(self.myc['cbar_fig_size'])
ax_cbar = fig.add_axes([0.05, 0.80, 0.8, 0.15])
cbar = mpl.colorbar.ColorbarBase(ax_cbar, cmap=mpl.cm.jet,
norm=mpl.colors.Normalize(vmin=0,
vmax=1),
ticks=[0, 1],
orientation='horizontal')
ax_cbar.xaxis.set_ticklabels(['0', '$g_{E/I}$'])
fname_cbar = self.get_fname("/connections_pcolor_grid_colorbar.pdf")
plt.savefig(fname_cbar, dpi=300, transparent=True)
plt.close()
开发者ID:MattNolanLab,项目名称:ei-attractor,代码行数:49,代码来源:connections.py
示例19: __init__
def __init__(self, window):
"""Initialize spectrogram canvas graphs."""
# Initialize variables to default values.
self.window = window
self.samples = 100 # Number of samples to store
self.fftSize = 256 # Initial FFT size just to render something in the charts
self.sampleRate = 0
self.binFreq = 0
self.binCount = self.fftSize/2
self.graphUpdateHz = 10 # Update rate of the animation
self.coloredBin = None
self.magnitudes = np.zeros((self.samples, self.binCount))
# Tell numpy to ignore errors like taking the log of 0
np.seterr(all='ignore')
# Set up figure to hold plots
self.figure = Figure(figsize=(1024,768), dpi=72, facecolor=(1,1,1), edgecolor=(0,0,0))
# Set up 2x1 grid to hold initial plots
gs = GridSpec(2, 1, height_ratios=[1,2], width_ratios=[1])
gs.update(left=0.075, right=0.925, bottom=0.05, top=0.95, wspace=0.05)
# Set up frequency histogram bar plot
self.histAx = self.figure.add_subplot(gs[0])
self.histAx.set_title('Frequency Histogram')
self.histAx.set_ylabel('Intensity (decibels)')
self.histAx.set_xlabel('Frequency Bin (hz)')
self.histAx.set_xticks([])
self.histPlot = self.histAx.bar(np.arange(self.binCount), np.zeros(self.binCount), width=1.0, linewidth=0.0, facecolor='blue')
# Set up spectrogram waterfall plot
self.spectAx = self.figure.add_subplot(gs[1])
self.spectAx.set_title('Spectrogram')
self.spectAx.set_ylabel('Sample Age (seconds)')
self.spectAx.set_xlabel('Frequency Bin (hz)')
self.spectAx.set_xticks([])
self.spectPlot = self.spectAx.imshow(self.magnitudes, aspect='auto', cmap=get_cmap('jet'))
# Add formatter to translate position to age in seconds
self.spectAx.yaxis.set_major_formatter(FuncFormatter(lambda x, pos: '%d' % (x*(1.0/self.graphUpdateHz))))
# Set up spectrogram color bar
#cbAx = self.figure.add_subplot(gs[3])
#self.figure.colorbar(self.spectPlot, cax=cbAx, use_gridspec=True, format=FuncFormatter(lambda x, pos: '%d' % (x*100.0)))
#cbAx.set_ylabel('Intensity (decibels)')
# Initialize canvas
super(SpectrogramCanvas, self).__init__(self.figure)
# Hook up mouse and animation events
self.mpl_connect('motion_notify_event', self._mouseMove)
self.ani = FuncAnimation(self.figure, self._update, interval=1000.0/self.graphUpdateHz, blit=False)
开发者ID:finson,项目名称:fountain,代码行数:49,代码来源:SpectrogramUI.py
示例20: test_lector
def test_lector():
os.chdir(os.path.join(home, "MILES"))
bands = os.path.join(tables_dir, "bands.txt")
filename = "lector_tmputH9bu.list_LINE"
stars = np.loadtxt(filename, usecols=(0,),
dtype=str)
ref = np.loadtxt(filename,
usecols=(2,3,4,5,6,7,8,9,14,15,16,17,18,24,25,26,
27,28,29,30,31,32,33,34,35))
obs = []
from lick import Lick
for i, star in enumerate(stars):
print star + ".fits"
spec = pf.getdata(star + ".fits")
h = pf.getheader(star + ".fits")
w = h["CRVAL1"] + h["CDELT1"] * \
(np.arange(h["NAXIS1"]) + 1 - h["CRPIX1"])
lick, tmp = lector.lector(w, spec, np.ones_like(w), bands,
interp_kind="linear")
ll = Lick(w, spec, np.loadtxt(bands, usecols=(2,3,4,5,6,7,)))
obs.append(ll.classic)
obs = np.array(obs)
fig = plt.figure(1, figsize=(20,12))
gs = GridSpec(5,5)
gs.update(left=0.08, right=0.98, top=0.98, bottom=0.06, wspace=0.25,
hspace=0.4)
obs = obs.T
ref = ref.T
names = np.loadtxt(bands, usecols=(0,), dtype=str)
units = np.loadtxt(bands, usecols=(9,), dtype=str).tolist()
# units = [x.replace("Ang", "\AA") for x in units]
for i in range(25):
ax = plt.subplot(gs[i])
plt.locator_params(axis="x", nbins=6)
ax.minorticks_on()
ax.plot(obs[i], (obs[i] - ref[i]) / ref[i], "o", color="0.5")
ax.axhline(y=0, ls="--", c="k")
lab = "median $= {0:.3f}$".format(
np.nanmedian(obs[i] - ref[i])).replace("-0.00", "0.00")
ax.axhline(y=np.nanmedian(obs[i] - ref[i]), ls="--", c="r", label=lab)
ax.set_xlabel("{0} ({1})".format(names[i].replace("_", " "), units[i]))
ax.legend(loc=1,prop={'size':15})
ax.set_ylim(-0.01, 0.01)
fig.text(0.02, 0.5, 'I$_{{\\rm pylector}}$ - I$_{{\\rm lector}}$', va='center',
rotation='vertical', size=40)
output = os.path.join(home, "plots/test_lector.png")
plt.show()
plt.savefig(output)
开发者ID:kadubarbosa,项目名称:groups,代码行数:48,代码来源:run_lector.py
注:本文中的matplotlib.gridspec.GridSpec类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论