def finish_plot(E, fig, level, xbins, ybins, h, l, nrows, title, fname, ADD_SOURCE): percent_time_color = E.fcolors['other'][0] set_legend(fig, h, l, text_color=percent_time_color) if (xbins, ybins) == (2, 4): fig.text(.94, .25, 'percent time', color=percent_time_color, fontsize=10, ha='left') if nrows == 1: typad = 0 sypad = -.05 elif nrows >= 2 or nrows < 6: typad = 0 sypad = .05 add_titles_notes(E, fig, title=title, typad=typad) plt.subplots_adjust(hspace=.3) save_plot(fname, fig, ADD_SOURCE=ADD_SOURCE, sypad=sypad)
def set_panel_layout(E, fig, err_type, tbin_type='12bins'): # legend annotation if tbin_type.endswith('bins'): fig.text(.7, 1.1, 'gray background: Dark Cycle', fontsize=8) xlabel = 'Circadian Time' add_xylabels(fig, xlabel=xlabel, xypad=-.15, labelsize=10) days_string = E.get_days_to_use_text() fig_title = '%s Experiment\nFeatures vs CT, 12bins group avg$\pm$%s\n%s days: %s' % ( E.short_name, err_type, E.use_days.replace('_', '-').title(), days_string) add_titles_notes(E, fig, title=fig_title, typad=.1) plt.subplots_adjust(hspace=.6, wspace=.6)
def set_panel_layout(E, fig, err_type, tbin_type): fig.text(.6, .9, '0: %s, control, %s (grayscale)' %(E.strain_names[0], tbin_type), fontsize=8) fig.text(.6, .85, '1: %s, knock-out, %s (colors)' %(E.strain_names[1], tbin_type), fontsize=8) if tbin_type.endswith('bins'): fig.text(.6, .8, 'gray background: Dark Cycle', fontsize=8) xlabel = 'Circadian Time' add_xylabels(fig, xlabel=xlabel, xypad=-.02, labelsize=10) days_string = E.get_days_to_use_text() fig_title = '%s Experiment\nFeatures vs CT, 12bins, group avg$\pm$%s\n%s days: %s' %( E.short_name, err_type, E.use_days.replace('_', '-').title(), days_string ) add_titles_notes(E, fig, title=fig_title)
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_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_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_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_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_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)