def plot_figure1(experiment, level='strain', err_type='stderr', ONSET=True, num_mins=15, tbin_size=5, ADD_SOURCE=True): """breakfast hypothesis """ E = experiment use_days = ['chow', 'HiFat'] all_avgs, all_errs = load_data(E, level, err_type, ONSET, num_mins, tbin_size) # directory text = 'AS_onset' if ONSET else 'AS_offset' on_text = 'from %s' % text if ONSET else 'to %s' % text dirname = E.figures_dir_subpar + 'breakfast/fig1/%s/' % text if not os.path.isdir(dirname): os.makedirs(dirname) if level == 'strain': fig_title = 'Probability of feeding and drinking %s, DC vs. LC\n%d strains, avg$\pm$%s' % ( on_text, E.num_strains, err_type) subtitles = [ '%s: %s' % (x, y) for y in use_days for x in E.strain_names ] fig = draw_subplot1(E, all_avgs, all_errs, fig_title, subtitles, ONSET, num_mins) fname = dirname + '%s_probability_DC_LC_%dstrains_first_%dmins_binsize%ds_%s' % ( text, E.num_strains, num_mins, tbin_size, err_type) save_plot(fname, fig, ADD_SOURCE=ADD_SOURCE, ypad=-0.04)
def plot_breakfast_cycles(experiment, level='strain', err_type='stdev', ONSET=True, num_mins=15, tbin_size=5, days=None, ADD_SOURCE=True): """breakfast hypothesis """ E = experiment cycles = E.cycles days_to_use = E.daysToUse if days is None else days print "days_to_use: %s" % days_to_use num_items = get_num_items(E, level) all_avgs = np.zeros( (len(cycles), num_items, num_mins * 60 / tbin_size, 2)) # F, W all_errs = np.zeros((len(cycles), num_items, num_mins * 60 / tbin_size, 2)) for c, cycle in enumerate(cycles): avgs, errs, labels = get_breakfast_data(E, level, err_type, ONSET=ONSET, cycle=cycle, num_mins=num_mins, days=days_to_use) all_avgs[c], all_errs[c] = avgs, errs # directory text = 'AS_onset' if ONSET else 'AS_offset' dirname = E.figures_dir_subpar + 'breakfast/all_cycles/%s/%s_days/' % ( text, E.use_days) if not os.path.isdir(dirname): os.makedirs(dirname) if level == 'strain': fig_title = 'Probability of feeding and drinking, 24H-DC-LC\n%s_days: %d to %d' %( E.use_days, E.daysToUse[0], E.daysToUse[-1]) \ + '\nstrains, avg$\pm$%s' %err_type subtitles = [x for x in E.strain_names] fig = draw_subplot(E, all_avgs, all_errs, fig_title, subtitles, ONSET, num_mins, ADD_SOURCE=ADD_SOURCE) fname = dirname + 'all_cycles_%s_probability_%dstrains_first_%dmins_binsize%ds_%s' % ( text, E.num_strains, num_mins, tbin_size, err_type) save_plot(fname, fig)
def plot_breakfast_comparison(experiment, level='strain', err_type='stderr', ONSET=True, num_mins=15, tbin_size=5, days=None, ADD_SOURCE=True): """ all groups in one plot """ E = experiment print "%s..\nlevel: %s\nerr_type: %s\nONSET: %s" % ( plot_breakfast.__name__, level, err_type, ONSET) if ONSET: print "num_mins: %d" % num_mins # days to use days_to_use = E.daysToUse if days is None else days _, num_md_ok = E.count_mousedays(days=days_to_use) # load data avgs, errs, labels = get_breakfast_data(E, level, err_type, ONSET=ONSET, num_mins=num_mins, days=days_to_use) # directory text = 'AS_onset' if ONSET else 'AS_offset' dirname = E.figures_dir_subpar + 'breakfast/%s/%s_days/' % (text, E.use_days) if not os.path.isdir(dirname): os.makedirs(dirname) if level == 'strain': fig_title = 'Probability of feeding and drinking, across 24H\n%s_days: %d to %d' %( E.use_days, E.daysToUse[0], E.daysToUse[-1]) \ + '\nstrains, avg$\pm$%s' %err_type subtitles = ['Feeding', 'Drinking'] fig = draw_subplot_compare(E, avgs, errs, fig_title, subtitles, ONSET, num_mins, ADD_SOURCE=ADD_SOURCE) fname = dirname + 'group_comparison_%s_probability_24H_%dstrains_first_%dmins_binsize%ds_%s' % ( text, E.num_strains, num_mins, tbin_size, err_type) save_plot(fname, fig)
def plot_breakfast(experiment, cycle='24H', level='group', err_type='sd', ONSET=True, num_mins=15, tbin_size=5, days=None, plot_type='breakfast', ADD_SOURCE=True): """breakfast hypothesis """ E = experiment # directory text = 'AS_onset' if ONSET else 'AS_offset' dirname = E.figures_dir + 'breakfast/%s/' % text if not os.path.isdir(dirname): os.makedirs(dirname) print "%s, level: %s, err_type: %s, cycle: %s" % (plot_breakfast.__name__, level, err_type, cycle) data_F, _ = E.generate_breakfast_data(cycle, level, act='F', err_type=err_type, ONSET=ONSET, days=days) data_W, labels = E.generate_breakfast_data(cycle, level, act='W', err_type=err_type, ONSET=ONSET, days=days) stop # data = np.tile(np.zeros_like(data[:, :, np.newaxis]), (1,1,2)) if level == 'group': # fig_title = 'Probability of feeding and drinking, across %s\n%s_days: %d to %d' %( # cycle, E.use_days, E.daysToUse[0], E.daysToUse[-1]) \ # + '\nstrains, avg$\pm$%s' %err_type # subtitles = [x for x in E.strain_names] fname = dirname + '%s_%s_%dstrains_%s' % (plot_type, text, E.num_strains, cycle) fig = draw_subplot(E, data, ONSET, num_mins, fname) save_plot(fname, fig)
def plot_first_ASs(experiment, level='strain', days=None, num_AS=5, num_mins=5, ADD_SOURCE=True): E = experiment days_to_use = E.daysToUse if days is None else days text = 'all ASs' if num_AS is None else str(num_AS) print "%s\nlevel: %s\ndays: %r\nnum_AS: %s\nnum_min: %d" % ( plot_first_ASs.__name__, level, days, text, num_mins) text2 = 'all_ASs' if num_AS is None else 'first_%dASs' % num_AS if level == 'strain': dirname = E.figures_dir_subpar + 'within_AS/%s_days/' % E.use_days if not os.path.isdir(dirname): os.makedirs(dirname) fig, axes = plt.subplots(nrows=len(days_to_use), ncols=len(E.groups), figsize=(7, 10), sharex=True, sharey=True) c = 0 for day in days_to_use: for group in E.groups: print 'day%d, group:%d, %s' % (day, group.number, group.name) ax = axes.flatten()[c] AS_list = group.generate_AS_structure(day, num_AS) plot_strain_AS_structure(E, level, group, ax, AS_list, day, num_AS, num_mins) c += 1 plt.subplots_adjust(bottom=.08, top=.92, hspace=.4) fig_title = 'Within-AS structure\n%s\nacclimation to transition days: %dto%d' % ( text2, days_to_use[0], days_to_use[-1]) xlabel = 'Time from AS onset [min]' ylabel = 'AS sorted by duration' subplot_labels(fig, xlabel, ylabel, fig_title, ADD_SOURCE) fname = dirname + 'within_AS_structure_strains_%s_%s_first_%dmin.pdf' % ( E.use_days, text2, num_mins) save_plot(fname, fig)
def draw_group_features(E, data, labels, features, bin_type, err_type, fname, plot_type='features', ADD_SOURCE=False): figsize = (16, 4.8) nrows, ncols = 4, 7 fig, axes = plt.subplots(nrows, ncols, figsize=figsize, sharex=True) other_color = E.fcolors['other'][0] xs = get_CT_xs(bin_type, SHIFT=E.BIN_SHIFT, tshift=E.binTimeShift) cnt = 0 for n in xrange(nrows): for m in xrange(ncols): ax = axes.flatten()[n*ncols + m] if n == 0 and m >= 3: ax.axis('off') continue feature = features[cnt] colors = get_two_group_features_colors(E, feature) subtitle = '%s %s' %(feature, E.plot_settings_dict[feature]['unit']) for g in xrange(E.num_strains): if bin_type.endswith('bins'): tkw = {'fmt':'o-', 'ms':2}#, 'elinewidth':.5, 'capsize':1} mec = '.3' if g == 1 else colors[g] ax.errorbar(xs, data[g, cnt, :, 0], yerr=data[g, cnt, :, 1], color=colors[g], mec=mec, **tkw) elif bin_type.endswith('cycles'): bar_width = .25 ax.bar(xs+bar_width*g, data[g, cnt, :, 0], bar_width, yerr=[[0,0,0], data[g, cnt, :, 1]], color=colors[g], capsize=2, ecolor=colors[g], ) set_axis_layout(E, ax, bin_type) ax.set_title(subtitle, fontsize=10) cnt += 1 set_panel_layout(E, fig, err_type, bin_type) plt.subplots_adjust(hspace=.6, wspace=.3) save_plot(fname, fig, ADD_SOURCE=ADD_SOURCE, sypad=-.02)
def draw_subplot(experiment, avgs, labels, level, cycle, err_type, fname, plot_subtype, plot_type, ADD_SOURCE=True): E = experiment figsize, nrows, ncols, _, _ = get_subplot_specs(E, num_subplots=len(E.groups)) fig, axes = plt.subplots(nrows, ncols, figsize=figsize) slice_labels = ['M', 'F', 'W', 'other', 'IS'] colors = [E.fcolors[x][0] for x in slice_labels] title, subtitles = get_figure_titles(E, labels, level, cycle, err_type, plot_type) for c in xrange(avgs.shape[0]): try: ax = axes.flatten()[c] if plot_subtype == 'bar': stop elif plot_subtype == 'pie': plot_as_a_pie(ax, avgs[c], colors, slice_labels, subtitles[c]) if c == 0: h, l = ax.get_legend_handles_labels() except IndexError: ax.axis('off') continue set_legend(fig, h, l) # plt.subplots_adjust(hspace=.4) add_titles_notes(E, fig, title=title, typad=-.15, tlxpad=0, tlypad=-.15) save_plot(fname, fig, ADD_SOURCE=ADD_SOURCE, labelsize=6, sypad=.25)
def draw_mouse_features(E, data, labels, features, bin_type, err_type, fname, plot_type='features', ADD_SOURCE=False): figsize = (14.4, 4.8) nrows, ncols = 4, 7 fig, axes = plt.subplots(nrows, ncols, figsize=figsize, sharex=True) other_color = E.fcolors['other'][0] xticks, xlabels = get_CT_ticks_labels(bin_type='12bins', SHIFT=E.BIN_SHIFT, tshift=E.binTimeShift) xs = xticks[:-1] +1 for g in xrange(E.num_strains): cnt = 0 for n in xrange(nrows): for m in xrange(ncols): ax = axes.flatten()[n*ncols + m] if n == 0 and m >= 3: ax.axis('off') continue feature = features[cnt] colors = get_two_group_features_colors(E, feature) subtitle = '%s %s' %(feature, E.plot_settings_dict[feature]['unit']) idx = labels[:, 0] == g data_, labels_ = data[idx], labels[idx] if bin_type.endswith('bins'): tkw = {'fmt':'o-', 'ms':2, 'elinewidth':.5, 'capsize':1} for mouse in xrange(idx.sum()): ax.errorbar(xs, data[mouse, cnt, :, 0], yerr=data[mouse, cnt, :, 1], color=colors[g], mec=colors[g], **tkw) else: stop set_axis_layout(E, ax, bin_type) ax.set_title(subtitle, fontsize=10) cnt += 1 set_panel_layout(E, fig, err_type, tbin_type='24H') save_plot(fname + '_group%d' %g, fig, ADD_SOURCE=ADD_SOURCE, sypad=-.02) plt.close()
def plot_figure(experiment, level='strain', err_type='stdev', plot_type='pie', ADD_SOURCE=True): E = experiment cycles = E.cycles use_days = ['chow', 'HiFat'] days_to_use = [E.chowDayNumbers, E.HiFatDayNumbers] print "days_to_use: %s" %days_to_use # load data num_items = get_num_items(E, level) num_slices = 5 all_avgs = np.zeros((num_items, len(days_to_use), len(cycles), num_slices)) # DC/LC all_errs = np.zeros((num_items, len(days_to_use), len(cycles), num_slices)) for d, days in enumerate(days_to_use): for c, cycle in enumerate(cycles): avgs, errs, labels = get_time_budgets_data( E, level, err_type, cycle=cycle, days=days) all_avgs[:, d, c, :], all_errs[:, d, c, :] = avgs, errs idx = [0, 2, 1, 3] all_avgs = all_avgs.reshape(-1, len(cycles), num_slices)[idx] all_errs = all_errs.reshape(-1, len(cycles), num_slices)[idx] # directory dirname = E.figures_dir_subpar + 'time_budgets/fig2/' if not os.path.isdir(dirname): os.makedirs(dirname) if level == 'strain': for c, cycle in enumerate(cycles): # fig_title = '' fig_title = 'Time budgets, %s\n%d strains avgs' %(cycle, E.num_strains) subtitles = ['%s: %s, %s' %(x, y, cycle) for y in use_days for x in E.strain_names] fig = draw_subplot(E, all_avgs[:, c, :], fig_title, subtitles, plot_type) fname = dirname + 'time_budgets_%s_%dstrains_%s' %(cycle, E.num_strains, plot_type) save_plot(fname, fig, ADD_SOURCE=ADD_SOURCE, xpad=.05, ypad=0) print "figures saved to: %s" %fname
def plot_explained_variance_ratio(experiment, X, pca, level, lastcomp, fname, EXCLUDE_SS): E = experiment components = pca.components_ num_components = pca.n_components_ expl_variance = pca.explained_variance_ratio_ figsize, nrows, ncols, _, _ = get_subplot_specs(E, num_subplots=2) fig, (ax0, ax1) = plt.subplots(nrows=nrows, ncols=ncols, figsize=figsize) ax0.plot(range(len(components)), expl_variance, color='.4') ax1.plot(range(len(components))[-lastcomp:], expl_variance[-lastcomp:], color='.4') ax0.set_ylim([0, .35]) ax1.set_ylim([0, .0006]) ax1.xaxis.set_major_locator(MultipleLocator(1)) for ax in [ax0, ax1]: ax.xaxis.set_major_formatter(FormatStrFormatter('%d')) ax_cleanup(ax) # annotate close-up text = 'close up,\nlast %d components' % lastcomp ax1.text(.5, .7, text, fontsize=8, transform=ax1.transAxes) text = '%d strains, ' %E.num_strains if not EXCLUDE_SS \ else '%d strains (no AKR, CAST, CZECH), ' %(E.num_strains-3) level_ = 'mice' if level == 'mouse' else level fig_title = 'Explained variance ratio, %d principal components\n%s%d %s, 24H avg data' % ( num_components, text, X.shape[0], level_) subplot_labels(E, fig, xlabel='Principal component', ylabel='explained variance', fig_title=fig_title) plt.subplots_adjust(bottom=.15, wspace=.4) save_plot(fname, fig)
def plot_features_panel_DC_LC(experiment, level='group', bin_type='3cycles', err_type='sem', plot_type='features', ADD_SOURCE=True): E = experiment print "%s, level: %s, bin_type: %s, err_type: %s, days: %s" % ( plot_features_panel_DC_LC.__name__, level, bin_type, err_type, E.daysToUse) features = E.features_by_activity num_features = len(features) days_to_use = E.daysToUse dirname = E.figures_dir + '%s/vectors/panels_expdays/%s/%s_days/' % ( plot_type, bin_type, E.use_days) if not os.path.isdir(dirname): os.makedirs(dirname) fname = dirname + '%s_panel_expdays_DC_LC_group_%s' % (plot_type, err_type) # groups, features, days, cycles, avg/err data = E.generate_feature_vectors_expdays(features, level, bin_type, err_type) new_data = data[:, :, :, 1:, :] figsize = (14.4, 4.8) nrows, ncols = 4, 7 fig, axes = plt.subplots(nrows, ncols, figsize=figsize, sharex=True) xs = days_to_use cnt = 0 for n in xrange(nrows): for m in xrange(ncols): ax = axes.flatten()[n * ncols + m] if n == 0 and m >= 3: ax.axis('off') continue feature = features[cnt] # get colors if feature.startswith('AS'): color1, color2 = [E.fcolors['AS'].values()[x] for x in [1, 3]] elif feature.startswith('T'): color1, color2 = [ E.fcolors[feature[1:]].values()[x] for x in [1, 3] ] else: color1, color2 = [ E.fcolors[feature[:1]].values()[x] for x in [1, 3] ] colors = ['.4', '.7', color1, color2] subtitle = '%s %s' % (feature, E.plot_settings_dict[feature]['unit']) for g in xrange(E.num_strains): tkw = {'fmt': 'o-', 'ms': 2, 'elinewidth': .5, 'capsize': 1} # DC mec = '0' if g == 0 else colors[2 * g] ax.errorbar(xs, new_data[g, cnt, :, 0, 0], yerr=new_data[g, cnt, :, 0, 1], color=colors[2 * g], mec=mec, **tkw) #LC mc = '0' if g == 0 else colors[2 * g + 1] ax.errorbar(xs, new_data[g, cnt, :, 1, 0], yerr=new_data[g, cnt, :, 1, 1], color=colors[2 * g + 1], mec=mec, **tkw) if E.short_name == 'HFD2': d_day = E.dietChangeDayNumbers[0] ax.axvspan(xmin=d_day, xmax=days_to_use[-1], color='.9', zorder=0) xlims = ax.get_xlim() ax.set_xlim((4, xlims[1])) ax.set_ylim([0, ax.get_ylim()[1]]) ax_cleanup(ax) ax.set_title(subtitle, fontsize=10) cnt += 1 fig.text(.6, .9, '0: %s, control (grayscale)\nDC:black, LC: gray' % E.strain_names[0], fontsize=8) fig.text(.6, .83, '1: %s, knock-out (colors)\nDC: dark, LC: light ' % E.strain_names[1], fontsize=8) fig.text(.6, .78, 'gray background: diet change', fontsize=8) xlabel = 'Experiment Day' add_xylabels(fig, xlabel=xlabel, xypad=-.02, labelsize=10) days_string = E.get_days_to_use_text() fig_title = '%s Experiment\nFeatures, DC vs. LC, %s avg and %s\nacross %s days: %s' % ( E.short_name, level, err_type, E.use_days.replace( '_', '-').title(), days_string) add_titles_notes(E, fig, title=fig_title) plt.subplots_adjust(hspace=.6, wspace=.34) save_plot(fname, fig, ADD_SOURCE=ADD_SOURCE, sypad=-.02)
def plot_features_panel_12bins(experiment, level='group', bin_type='12bins', err_type='sem', plot_type='features', ADD_SOURCE=True): E = experiment print "%s, level: %s, bin_type: %s, err_type: %s, days: %s" % ( plot_features_panel_12bins.__name__, level, bin_type, err_type, E.daysToUse) features = E.features_by_activity num_features = len(features) days_to_use = E.daysToUse num_bins = int(bin_type.strip('bins')) tbins = my_utils.get_tbins_string(bin_type) dirname = E.figures_dir + '%s/vectors/panels_expdays/%s/%s_days/' % ( plot_type, bin_type, E.use_days) if not os.path.isdir(dirname): os.makedirs(dirname) data = E.generate_feature_vectors_expdays(features, level, bin_type, err_type) ymaxs = get_ymaxs(data) # stop for b in xrange(num_bins): new_data = data[:, :, :, b, :] figsize = (14.4, 4.8) nrows, ncols = 4, 7 fig, axes = plt.subplots(nrows, ncols, figsize=figsize, sharex=True) xs = days_to_use cnt = 0 for n in xrange(nrows): for m in xrange(ncols): ax = axes.flatten()[n * ncols + m] if n == 0 and m >= 3: ax.axis('off') continue feature = features[cnt] colors = get_two_group_features_colors(E, feature) subtitle = '%s %s' % (feature, E.plot_settings_dict[feature]['unit']) for g in xrange(E.num_strains): tkw = { 'fmt': 'o-', 'ms': 2, 'elinewidth': .5, 'capsize': 1 } ax.errorbar(xs, new_data[g, cnt, :, 0], yerr=new_data[g, cnt, :, 1], color=colors[g], mec=colors[g], **tkw) if E.short_name == 'HFD2': d_day = E.dietChangeDayNumbers[0] ax.axvspan(xmin=d_day, xmax=days_to_use[-1], color='.9', zorder=0) # xmin, xmax = ax.get_xlim() # ax.set_xlim((xmin-.5, xmax+.5)) # ax.set_ylim([0, ymaxs[cnt]]) ax_cleanup(ax) ax.set_title(subtitle, fontsize=10) cnt += 1 xmin, xmax = ax.get_xlim() ax.set_xlim((xmin - .5, xmax + .5)) fig.text(.6, .9, '0: %s, control, %s (grayscale)' % (E.strain_names[0], tbins[b]), fontsize=8) fig.text(.6, .85, '1: %s, knock-out, %s (colors)' % (E.strain_names[1], tbins[b]), fontsize=8) fig.text(.6, .8, 'gray background: diet change', fontsize=8) xlabel = 'Experiment Day' add_xylabels(fig, xlabel=xlabel, xypad=-.02, labelsize=10) days_string = E.get_days_to_use_text() fig_title = '%s Experiment\nFeatures, %s %s avg$\pm$%s, %s\nacross %s days: %s' % ( E.short_name, bin_type, level, err_type, tbins[b], E.use_days.replace('_', '-').title(), days_string) add_titles_notes(E, fig, title=fig_title) plt.subplots_adjust(hspace=.6, wspace=.34) fname = dirname + '%s_panel_expdays_%s_group_%s_bin%d' % ( plot_type, bin_type, err_type, b) save_plot(fname, fig, ADD_SOURCE=ADD_SOURCE, sypad=-.02)
def draw_group_features_days_collapse(E, data, act, features, bin_type, err_type, fname, plot_type='features', ADD_SOURCE=False): figsize = (17.6, 2.4) nrows, ncols = E.num_strains, len(features) fig, axes = plt.subplots(nrows, ncols, figsize=figsize, sharex=True) other_color = E.fcolors['other'][0] xticks, xlabels = get_CT_ticks_labels(bin_type='12bins', SHIFT=E.BIN_SHIFT, tshift=E.binTimeShift) xs = xticks[:-1] + 1 ymaxs = get_ymaxs(data) cnt = 0 for n in xrange(nrows): for m in xrange(ncols): ax = axes.flatten()[cnt] feature = features[m] subtitle = '%s %s' % (feature, E.plot_settings_dict[feature]['unit']) # idx = [0, 1, 2, 3] # colors = [E.fcolors['AS'].values()[x] for x in idx] if m < 3 else [E.fcolors['F'].values()[x] for x in idx] colors = E.fcolors['AS'].values( ) if m < 3 else E.fcolors[act].values() colors[0] = '.4' colors[3] = '.7' zord = [0, 1, 2, 0] if bin_type.endswith('bins'): tkw = {'fmt': 'o-', 'ms': 2, 'elinewidth': .5, 'capsize': 1} for d in xrange(len(E.daysToUse)): ax.errorbar(xs, data[n, d, m, :, 0], yerr=data[n, d, m, :, 1], color=colors[d], mec=colors[d], label='day%d' % E.daysToUse[d], zorder=zord[d], **tkw) else: stop # same y-axis, per feature ax.set_ylim([0, ymaxs[m]]) set_axis_layout(E, ax, bin_type) if m < 1: texts = [ '0: %s\ncontrol' % E.strain_names[0], '1: %s\nknock-out' % E.strain_names[1] ] bbox = ax.get_position() fig.text(.06, bbox.y1 - (bbox.y1 - bbox.y0) / 2., texts[n], ha='left', va='center', fontsize=10) if n < 1: # plot subtitle ax.set_title(subtitle, fontsize=10, y=1.05) # legend if m in [0, 3]: # legend ltkw = { 'numpoints': 1, 'bbox_to_anchor': [.25, 2, .1, .05], 'fontsize': 6, 'handletextpad': .8, 'labelspacing': .3, 'borderaxespad': .5, 'frameon': False } ax.legend(**ltkw) cnt += 1 set_panel_layout(E, fig, err_type, tbin_type='12bins') save_plot(fname, fig, ADD_SOURCE=ADD_SOURCE, sypad=-.15) plt.close()
def draw_subplot(experiment, data, labels, data_rescaled, fname, act='F', level='mouse', sub_type='line', plot_type='ingestion', ADD_SOURCE=False): E = experiment i_act = 0 if act == 'F' else 1 units = ['mg/s', 'g', 'min'] # var_names = [E.HCM_variables[x][i_act] for x in var_types] varTypes = ['coeffs', 'tots', 'durs'] varNames = [E.HCM_derived['events'][plot_type][x][0] for x in varTypes] m_labels = np.unique(labels[:, 1]) figsize, nrows, ncols, sharex, sharey = get_subplot_specs( num_subplots=len(m_labels)) fig, axes = plt.subplots(nrows, ncols, figsize=figsize, sharex=sharex, sharey=sharey) colors = [E.fcolors[act].values()[x] for x in [1, 0, 2]] title, subtitles = get_figure_titles(E, labels, act=act, plot_type=plot_type) hls = [] for m, mouse in enumerate(m_labels): try: ax = axes.flatten()[m] idx = labels[:, 1] == mouse arr = data_rescaled[idx] if sub_type == 'line': for k, var in enumerate(varNames): ax.plot(arr[:, k], lw=.5, color=colors[k], label=var) # ax.axhline(y=arr.mean()[k], c='grey', alpha='.5', label='') # stop make_annotation(ax, arr, data, k, idx, colors, units) elif sub_type == 'bar': pass # bar_width = .2 # for k, var in enumerate(varNames): # ind = np.arange(len(arr)) + k * bar_width -.1 # tkw = {'lw':.2, 'label':var, # 'color':colors[k], 'edgecolor':None, # } # ax.bar(ind, arr[:, k], bar_width, **tkw) set_layout(E, ax) ax.set_title(subtitles[m], fontsize=10) if m == 0: h, l = ax.get_legend_handles_labels() except IndexError: ax.axis('off') continue # legend tkw = { 'ncol': 3, 'fontsize': 8, 'bbox_to_anchor': [0.85, .08], 'frameon': False } legend = fig.legend(h, l, **tkw) for label in legend.get_lines(): label.set_linewidth(3) # the legend line width # set subplot labels xlabel = 'Experiment Day' ylabel = '%s Coefficient' % act add_xylabels(fig, xlabel, ylabel) #, xypad=0, yxpad=0, labelsize=10) add_titles_notes( E, fig, title=title, # typad=typad, # tlxpad=tlxpad, # tlypad=typad ) plt.subplots_adjust(bottom=.12, hspace=0.6, wspace=0.4) save_plot(fname, fig, ADD_SOURCE=ADD_SOURCE) #, sypad=-.05)
def draw_histogram_plot(E, mouse_data, arr_preFast, arr_postFast, mouseNumbers, fname, plot_type, ADD_SOURCE): # ZeroLight is one group only # for m in xrange(num_mice): # data = mouse_data[m] # label = mouseNumbers[m] # data_pre, data_post = arr_preFast[m], arr_postFast[m] # stop # i_act = 0 if act == 'F' else 1 units = ['mg/s', 'g', 'min'] # var_names = [E.HCM_variables[x][i_act] for x in var_types] varTypes = ['coeffs', 'tots', 'durs'] varNames = [E.HCM_derived['events'][plot_type][x][0] for x in varTypes] num_mice = len(mouseNumbers) figsize = (12.8, 3.6) nrows, ncols = len(varNames), num_mice fig, axes = plt.subplots(nrows, ncols, figsize=figsize, sharex=True, sharey=False) colors = [E.fcolors['F'].values()[x] for x in [1, 0, 2]] # title, subtitles = get_figure_titles(E, labels, act=act, plot_type=plot_type) hls = [] cnt = 0 for m in xrange(nrows): # FC, FT, FD data = mouse_data[:, :, m] pre, post = arr_preFast[:, m], arr_postFast[:, m] for n in xrange(ncols): # mouseNumbers ax = axes.flatten()[cnt] # plot quantity across days for each mouse ax.plot(data[n, :], lw=.5, color=colors[m]) if m == 0: xmin, xmax = ax.get_xlim() ax.axhline(xmin=xmin, xmax=xmax, y=data[n].mean(0), linestyle='-', color=colors[m], zorder=0, label='average FC - up to day 35 value') ax.axhline(xmin=xmin, xmax=xmax, y=pre[n], linestyle='--', color='g', zorder=1, label='day%d, FC 4h-preFast value' % E.fastDayNumbers[0]) ax.axhline(xmin=xmin, xmax=xmax, y=post[n], linestyle=':', color='r', zorder=2, label='day%d FC 1h-postFast value' % E.fastDayNumbers[0]) ax.set_title('M%d' % mouseNumbers[n], fontsize=10) if n == 0: h, l = ax.get_legend_handles_labels() if n == 0: ax.set_ylabel('%s [%s]' % (varNames[m], units[m]), fontsize=10) ax.set_ylim([.9 * data.min(), 1.1 * data.max()]) set_layout2(E, ax, m, n) cnt += 1 # legend tkw = {'fontsize': 8, 'bbox_to_anchor': [0.8, .15], 'frameon': False} legend = fig.legend(h, l, **tkw) for label in legend.get_lines(): label.set_linewidth(3) # the legend line width # set subplot labels xlabel = 'Experiment Day' add_xylabels(fig, xlabel) add_titles_notes( E, fig, title='F-Coefficient, F-Total Amounts, F-Total PhotoBeam BreakTime') plt.subplots_adjust(bottom=.12) #, hspace=0.6, wspace=0.4) save_plot(fname, fig, ADD_SOURCE=ADD_SOURCE, sypad=-.03)
def plot_loadings(experiment, X, pca_components, feature_names, level, comps_idx, fname, plot_type, EXCLUDE_SS, ADD_SOURCE=True): E = experiment num_items = X.shape[0] num_components = len(pca_components) num_features = len(feature_names) assert num_features == num_components, 'wtf' # select components selected_comps = pca_components[comps_idx] fig, ax = plt.subplots(figsize=(7, 3)) bar_width = .03 if len(comps_idx) == num_components else .1 colors = [E.plot_settings_dict[feat]['color'] for feat in feature_names] if plot_type == 'bar': for c, comp in enumerate(selected_comps): ind = np.arange(num_features) + c * bar_width alpha_step = .03 * comp if len( comps_idx) == num_components else .2 * comp tkw = { 'lw': .2, 'alpha': (1 - alpha_step), 'color': colors, 'edgecolor': None, 'label': 'PC%d' % comp } ax.bar(ind, pca_components[-(comp + 1)], bar_width, **tkw) elif plot_type == 'line': colors = get_16_colors()[1::4] tkw = { 'numpoints': 1, 'fontsize': 6, 'handletextpad': 1.2, 'labelspacing': .8, 'borderaxespad': 1.5, 'frameon': False, 'bbox_to_anchor': (1., 1.2), 'bbox_transform': ax.transAxes } for c, comp in enumerate(selected_comps): ax.plot(comp, color=colors[c], label='comp%d' % (comps_idx[c])) leg = ax.legend(**tkw) ax.set_xticks(range(num_features)) ax.set_xticklabels([]) ax.set_ylim(-1, 1) ax.axhline(xmin=0, xmax=num_features, lw=.5, color='k') ax.spines['bottom'].set_position('zero') ax.spines['bottom'].set_visible(False) ax_cleanup(ax) # display feature names on top of bars xpos = np.arange(num_features) + .2 heights = selected_comps.max(axis=0) + .04 heights[5] = heights[4] + .05 # correct FBASR if plot_type == 'line': heights += .1 for p, feat in enumerate(feature_names): ax.text(xpos[p], heights[p], feat, fontsize=6, ha='center', transform=ax.transData) # annotate if plot_type == 'hist': annotation = 'Color-code by feature type.\n' \ + 'AS:purple, Feeding:orange, Drinking:blue, Move:green.\n' \ + 'For each feature, components from %d (opaque) to\n' %comps_idx[0] \ + '%dth (transparent) are shown on a sliding\ntransparency scale.' %comps_idx[-1] ax.text(13.8, ax.get_ylim()[0], annotation, fontsize=6, va='center', transform=ax.transData) # title text = '%d strains, ' %E.num_strains if not EXCLUDE_SS \ else '%d strains (no AKR, CAST, CZECH), ' %(E.num_strains-3) level_ = 'mice' if level == 'mouse' else level fig_title = 'Principal Component loadings, components: %s of %d total\n%s%d %s, 24H avg data\n%s days:%dto%d' % ( comps_idx, num_components, text, num_items, level_, E.use_days, E.daysToUse[0], E.daysToUse[-1]) subplot_labels(E, fig, xlabel='', ylabel='Loading', fig_title=fig_title) save_plot(fname, fig, ADD_SOURCE=ADD_SOURCE)
def plot_component_loadings(E, X, pca_components, feature_names, level, fname, EXCLUDE_SS=False, BY_STRAIN=False, strain=None, ADD_SOURCE=True): num_items = X.shape[0] num_components = len(pca_components) num_features = len(feature_names) figsize, nrows, ncols, sharex, sharey = get_subplot_specs( E, num_subplots=num_components) fig, axes = plt.subplots(nrows, ncols, figsize=figsize, sharex=sharex, sharey=sharey) xs = range(1, num_components + 1) for c, comp in enumerate(pca_components): ax = axes.flatten()[c] ax.plot(xs, comp, color='.4') ax.set_xlim(0, ax.get_xlim()[1]) ax.set_xticks(range(num_features)) ax.set_xticklabels([]) ax.set_title('PC%d' % c, fontsize=8, position=(.5, 1.15), ha='center') ax.axhline(xmin=0, xmax=num_features, lw=.5, color='k') ax.spines['bottom'].set_position('zero') ax.spines['bottom'].set_visible(False) ax_cleanup(ax) # display feature names on top heights = list(np.linspace(1.05, .55, 4)) * 8 for p, feat in enumerate(feature_names): ax.text(xs[p], heights[p], feat, fontsize=4, ha='center', transform=ax.transData) ax.axvline(x=xs[p], ymin=.4, ymax=heights[p], lw=.2, color='.5') # title text = '%d strains,' %E.num_strains if not EXCLUDE_SS \ else '%d strains (no AKR, CAST, CZECH),' %(E.num_strains-3) level_ = 'mice' if level == 'mouse' else level fig_title = 'Principal Component loadings, %d components\n' %num_components \ + '%s %d %s, 24H avg data\n%s days:%dto%d' %( text, num_items, level_, E.use_days, E.daysToUse[0], E.daysToUse[-1]) if BY_STRAIN: fig_title = 'Principal Component loadings, %d components\n' %num_components \ + '%s %d %s, 24H avg data\ngroup%d: %s\n%s days:%dto%d' %( text, num_items, level_, strain, E.strain_names[strain], E.use_days, E.daysToUse[0], E.daysToUse[-1]) subplot_labels(E, fig, xlabel='', ylabel='Loading', fig_title=fig_title) plt.subplots_adjust(hspace=.4, wspace=.3) save_plot(fname, fig, ADD_SOURCE=ADD_SOURCE)
def plot_features_panel_LC_DC_ratio(experiment, level='group', bin_type='3cycles', err_type='sem', plot_type='features', ADD_SOURCE=True): E = experiment print "%s, level: %s, bin_type: %s, err_type: %s, days: %s" % ( plot_features_panel_LC_DC_ratio.__name__, level, bin_type, err_type, E.daysToUse) features = E.features_by_activity num_features = len(features) days_to_use = E.daysToUse dirname = E.figures_dir + '%s/vectors/panels_expdays/%s/%s_days/' % ( plot_type, bin_type, E.use_days) if not os.path.isdir(dirname): os.makedirs(dirname) fname = dirname + '%s_panel_expdays_LC_DC_ratio' % (plot_type ) #s, err_type) # using mouseday value # ratios = E.generate_feature_vectors_LC_DC_ratio_expdays(features, level, bin_type, err_type) # using group averages value data_ = E.generate_feature_vectors_expdays(features, level, bin_type, err_type) ratios_ = data_[:, :, :, 2, 0] / data_[:, :, :, 1, 0] # LC/DC, avgs figsize = (14.4, 4.8) nrows, ncols = 4, 7 fig, axes = plt.subplots(nrows, ncols, figsize=figsize, sharex=True) xs = days_to_use cnt = 0 for n in xrange(nrows): for m in xrange(ncols): ax = axes.flatten()[n * ncols + m] if n == 0 and m >= 3: ax.axis('off') continue feature = features[cnt] colors = get_two_group_features_colors(E, feature) subtitle = '%s %s' % (feature, E.plot_settings_dict[feature]['unit']) for g in xrange(E.num_strains): # # using mouseday values # tkw = {'fmt':'o-', 'ms':2, 'elinewidth':.5, 'capsize':1} # ax.errorbar(xs, ratios[g, cnt, :, 0], yerr=ratios[g, cnt, :, 1], # color=colors[g], mec=colors[g], **tkw) # using group averages value tkw = {'marker': 'o', 'ms': 2, 'zorder': 0} ax.plot(xs, ratios_[g, cnt, :], color=colors[g], mec=colors[g], **tkw) # use when plotting all for comparison # colors_ = ['r', 'y'] # ax.plot(xs, ratios_[g, cnt, :], color=colors_[g], mec=colors_[g], **tkw) if E.short_name == 'HFD2': d_day = E.dietChangeDayNumbers[0] ax.axvspan(xmin=d_day, xmax=days_to_use[-1], color='.9', zorder=0) xlims = ax.get_xlim() ax.set_xlim((4, xlims[1])) ax.set_ylim((0, ax.get_ylim()[1])) ax_cleanup(ax) ax.set_title(subtitle, fontsize=10) cnt += 1 fig.text(.6, .9, '0: %s, control, 24H (grayscale)' % E.strain_names[0], fontsize=8) fig.text(.6, .85, '1: %s, knock-out, 24H (colors)' % E.strain_names[1], fontsize=8) fig.text(.6, .8, 'gray background: diet change', fontsize=8) xlabel = 'Experiment Day' add_xylabels(fig, xlabel=xlabel, xypad=-.02, labelsize=10) days_string = E.get_days_to_use_text() fig_title = '%s Experiment\nFeatures vs days, LC/DC ratio %s avg$\pm$%s\nacross %s days: %s' % ( E.short_name, level, err_type, E.use_days.replace( '_', '-').title(), days_string) add_titles_notes(E, fig, title=fig_title) plt.subplots_adjust(hspace=.6, wspace=.34) save_plot(fname, fig, ADD_SOURCE=ADD_SOURCE, sypad=-.02)
def plot_raster_groups(E, group_list, bin_type='12bins', SHOW_DAYS=True, plot_type='raster', ADD_SOURCE=True): """ does not plot ignored mice/mousedays """ dirname_out = E.figures_dir + '%ss/%s/group/%s_days/' %(plot_type, bin_type, E.use_days) if not os.path.isdir(dirname_out): os.makedirs(dirname_out) print "%s, %s days.." %(plot_raster_groups.__name__, E.use_days) y_sep = 10 for strain in group_list: group = E.get_group_object(groupNumber=strain) num_mice = len(group.count_mice()[0]) # mice ok if num_mice > 12 and num_mice <=16: nrows, ncols = (4,4) elif num_mice > 8 and num_mice <=12: nrows, ncols = (3, 4) figsize = (12.8, 6.4) fig, axes = plt.subplots(nrows, ncols, figsize=figsize) m = 0 # mouse counter for mouse in group.individuals: ax = axes.flatten()[m] if mouse.ignored: print mouse, 'excluded' ax.text(.5, .6, 'M%d\nexcluded' %mouse.mouseNumber, fontsize=12, color='.5', ha='center', va='center') ax.axis('off') else: cnt = 0 for MD in mouse.mouse_days: if MD.dayNumber in E.daysToUse: y_offset = y_sep * (-cnt) if MD.ignored: print MD, 'excluded' ax.text(18, y_offset-5, 'D%d excluded' %MD.dayNumber, fontsize=8, color='.5', ha='center', va='center') ax.axis('off') else: print MD plot_events(MD, fig, ax, y_offset) if SHOW_DAYS: if m%4 == 0: show_days(MD, ax, y_offset, labelsize=8) cnt += 1 # subtitle ax.set_title('M%d' %mouse.mouseNumber, y=1.1, fontsize=10) set_raster_layout(fig, ax, num_days=len(E.daysToUse)), add_DC_rectangle_to_raster(ax, ypos=5, height=1.5) m += 1 remove_axes_not_used(group, axes, nrows, ncols, m) add_titles_notes(E, fig, title=group.get_figtitle()) plt.subplots_adjust(hspace=0.4) print "saving.." fname = dirname_out + '%s_group%d' %(plot_type, group.number) save_plot(fname, fig, ADD_SOURCE=ADD_SOURCE, sypad=.03)
def plot_events(MD, fname, plot_type, bin_type='12bins', FLAG_IGNORED=False): E = MD.experiment varNames, colors, offsets, heights, labels, label_offsets = \ get_settings_and_annotations(MD) figsize = (12., 3.6) fig, ax = plt.subplots(figsize=figsize) other_color = E.fcolors['other'][0] c = 0 for tup in zip(varNames, colors, offsets, heights, labels, label_offsets): name, color, offset, height, label, label_offset = tup events = MD.load(name) / 3600. - 7 # why here did I use -6.5 ?? if name in ['CT_out_HB', 'CT_at_HB']: ax.scatter(events, offset * np.ones(events.shape[0]), c=color, marker='|', s=150, lw=0.01, edgecolor=None) else: for x in events: event_patch = patches.Rectangle( (x[0], offset), x[1] - x[0], height, # xy lower left corner, width, height lw=0.001, fc=color, ec=color) ax.add_patch(event_patch) if name in [ 'AS_timeSet', 'FB_timeSet', 'WB_timeSet', 'MB_timeSet' ]: print_duration(ax, events, offset, name, color) ax.text(4.5, label_offset, label, color=color, ha='right', va='center', fontsize=8, clip_on=False) set_raster_layout(fig, ax, num_days=len(E.daysToUse), bin_type=bin_type, SHIFT=E.BIN_SHIFT, tshift=E.binTimeShift) add_DC_rectangle_to_raster(ax, ypos=-.3, height=.3) add_titles_notes( E, fig, title=MD.get_figtitle() + ', %s' % bin_type, TL_NOTE=True, ) if MD.ignored: fig.text(.3, 1.02, 'MD excluded', fontsize=18, color='.5', ha='right', va='bottom', transform=ax.transAxes) # begin/end fast if E.short_name == '2CFast': if MD.dayNumber in E.fastDayNumbers + E.reFeedDayNumbers: text = '"FAST"' if MD.dayNumber in E.fastDayNumbers else '"REFEED"' fig.text(.15, 1.05, text, fontsize=18, color=other_color, ha='left', va='bottom', transform=ax.transAxes) show_fast_times(E, ax, day_num=MD.dayNumber, TEXT=True, color=other_color) print "saving.." save_plot(fname, fig, ADD_SOURCE=True)
def draw_position_density_tbins2(E, data, mouseNumbers, tbin_type, err_type, xbins, ybins, fig_title, fname, rect_HB=None, obs_rect=None, plot_type='position_density', ADD_SOURCE=False): C = Cage() # figure figsize = (6.4, 6.4) nrows, ncols = data.shape[0], data.shape[1] fig, axes = plt.subplots(nrows, ncols, figsize=figsize) cmap = plt.get_cmap("viridis") vmin, vmax = .0001, 1. if (xbins, ybins) == (2, 4): vmin = 0.01 extent = [C.CMXLower, C.CMXUpper, C.CMYLower, C.CMYUpper] percent_time_color = E.fcolors['other'][0] row_labels = ['M%d' % m for m in mouseNumbers] column_labels = ['D%d' % d for d in E.daysToUse] for r in xrange(nrows): # display row labels top, bottom, left, right = [ getattr(fig.subplotpars, x) for x in ['top', 'bottom', 'left', 'right'] ] yy = top - .025 - (top - bottom) * r / nrows fig.text(left - .1, yy, row_labels[r], va='center', fontsize=8) for c in xrange(ncols): # display column labels if r < 1: xx = left + .02 + (right - left) * c / ncols fig.text(xx, top + .02, column_labels[c], ha='center', fontsize=8) try: ax = axes[r, c] if type( axes) is np.ndarray else axes # when just one axis Z3 = data[r, c, :, :, 0] # plt average only for the moment if np.isnan(Z3).all(): ax.axis('off') else: Z3_ = Z3.copy() Z3_[Z3 < 1e-4] = 1e-4 # round small numbers to almost zero for plotting im = ax.imshow(Z3_, interpolation='nearest', cmap=cmap, norm=LogNorm(vmin=vmin, vmax=vmax)) #, extent=extent) set_position_density_layout(fig, ax, im) if (xbins, ybins) == (2, 4): draw_homebase_star(ax, rect_HB[r, c], color=percent_time_color) if r * c < 1: hh, ll = ax.get_legend_handles_labels() except IndexError: ax.axis('off') continue set_colorbar(fig, ax, im) set_legend(fig, hh, ll, xbins, ybins, text_color=percent_time_color) add_titles_notes(E, fig, title=fig_title, titlesize=14, typad=.08, TL_NOTE=False) plt.subplots_adjust(hspace=.2, wspace=.05) save_plot(fname, fig, ADD_SOURCE=ADD_SOURCE, sypad=.03)
def draw_position_density_tbins(E, data, labels, tbin_type, level, err_type, xbins, ybins, fname, rect_HB=None, obs_rect=None, plot_type='position_density', ADD_SOURCE=False): C = Cage() # figure figsize, nrows, ncols = get_subplot_specs(E, num_subplots=data.shape[0], plot_type=plot_type, sub_type=tbin_type) fig, axes = plt.subplots(nrows, ncols, figsize=figsize) cmap = plt.get_cmap("viridis") vmin, vmax = .0001, 1. if (xbins, ybins) == (2, 4): vmin = 0.01 extent = [C.CMXLower, C.CMXUpper, C.CMYLower, C.CMYUpper] percent_time_color = E.fcolors['other'][0] title, subtitles = get_figure_titles(E, labels=labels, level=level, tbin_type=tbin_type, err_type=err_type, plot_type=plot_type) data_ = data.swapaxes(0, 1) arr = my_utils.get_CT_bins( bin_type=tbin_type) / 3600 - 7 # CT in hours. num_tbins=arr.shape[0] row_labels = ['CT%d-%d' % (row[0], row[1]) for row in arr] column_labels = subtitles for r in xrange(nrows): # row labels top, bottom, left, right = [ getattr(fig.subplotpars, x) for x in ['top', 'bottom', 'left', 'right'] ] yy = top - .03 - (top - bottom) * r / nrows fig.text(left - .1, yy, row_labels[r], va='center', fontsize=8) for c in xrange(ncols): # column labels if r < 1: xx = left + .01 + (right - left) * c / ncols fig.text(xx, top + .03, column_labels[c], fontsize=8) bin_data = data_[r, c, :, :] try: ax = axes[r, c] if type( axes) is np.ndarray else axes # when just one axis Z3 = bin_data[:, :, 0] # plt average only for the moment if np.isnan(Z3).all(): # ax.text(.5, .5, subtitles[r] + ' excluded', # fontsize=12, color='.5', ha='center', va='center') ax.axis('off') else: Z3_ = Z3.copy() Z3_[Z3 < 1e-4] = 1e-4 # round small numbers to almost zero for plotting im = ax.imshow(Z3_, interpolation='nearest', cmap=cmap, norm=LogNorm(vmin=vmin, vmax=vmax)) #, extent=extent) # ax.set_title(subtitles[c]) set_position_density_layout(fig, ax, im) if (xbins, ybins) == (2, 4): draw_homebase_star(ax, rect_HB[c], color=percent_time_color) if r * c < 1: hh, ll = ax.get_legend_handles_labels() except IndexError: ax.axis('off') continue set_colorbar(fig, ax, im) set_legend(fig, hh, ll, xbins, ybins, text_color=percent_time_color) typad = .15 #if level == 'group' else 0 add_titles_notes(E, fig, title=title, typad=typad, titlesize=14, TL_NOTE=False) plt.subplots_adjust(hspace=.2, wspace=.05) sypad = -.05 if level == 'group' else .05 save_plot(fname, fig, ADD_SOURCE=ADD_SOURCE, sypad=sypad)
def plot_HCM_system_time(E, ttype='maintenance', ADD_SOURCE=True): """plots system_on_off """ if ttype == 'maintenance': HCM_time, labels = E.get_HCM_maintenance_time() xlims = [2, 8] xticks = range(2, 10+1, 2) xticklabels = xticks elif ttype == 'recording': HCM_time, labels = E.get_HCM_recording_time() xlims = [2, 34] xticks = range(4, 32+1, 4) xticklabels = [str(x) for x in range(4, 24+1, 4)] \ + [str(x) for x in range(4, 10+1, 4)] print "%s, %s days.." %(plot_HCM_system_time.__name__, E.use_days) figsize, nrows, ncols, sharex, sharey = \ get_subplot_specs(E, num_subplots=len(E.groups), plot_type='subplot') fig, axes = plt.subplots(nrows, ncols, figsize=figsize, sharex=sharex, sharey=sharey) for strain in range(nrows * ncols): ax = axes.flatten()[strain] if type(axes) == np.ndarray else axes idx = labels [:, 0] == strain data = HCM_time[idx] / 3600. - 7 c = 0 for row in data: ax.plot([row[0], row[1]], [c, c], lw=0.5, color='0.5') c += 1 ax.set_xlim(xlims) ax.set_xticks(xticks) ax.set_xticklabels(xticklabels) if ttype == 'maintenance': text = 'avg:\n%1.1fmin' %(np.diff(data).mean() * 60) elif ttype == 'recording': text = 'avg:\n%1.2fhrs' %np.diff(data).mean() ax.axvline(x=12, linestyle='--', color='k') ax.axvline(x=24, linestyle='--', color='k') ax.text(.9, .9, text, fontsize=10, ha='center', transform=ax.transAxes) ax.set_xlabel('Circadian Time') ax.set_ylabel('Obs. days', labelpad=10) ax.set_title('group%d: %s' %(strain, E.strain_names[strain]), y=1.05) ax_cleanup(ax, labelsize=10) title = '%sExp\n%s days\nDaily %s Time' %( E.short_name, E.use_days.replace('_', '-').title(), ttype.title()) add_titles_notes(E, fig, title=title, typad=.18, tlxpad=-.1, tlypad=.15, HP_TEXT=False) plt.subplots_adjust(wspace=0.4) # save dirname_out = E.figures_dir + 'HCM_recording_time/%s_days/' %E.use_days if not os.path.isdir(dirname_out): os.makedirs(dirname_out) fname = dirname_out + 'HCMsystem_%s_time_%s_days' %(ttype, E.use_days) save_plot(fname, fig, ADD_SOURCE=ADD_SOURCE, sypad=-.1)
def plot_within_AS_structure(experiment, level='strain', EARLY=True, num_mins=15, days=None, cycle='24H', ADD_SOURCE=True): #, s_start=0): E = experiment print "%s, level: %s, EARLY: %s, %s" % (plot_within_AS_structure.__name__, level, EARLY, cycle) if EARLY: print "first %d minutes" % num_mins text = 'full_AS' if not EARLY else 'first_%dmin' % num_mins labels = ['F', 'W', 'M', 'other'] colors = [E.fcolors[x][0] for x in labels] colors[3] = E.fcolors['other'][1] if level == 'strain': # dirname = E.figures_dir_subpar + 'within_AS/examples/' dirname = E.figures_dir_subpar + 'within_AS/%s_days/%s/%s/%s/' % ( E.use_days, level, cycle, text) if not os.path.isdir(dirname): os.makedirs(dirname) for group in E.groups: #[s_start:s_start+4]: print '%d: %s' % (group.number, group.name) mice = E.get_mouseNumbers_from_groupNumber(group.number) figsize, nrows, ncols, sharex, sharey = get_subplot_specs( E, num_subplots=len(mice)) fig, axes = plt.subplots(nrows, ncols, figsize=figsize, sharex=sharex, sharey=sharey) m = 0 for mouse in group.individuals: if not mouse.ignored: print mouse ax = axes.flatten()[m] plot_mouse_AS_structure(E, level, mouse, ax, colors, EARLY, num_mins, days, cycle) m += 1 remove_axes_not_used(group, axes, nrows, ncols, m) set_legend(fig, colors) title = '%s: %s, %s' % (group.name, E.use_days, cycle) fig.suptitle(title, y=1.03) fig_title = '' # fig_title = 'Within-AS structure, across %s\ngroup%d: %s\n%s_days: %d to %d' %( # cycle, group.number, E.strain_names[group.number], E.use_days, E.daysToUse[0], E.daysToUse[-1]) xlabel = 'Time from AS onset [min]' ylabel = 'AS sorted by duration' subplot_labels(E, fig, xlabel, ylabel, fig_title, txpad=-0.03, typad=.03) fname = dirname + 'within_AS_structure_strain%d_%s_%s' % ( group.number, text, cycle) save_plot(fname, fig, ADD_SOURCE=ADD_SOURCE, ypad=-.04) elif level == 'mouse': for group in E.groups: #[s_start:s_start+4]: print '%d: %s' % (group.number, group.name) dirname = E.figures_dir_subpar + 'within_AS/%s_days/%s/%s/%s/strain%d/' % ( E.use_days, level, cycle, text, group.number) if not os.path.isdir(dirname): os.makedirs(dirname) for mouse in group.individuals: if not mouse.ignored: print mouse figsize = get_subplot_specs(E) fig, ax = plt.subplots(figsize=figsize) plot_mouse_AS_structure(E, level, mouse, ax, colors, EARLY, num_mins, days, cycle) fig_title = 'Within-AS structure, across %s\ngroup %d: %s\n%s_days: %d to %d' % ( cycle, group.number, E.strain_names[group.number], E.use_days, E.daysToUse[0], E.daysToUse[-1]) xlabel = 'Time from AS onset [min]' ylabel = 'AS sorted by duration' subplot_labels(E, fig, xlabel, ylabel, fig_title) if ADD_SOURCE: add_source(fig) fname = dirname + 'within_AS_structure_individual%d_%s_%s' % ( mouse.mouseNumber, text, cycle) save_plot(fname, fig)