def draw_subplot(experiment, avgs, fig_title, subtitles, plot_type): E = experiment figsize, nrows, ncols, _, _ = get_subplot_specs(E, num_subplots=4) labels = ['M', 'F', 'W', 'other', 'IS'] colors = [E.fcolors[x][0] for x in labels] fig, axes = plt.subplots(nrows, ncols, figsize=figsize) for c in xrange(avgs.shape[0]): ax = axes.flatten()[c] if plot_type == 'bar': stop elif plot_type == 'pie': plot_as_a_pie(ax, avgs[c], colors, labels, subtitles[c]) if c == 0: h, l = ax.get_legend_handles_labels() set_legend(fig, h, l) subplot_labels(E, fig, xlabel='', ylabel='', fig_title=fig_title, txpad=.1, typad=.03) plt.subplots_adjust(hspace=0.4, wspace=.1) return fig
def draw_subplot_compare(experiment, avgs, errs, fig_title, subtitles, ONSET=True, num_mins=15, tbin_size=5, ADD_SOURCE=False): E = experiment figsize, nrows, ncols, _, _ = get_subplot_specs(E, num_subplots=2) if E.num_strains == 2: pass # colors = [[get_16_colors()[x] for x in idx] for idx in [[2, 3, 8, 9], [0, 1, 14, 15]] elif E.num_strains == 4: colors = [[get_16_colors()[x] for x in idx] for idx in [[2, 3, 8, 9], [0, 1, 14, 15]]] elif E.num_strains == 16: colors = get_16_colors() # probability fig, axes = plt.subplots(nrows, ncols, figsize=figsize) every_tbins = 2 if num_mins > 5 else 1 xticklim = (0, 15) if ONSET else (-15, 0) xs = np.arange(xticklim[0], xticklim[1], tbin_size * every_tbins / 60.) k = 0 for act in ['F', 'W']: ax = axes[k] for c in xrange(avgs.shape[0]): # plotting every 5 tbins ax.errorbar(xs, avgs[c, ::every_tbins, k], yerr=errs[c, ::every_tbins, k], lw=.3, color=colors[k][c], label=E.strain_names[c], elinewidth=.5, capsize=.5, capthick=.2) set_compare_layout(E, ax, act, colors[k][c], ONSET, k, num_mins, tbin_size) set_compare_legend(ax, colors[k]) ax.set_title(subtitles[k], fontsize=10) k += 1 # set subplot labels on_text = 'from AS onset' if ONSET else 'to AS offset' xlabel = 'Time ' + on_text + ' [min]' ylabel = 'Probability' subplot_labels(fig, xlabel, ylabel, fig_title, ADD_SOURCE) plt.subplots_adjust(bottom=.12, hspace=0.6, wspace=0.3) return fig
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 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 draw_subplot1(experiment, all_avgs, all_errs, fig_title, subtitles, ONSET=True, num_mins=15, tbin_size=5): E = experiment act = ['F', 'W'] colors = [ E.fcolors['F'][1], E.fcolors['F'][0], E.fcolors['W'][1], E.fcolors['W'][0] ] tick_colors = [E.fcolors[x][1] for x in act] leg_labels = ['F-DC', 'W-DC', 'F-LC', 'W-LC'] # subplot labels on_text = 'from AS onset' if ONSET else 'to AS offset' xlabel = 'Time ' + on_text + ' [min]' ylabel = 'Probability' every_tbins = 2 if num_mins > 5 else 1 xticklim = (0, 15) if ONSET else (-15, 0) xs = np.arange(xticklim[0], xticklim[1], tbin_size * every_tbins / 60.) figsize, nrows, ncols, sharex, _ = get_subplot_specs(E, num_subplots=4) fig, axes = plt.subplots(nrows, ncols, figsize=figsize, sharex=sharex) hls = [] for n in xrange(all_avgs.shape[0] ): # shape: (groups * chow/hifat, F/W, DC/LC, prob values) ax0 = axes.flatten()[n] # F ax1 = ax0.twinx() # W twin_axes = [ax0, ax1] data, yerrs = all_avgs[n], all_errs[n] c = 0 for avgs, errs in zip(data, yerrs): # DC/LC k = 0 for avg, err in zip(avgs, errs): # F/W ax = twin_axes[k] # plotting every 5 tbins ax.errorbar( xs, avg[::every_tbins], yerr=err[::every_tbins], lw=.8, color=colors[c], label=leg_labels[c], #fmt='.', ms=.3, elinewidth=.8, capsize=.8, capthick=.3, zorder=5 - c) set_layout(E, ax, act[k], tick_colors[k], ONSET, k, num_mins, tbin_size) k += 1 c += 1 if n == 0: hls.append(ax.get_legend_handles_labels()) ax0.set_xlabel(xlabel, fontsize=8) if n % 2 == 0: ax0.set_ylabel(ylabel, fontsize=8, labelpad=10) if n == 1: set_legend(ax0, hls, colors) ax0.set_title(subtitles[n], fontsize=10) subplot_labels(E, fig, fig_title=fig_title, txpad=0, typad=0) plt.subplots_adjust(bottom=.12, hspace=0.6, wspace=0.3) return fig
def draw_subplot2(experiment, avgs, errs, fig_title, subtitles, ONSET=True, num_mins=15, tbin_size=5, act='F'): E = experiment colors = [E.fcolors[act][1], E.fcolors[act][0]] tick_colors = colors[0] text = 'drink' if act == 'W' else 'feed' leg_labels = ['%s-%s' % (text, x) for x in ['DC', 'LC']] # subplot labels on_text = 'from AS onset' if ONSET else 'to AS offset' xlabel = 'Time ' + on_text + ' [min]' ylabel = 'Probability' every_tbins = 2 if num_mins > 5 else 1 xticklim = (0, 15) if ONSET else (-15, 0) xs = np.arange(xticklim[0], xticklim[1], tbin_size * every_tbins / 60.) figsize, nrows, ncols, sharex, _ = get_subplot_specs(E, num_subplots=4) fig, axes = plt.subplots(nrows, ncols, figsize=figsize, sharex=sharex) hls = [] for n in xrange(avgs.shape[0] ): # shape: (groups * chow/hifat, F/W, DC/LC, prob values) ax = axes.flatten()[n] data, yerrs = avgs[n], errs[n] c = 0 for avg, err in zip(data, yerrs): # DC/LC # plotting every 5 tbins ax.errorbar( xs, avg[::every_tbins], yerr=err[::every_tbins], lw=.8, color=colors[c], label=leg_labels[c], #fmt='.', ms=.3, elinewidth=.8, capsize=.8, capthick=.3, zorder=5 - c) c += 1 set_layout(E, ax, act, tick_colors, ONSET, item_num=None, num_mins=num_mins, tbin_size=tbin_size) if n == 0: hls.append(ax.get_legend_handles_labels()) ax.set_xlabel(xlabel, fontsize=8) if n % 2 == 0: ax.set_ylabel(ylabel, fontsize=8, labelpad=10) if n == 1: set_legend(ax, hls, colors) ax.set_title(subtitles[n], fontsize=10) subplot_labels(E, fig, fig_title=fig_title, txpad=0, typad=0) plt.subplots_adjust(bottom=.12, hspace=0.6, wspace=0.3) return fig
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_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)
def draw_subplot(experiment, all_avgs, all_errs, fig_title, subtitles, ONSET=True, num_mins=15, tbin_size=5, ADD_SOURCE=False): E = experiment figsize, nrows, ncols, sharex, sharey = get_subplot_specs(E, num_subplots=len( E.groups)) # cy_labels = ['24hrs', 'Dark Cycle', 'Light Cycle'] act = ['F', 'W'] colors = [ '.4', E.fcolors['F'][0], E.fcolors['F'][1], '.65', E.fcolors['W'][0], E.fcolors['W'][1] ] tick_colors = [E.fcolors[x][0] for x in act] leg_labels = ['F-24H', 'W-24H', 'F-DC', 'W-DC', 'F-LC', 'W-LC'] # probability fig, axes = plt.subplots(nrows, ncols, figsize=figsize, sharex=sharex, sharey=sharey) every_tbins = 2 if num_mins > 5 else 1 xticklim = (0, 15) if ONSET else (-15, 0) xs = np.arange(xticklim[0], xticklim[1], tbin_size * every_tbins / 60.) hls = [] for c in xrange(all_avgs.shape[1]): try: ax0 = axes.flatten()[c] ax1 = ax0.twinx() k = 0 # F, W m = 0 # colors and leg_labels for ax in [ax0, ax1]: # plotting every 5 tbins for avgs, errs in zip(all_avgs, all_errs): ax.errorbar( xs, avgs[c, ::every_tbins, k], yerr=errs[c, ::every_tbins, k], lw=.3, color=colors[m], label=leg_labels[m], #fmt='.', ms=.3, elinewidth=.5, capsize=.5, capthick=.2, zorder=5 - k) m += 1 if c == 0: h, l = ax.get_legend_handles_labels() hls.append([h[0][0], l[0]]) set_layout(E, ax, act[k], tick_colors[k], ONSET, c, num_mins, tbin_size) k += 1 ax.set_title(subtitles[c], fontsize=10) # if c == 0: # set_legend(ax, hls, colors) except IndexError: ax.axis('off') continue # set subplot labels on_text = 'from AS onset' if ONSET else 'to AS offset' xlabel = 'Time ' + on_text + ' [min]' ylabel = 'Probability' subplot_labels(E, fig, xlabel, ylabel, fig_title) if ADD_SOURCE: add_source(fig) plt.subplots_adjust(bottom=.12, hspace=0.6, wspace=0.3) return fig
def draw_subplot(experiment, data, labels, ONSET=True, num_mins=15, tbin_size=5): E = experiment figsize, nrows, ncols, _, _ = get_subplot_specs(E, num_subplots=len(E.groups)) fig, axes = plt.subplots(nrows, ncols, figsize=figsize, sharex=sharex, sharey=sharey) act = ['F', 'W'] fd_text = ['Feeding', 'Drinking'] colors = [E.fcolors[x][0] for x in act] every_tbins = 2 if num_mins > 5 else 1 xticklim = (0, 15) if ONSET else (-15, 0) xs = np.arange(xticklim[0], xticklim[1], tbin_size * every_tbins / 60.) avgs = data[:, :, 0] errs = data[:, :, 1] hls = [] for c in xrange(avgs.shape[0]): try: ax0 = axes.flatten()[c] ax1 = ax0.twinx() k = 0 for ax in [ax0, ax1]: # plotting every 5 tbins ax.errorbar( xs, avgs[c, ::every_tbins, k], yerr=errs[c, ::every_tbins, k], lw=.3, color=colors[k], label=fd_text[k], #fmt='.', ms=.3, elinewidth=.5, capsize=.5, capthick=.2, zorder=5 - k) set_layout(E, ax, act[k], colors[k], ONSET, c, num_mins, tbin_size) if c == 0: h, l = ax.get_legend_handles_labels() hls.append([h[0][0], l[0]]) k += 1 ax.set_title(subtitles[c], fontsize=10) if c == 0: set_legend(ax, hls, colors) except IndexError: ax.axis('off') continue # set subplot labels on_text = 'from AS onset' if ONSET else 'to AS offset' xlabel = 'Time ' + on_text + ' [min]' ylabel = 'Probability' subplot_labels(E, fig, xlabel, ylabel, fig_title) plt.subplots_adjust(bottom=.12, hspace=0.6, wspace=0.3) return fig