def _color_palette(cmap, n_colors): import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap colors_i = np.linspace(0, 1., n_colors) if isinstance(cmap, (list, tuple)): # we have a list of colors pal = color_palette(cmap, n_colors=n_colors) elif isinstance(cmap, str): # we have some sort of named palette try: pal = color_palette(cmap, n_colors=n_colors) except ValueError: # ValueError is raised when seaborn doesn't like a colormap (e.g. jet) # if that fails, use matplotlib try: # is this a matplotlib cmap? cmap = plt.get_cmap(cmap) except ValueError: # or maybe we just got a single color as a string cmap = ListedColormap([cmap], N=n_colors) pal = cmap(colors_i) else: # cmap better be a LinearSegmentedColormap (e.g. viridis) pal = cmap(colors_i) return pal
def test_chain(): periodic = True # periodic = False graph = gt_gen.lattice([1, 200], periodic=periodic) if periodic: figure_title = 'line_periodic' else: figure_title = 'line_non-periodic' n = graph.num_vertices() location1 = 0.2 * n location2 = n - location1 jump = 1e-3 weight = graph.new_edge_property('double', vals=1) e1 = graph.edge(location1, location1 + 1) weight[e1] = jump e2 = graph.edge(location2 - 1, location2) weight[e2] = jump pos_x = np.arange(n) pos_y = np.zeros((n,)) v_pos = graph.new_vertex_property('vector<double>', vals=np.vstack((pos_x, pos_y)).T) v_text = graph.new_vertex_property('string') for v in graph.vertices(): v_text[v] = pos_x[graph.vertex_index[v]] palette = sns.color_palette('Set1', n_colors=2) cmap = colors.ListedColormap(palette) gt_draw.graph_draw(graph, pos=v_pos, edge_color=weight, ecmap=cmap, edge_pen_width=.5, vertex_fill_color='w', vertex_size=2, vertex_text=v_text, vertex_font_size=1, output=figure_title + '_graph.pdf') x_signal1 = np.cos(np.linspace(0, 4 * np.pi, location1)) x_signal2 = np.cos(np.linspace(0, 50 * np.pi, n - 2 * location1)) x_signal3 = np.cos(np.linspace(0, 8 * np.pi, location1)) x_signal = np.hstack([x_signal1, x_signal2, x_signal3]) palette = sns.color_palette('Set1', n_colors=3) plt.figure() markerline, stemlines, baseline = plt.stem(x_signal, markerfmt=' ') plt.setp(stemlines, color=palette[1], linewidth=1.5) plt.setp(baseline, color='k') plt.savefig(figure_title + '_signal.pdf', dpi=300) n_eigs = graph.num_vertices() - 1 tau = 200 alpha = -1e-4 factories = [spec.ConvolutionSGFT(graph, n_eigs, tau, weight=weight), spec.PageRankSGFT(graph, n_eigs, alpha, weight=weight), spec.ConvolutionSGFT(graph, n_eigs, tau, weight=None), spec.PageRankSGFT(graph, n_eigs, alpha, weight=None)] sgft.comparison.compare_spectrograms(factories, x_signal, graph, v_pos, file_name=figure_title) sgft.comparison.compare_localization(factories, location1, graph, v_pos, file_name=figure_title)
def plot(graph, weights, pos, station_values, name): palette = sns.color_palette('RdBu', n_colors=256) cmap = colors.ListedColormap(palette[::-1]) weights = weights.copy() weights.a -= np.min(weights.a) weights.a *= 2 / np.max(weights.a) weights.a += 0.2 gt_draw.graph_draw(graph, pos=pos, vertex_color=[0, 0, 0, 0.5], vertex_fill_color=station_values, vcmap=cmap, vertex_size=5, edge_color=[0, 0, 0, 0.7], edge_pen_width=weights, output=name + '_temp.svg') gt_draw.graph_draw(graph, pos=pos, vertex_color=[0, 0, 0, 0.5], vertex_fill_color=station_values, vcmap=cmap, vertex_size=10, edge_color=[0, 0, 0, 0.7], edge_pen_width=weights, output=name + '_temp.png', output_size=(1200, 1200)) min_val = np.min(station_values.a) max_val = np.max(station_values.a) step = (max_val - min_val) / 5 labels = np.array(['{0:.2f}'.format(x) for x in np.arange(min_val, max_val, step)]) plt.figure() utils.plot_colorbar(cmap, labels, name)
def _color_palette(cmap, n_colors): import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap colors_i = np.linspace(0, 1., n_colors) if isinstance(cmap, (list, tuple)): # we have a list of colors cmap = ListedColormap(cmap, N=n_colors) pal = cmap(colors_i) elif isinstance(cmap, basestring): # we have some sort of named palette try: # is this a matplotlib cmap? cmap = plt.get_cmap(cmap) pal = cmap(colors_i) except ValueError: # ValueError happens when mpl doesn't like a colormap, try seaborn try: from seaborn.apionly import color_palette pal = color_palette(cmap, n_colors=n_colors) except (ValueError, ImportError): # or maybe we just got a single color as a string cmap = ListedColormap([cmap], N=n_colors) pal = cmap(colors_i) else: # cmap better be a LinearSegmentedColormap (e.g. viridis) pal = cmap(colors_i) return pal
def get_color_palette(name="dark"): """ Load a color pallete, use seaborn if available """ if not seaborn_loaded: color_palette = ColorDict() # stolen from seaborn color-palette color_palette[0] = (0.2980392156862745, 0.4470588235294118, 0.6901960784313725) color_palette[5] = (0.8, 0.7254901960784313, 0.4549019607843137)#(0.3921568627450 9803, 0.7098039215686275, 0.803921568627451) color_palette["k"] = "k" color_palette[1] = (0.3333333333333333, 0.6588235294117647, 0.40784313725490196) color_palette[2] = (0.7686274509803922, 0.3058823529411765, 0.3215686274509804) color_palette[3] = (0.5058823529411764, 0.4470588235294118, 0.6980392156862745) color_palette['prohibited'] = 'grey' else: color_palette = ColorDict() color_palette.update(dict(zip(range(6),sb.color_palette(name)))) color_palette['prohibited'] = sb.color_palette("deep")[3] return color_palette
def parallel_coordinates(dataframe, hue, cols=None, palette=None, **subplot_kws): """ Produce a parallel coordinates plot from a dataframe. Parameters ---------- dataframe : pandas.DataFrame The data to be plotted. hue : string The column used to the determine assign the lines' colors. cols : list of strings, optional The non-hue columns to include. If None, all other columns are used. palette : string, optional Name of the seaborn color palette to use. **subplot_kws : keyword arguments Options passed directly to plt.subplots() Returns ------- fig : matplotlib Figure """ # get the columsn to plot if cols is None: cols = dataframe.select(lambda c: c != hue, axis=1).columns.tolist() # subset the data final_cols = copy.copy(cols) final_cols.append(hue) data = dataframe[final_cols] # these plots look ridiculous in anything other than 'ticks' with seaborn.axes_style('ticks'): fig, axes = plt.subplots(ncols=len(cols), **subplot_kws) hue_vals = dataframe[hue].unique() colors = seaborn.color_palette(name=palette, n_colors=len(hue_vals)) color_dict = dict(zip(hue_vals, colors)) for col, ax in zip(cols, axes): data_limits =[(0, dataframe[col].min()), (0, dataframe[col].max())] ax.set_xticks([0]) ax.update_datalim(data_limits) ax.set_xticklabels([col]) ax.autoscale(axis='y') ax.tick_params(axis='y', direction='inout') ax.tick_params(axis='x', direction='in') for row in data.values: for n, (ax1, ax2) in enumerate(zip(axes[:-1], axes[1:])): line = _connect_spines(ax1, ax2, row[n], row[n+1], color=color_dict[row[-1]]) fig.subplots_adjust(wspace=0) seaborn.despine(fig=fig, bottom=True, trim=True) return fig
def _color_palette(cmap, n_colors): import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap colors_i = np.linspace(0, 1.0, n_colors) if isinstance(cmap, (list, tuple)): # we have a list of colors try: # first try to turn it into a palette with seaborn from seaborn.apionly import color_palette pal = color_palette(cmap, n_colors=n_colors) except ImportError: # if that fails, use matplotlib # in this case, is there any difference between mpl and seaborn? cmap = ListedColormap(cmap, N=n_colors) pal = cmap(colors_i) elif isinstance(cmap, basestring): # we have some sort of named palette try: # first try to turn it into a palette with seaborn from seaborn.apionly import color_palette pal = color_palette(cmap, n_colors=n_colors) except (ImportError, ValueError): # ValueError is raised when seaborn doesn't like a colormap # (e.g. jet). If that fails, use matplotlib try: # is this a matplotlib cmap? cmap = plt.get_cmap(cmap) except ValueError: # or maybe we just got a single color as a string cmap = ListedColormap([cmap], N=n_colors) pal = cmap(colors_i) else: # cmap better be a LinearSegmentedColormap (e.g. viridis) pal = cmap(colors_i) return pal
def test_chain(): graph = gt_gen.lattice([1, 1000], periodic=False) # gt_draw.graph_draw(graph) jump = 1e-3 weight = graph.new_edge_property('double', vals=1) e1 = graph.edge(300, 301) weight[e1] = jump e1 = graph.edge(699, 700) weight[e1] = jump# + 0.01 for e in graph.edges(): # weight[e] += min(abs(0.3 * np.random.randn()), 1) if e.source() == 300 or e.source() == 699: print e, weight[e] n_eigs = 100 alpha = -1e-10 factory_weighted = ppr.PersonalizedPageRank(graph, n_eigs, weight=weight) factory_unweighted = ppr.PersonalizedPageRank(graph, n_eigs, weight=None) spectrogram_weighted = np.zeros((graph.num_vertices(), n_eigs)) spectrogram_unweighted = np.zeros((graph.num_vertices(), n_eigs)) t = timeit.default_timer() for v in range(graph.num_vertices()): _, loadings_weighted = factory_weighted.vector([graph.vertex(v)], alpha) _, loadings_unweighted = factory_unweighted.vector([graph.vertex(v)], alpha) spectrogram_weighted[v, :] = loadings_weighted spectrogram_unweighted[v, :] = loadings_unweighted print timeit.default_timer() - t spectrogram_weighted = np.abs(spectrogram_weighted) spectrogram_unweighted = np.abs(spectrogram_unweighted) spectrogram_weighted /= np.atleast_2d(np.sum(spectrogram_weighted, axis=1)).T spectrogram_unweighted /= np.atleast_2d(np.sum(spectrogram_unweighted, axis=1)).T palette = sns.color_palette('RdBu_r', n_colors=256) cmap = colors.ListedColormap(palette, N=256) plt.figure() plt.subplot(121) plt.imshow(spectrogram_weighted, interpolation='none', cmap=cmap) plt.title('Weighted') plt.axis('tight') plt.subplot(122) plt.imshow(spectrogram_unweighted, interpolation='none', cmap=cmap) plt.title('Unweighted') plt.axis('tight')
def make_figure(fig_name='timing_tech', Acquisition_time=np.array([1.6, 0.122, 0.122]), AWG_overhead=np.array([0.093, 0.093, 0]), Processing_overhead=np.array([.164+.063, .164+.063, 0]), Overhead=np.array([0.04, 0.04, 0.04]), methods=('Conventional-', 'Restless-', 'Restless+'), ): cls = (sns.color_palette('muted')) plt.rcParams.update({'font.size': 9, 'legend.labelspacing': 0, 'legend.columnspacing': .3, 'legend.handletextpad': .2}) f, ax = plt.subplots(figsize=(3.3, .9)) y_pos = np.array([.8, 0, -.8])+.1 lefts = np.array([0, 0, 0]) ax.barh(y_pos, AWG_overhead, color=cls[2], align='center', height=0.6, label='Set pars.') lefts = lefts+np.array(AWG_overhead) ax.barh(y_pos, Acquisition_time, color=cls[0], align='center', height=0.6, label='Experiment', left=lefts) lefts = lefts + Acquisition_time ax.barh(y_pos, Processing_overhead, color=cls[3], align='center', height=0.6, label='Processing', left=lefts) lefts = lefts + Processing_overhead ax.barh(y_pos, Overhead, color=cls[1], align='center', height=0.6, label='Misc.', left=lefts) lefts = lefts + Overhead ax.set_yticks(y_pos) ax.set_yticklabels(methods, rotation=0) # , va='top') ax.set_xlabel('Time per iteration (s)') ax.set_xlim(0, 2.) ax.set_ylim(-1.2, 1.3) ax.legend(frameon=False, ncol=4, loc=(-0.2, 1), labelspacing=0, prop={'size': 7}) ax.tick_params(pad=1.5) ax.xaxis.labelpad = 0 plt.subplots_adjust( left=0.28, bottom=0.3, right=.96, top=.8, wspace=0.1, hspace=0.1) for fmt in ['pdf']: if f is not None: save_name = os.path.abspath( os.path.join(save_folder, fig_name+'.{}'.format(fmt))) f.savefig(save_name, format=fmt, dpi=400)
def make_shotchart(top, left, result, player_name, cache=True): """ Makes shotchart of a given player Args: top (list): list of y coordinates (int) of all shots left (list): list of x coordinates (int) of all shots result (list): list of results (str in ['Made', 'Missed'] of all shots player_name (str): player name cache (bool): if True, save plot Returns: None """ plt.figure() df = pd.DataFrame({'top': top, 'left': left, 'result': result}) made = df[df.result == 'Made'] missed = df[df.result == 'Missed'] im = plt.imread('shotchart/court.png') plt.imshow(im) plt.scatter(list(missed.left), list(missed.top), c=sns.color_palette()[2], alpha=0.7, linewidths=0) plt.scatter(list(made.left), list(made.top), c=sns.color_palette()[1], alpha=0.7, linewidths=0) plt.axis('off') if cache: plt.savefig('images/' + player_name) else: plt.show() plt.close()
def divergent_palette(y, n_bins=100): """ Returns the color palette for a continuous variable y https://stanford.edu/~mwaskom/software/seaborn/tutorial/color_palettes.html """ # palette = color_palette('Blues', n_colors=len(y)) palette = color_palette('RdBu_r', n_colors=len(y)) bin_assignments = pd.cut(y, n_bins, labels=range(n_bins)) # return [palette[int(k-1)] for k in y.rank(method='min')] return [palette[bin_assignments[k]] for k in range(n_bins)]
def _color_palette(cmap, n_colors): import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap colors_i = np.linspace(0, 1., n_colors) if isinstance(cmap, (list, tuple)): # we have a list of colors try: # first try to turn it into a palette with seaborn from seaborn.apionly import color_palette pal = color_palette(cmap, n_colors=n_colors) except ImportError: # if that fails, use matplotlib # in this case, is there any difference between mpl and seaborn? cmap = ListedColormap(cmap, N=n_colors) pal = cmap(colors_i) elif isinstance(cmap, basestring): # we have some sort of named palette try: # first try to turn it into a palette with seaborn from seaborn.apionly import color_palette pal = color_palette(cmap, n_colors=n_colors) except (ImportError, ValueError): # ValueError is raised when seaborn doesn't like a colormap # (e.g. jet). If that fails, use matplotlib try: # is this a matplotlib cmap? cmap = plt.get_cmap(cmap) except ValueError: # or maybe we just got a single color as a string cmap = ListedColormap([cmap], N=n_colors) pal = cmap(colors_i) else: # cmap better be a LinearSegmentedColormap (e.g. viridis) pal = cmap(colors_i) return pal
def _color_palette(cmap, n_colors): import matplotlib.pyplot as plt try: from seaborn.apionly import color_palette pal = color_palette(cmap, n_colors=n_colors) except (TypeError, ImportError, ValueError): # TypeError is raised when LinearSegmentedColormap (viridis) is used # ImportError is raised when seaborn is not installed # ValueError is raised when seaborn doesn't like a colormap (e.g. jet) # Use homegrown solution if you don't have seaborn or are using viridis if isinstance(cmap, basestring): cmap = plt.get_cmap(cmap) colors_i = np.linspace(0, 1., n_colors) pal = cmap(colors_i) return pal
def class_to_color(classes, class_alphas=False): """ Returns a dictionary mapping class label to color """ class_labels = list(set(classes)) pallette = sns.color_palette("Set2", len(class_labels)) class2col = {class_labels[k]: pallette[k] for k in range(len(class_labels))} # possibly add alphas if class_alphas: class2alpha = class_to_alpha(classes) class2col = {k: (class2col[k][0], class2col[k][1], class2col[k][2], class2alpha[k]) for k in class2col.keys()} return class2col
def plot_waveform(wf_header, wf_data,\ fig=None,savename=None,\ use_mv_and_ns=True,color=sb.color_palette("dark")[0]): """ Make a plot of a single acquisition Args: wf_header (dict): custom waveform header wf_data (np.ndarray): waveform data Keyword Args: fig (pylab.figure): A figure instance savename (str): where to save the figure (full path) use_mv_and_ns (bool): use mV and ns instead of V and s Returns: pylab.fig """ if fig is None: fig = p.figure() ax = fig.gca() # if remove_empty_bins: # bmin = min(bincenters[bincontent > 0]) # bmax = max(bincenters[bincontent > 0]) # bincenters = bincenters[np.logical_and(bincenters >= bmin, bincenters <= bmax)] # bincontent = bincontent[np.logical_and(bincenters >= bmin, bincenters <= bmax)] xlabel = wf_header["xunit"] ylabel = wf_header["yunit"] xs = copy(wf_header["xs"]) ys = copy(wf_data) if xlabel == "s" and ylabel == "V" and use_mv_and_ns: xs *= 1e9 ys *= 1e3 xlabel = "ns" ylabel = "mV" ax.plot(xs, ys, color=color) ax.grid() sb.despine(fig) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) p.tight_layout() if savename is not None: fig.savefig(savename) return fig
def _make_em_axes(self,ax,tn_val): """Plot single em curve""" if tn_val not in self.Tn: raise ValueError("Invalid wait time %f. Use a valid value from self.Tn"%(tn_val)) tn_index = np.where(self.Tn==tn_val)[0][0] #standard deviation ax.fill_between(self.em_stats[tn_index]['T_mean'], self.em_stats[tn_index]['em_mean']-self.em_stats[tn_index]['em_std'], self.em_stats[tn_index]['em_mean']+self.em_stats[tn_index]['em_std'], facecolor=sns.color_palette('deep')[2], edgecolor=sns.color_palette('deep')[2], alpha=0.75) #MC histograms for pfile in os.listdir(os.path.join(self.em_res_top_dir,'tn%d'%tn_val)): with open(os.path.join(self.em_res_top_dir,'tn%d'%tn_val,pfile),'rb') as f: h=pickle.load(f) ax.hist(h['T'], bins=h['bins'], weights=h['em'], histtype='step', color=sns.color_palette('deep')[0], linestyle=self.linestyles[-1], alpha=0.1) #mean ax.plot(self.em_stats[tn_index]['T_mean'], self.em_stats[tn_index]['em_mean'], color='black', linestyle=self.linestyles[-1], linewidth=2)
def show_argmax_spectrogram_graph(s, vertex_size=20, amax_file_name=None): amax = np.argmax(np.abs(s), axis=0) n_values = np.unique(amax).size assignment = graph.new_vertex_property('double', vals=amax) if weight is None: edge_pen_width = 1.0 else: edge_pen_width = weight palette = sns.color_palette('BuGn', n_colors=n_values) cmap = colors.ListedColormap(palette) gt_draw.graph_draw(graph, pos=pos, vertex_color=[0, 0, 0, 0.5], vertex_fill_color=assignment, vcmap=cmap, vertex_size=vertex_size, edge_color=[0, 0, 0, 0.7], edge_pen_width=edge_pen_width, output=amax_file_name, output_size=(1200, 1200))
def run_biclustering(model_class, data, pref_matrix, comp_level, thresholder, ac_tester, output_prefix, palette='Set1'): t = timeit.default_timer() bic_list = bc.bicluster(pref_matrix, comp_level=comp_level) t1 = timeit.default_timer() - t print('Time:', t1) bic_list = postproc.clean(model_class, data['data'], thresholder, ac_tester, bic_list, share_elements=False)[1] colors = sns.color_palette(palette, len(bic_list)) plt.figure() pref.plot(pref_matrix, bic_list=bic_list, palette=colors) plt.savefig(output_prefix + '_pref_mat.pdf', dpi=600) bc_groups = [np.squeeze(bic[0].toarray()) for bic in bic_list] print('Inlier sets size:', [np.sum(g) for g in bc_groups]) plot_models(data, bc_groups, palette=colors) plt.savefig(output_prefix + '_final_models.pdf', dpi=600) line_plot(data, groups=bc_groups, palette=colors) plt.savefig(output_prefix + '_line_plot.pdf', dpi=600) if bc_groups: union = np.sum(np.vstack(bc_groups), axis=0) == 0 else: union = np.zeros((pref_matrix.shape[0],), dtype=np.bool) line_plot(data, groups=[union], palette=['#e7298a']) plt.savefig(output_prefix + '_line_plot_outliers.pdf', dpi=600) if 'label' in data: if bc_groups: inliers = np.sum(np.vstack(bc_groups), axis=0) > 0 else: inliers = np.zeros((pref_matrix.shape[0],), dtype=np.bool) bc_groups.append(np.logical_not(inliers)) gt_groups = ground_truth(data['label']) gnmi, prec, rec = test_utils.compute_measures(gt_groups, bc_groups) stats = dict(time=t1, gnmi=gnmi, precision=prec, recall=rec) else: stats = dict(time=t1) return stats, bc_groups
def __init__(self, em_res_top_dir, em_stats, diagnostics, diagnostics_stats, Tn = np.arange(250,5250,250), dpi=1000, fontsize=18., figsize=(8,8), alfs=0.75, fformat='eps', **kwargs): #set up logger self.logger = logging.getLogger(type(self).__name__) #arguments self.em_res_top_dir = em_res_top_dir self.em_stats = em_stats self.diagnostics = diagnostics self.diagnostics_stats = diagnostics_stats #keyword arguments self.dpi,self.fontsize,self.figsize,self.alfs,self.fformat = dpi,fontsize,figsize,alfs,fformat self.Tn = Tn self.Tndelta = self.Tn[1] - self.Tn[0] #static parameters for plot styling self.linestyles = (':','-.','--','-') self.colors = [] [self.colors.extend(len(self.linestyles)*[sns.color_palette('deep')[i]]) for i in range(int(len(self.Tn)/len(self.linestyles)))] if len(self.colors) != len(self.Tn): self.logger.warning("Number of colors does not match number of wait-time values. Reconfigure one or the other before plotting.")
def test(ransac_gen, x, sigma, name=None, gt_groups=None, palette='Set1'): t = timeit.default_timer() pref_mat, orig_models, models, bics = detection.run(ransac_gen, x, sigma) t1 = timeit.default_timer() - t print('Total time: {:.2f}'.format(t1)) base_plot(x) if name is not None: plt.savefig(name + '_data.pdf', dpi=600, bbox_inches='tight', pad_inches=0) plt.figure() detection.plot(pref_mat) if name is not None: plt.savefig(name + '_pref_mat.png', dpi=600, bbox_inches='tight', pad_inches=0) palette = sns.color_palette(palette, len(bics)) plt.figure() detection.plot(bics, palette=palette) if name is not None: plt.savefig(name + '_pref_mat_bic.png', dpi=600, bbox_inches='tight', pad_inches=0) plot_models(x, models, palette=palette) if name is not None: plt.savefig(name + '_final_models.pdf', dpi=600, bbox_inches='tight', pad_inches=0) plot_final_biclusters(x, bics, palette=palette) if name is not None: plt.savefig(name + '_final_bics.pdf', dpi=600, bbox_inches='tight', pad_inches=0) plot_original_models(x, orig_models, bics, palette) if name is not None: plt.savefig(name + '_original_models.pdf', dpi=600, bbox_inches='tight', pad_inches=0) bc_groups = [(b[0] > 0).astype(dtype=float) for b in bics] stats = test_utils.compute_measures(gt_groups, bc_groups) stats['time'] = t1 return stats
def main(): expts = lab.ExperimentSet( os.path.join(df.metadata_path, 'expt_metadata.xml'), behaviorDataPath=os.path.join(df.data_path, 'behavior'), dataPath=os.path.join(df.data_path, 'imaging')) sal_grp = lab.classes.HiddenRewardExperimentGroup.from_json( sal_json, expts, label='saline to muscimol') mus_grp = lab.classes.HiddenRewardExperimentGroup.from_json( mus_json, expts, label='muscimol to saline') fig = plt.figure(figsize=(8.5, 11)) gs = plt.GridSpec(1, 1, top=0.9, bottom=0.7, left=0.1, right=0.4) ax = fig.add_subplot(gs[0, 0]) for expt in mus_grp: if 'saline' in expt.get('drug'): expt.attrib['drug_condition'] = 'reversal' elif 'muscimol' in expt.get('drug'): expt.attrib['drug_condition'] = 'learning' for expt in sal_grp: if 'saline' in expt.get('drug'): expt.attrib['drug_condition'] = 'learning' elif 'muscimol' in expt.get('drug'): expt.attrib['drug_condition'] = 'reversal' plotting.plot_metric( ax, [sal_grp, mus_grp], metric_fn=ra.fraction_licks_in_reward_zone, label_groupby=False, plotby=['X_drug_condition'], plot_method='swarm', rotate_labels=False, activity_label='Fraction of licks in reward zone', colors=sns.color_palette('deep'), plot_bar=True) ax.set_yticks([0, 0.1, 0.2, 0.3, 0.4]) ax.set_ylim(top=0.4) ax.set_xticklabels(['Days 1-3', 'Day 4']) sns.despine(fig) ax.set_title('') ax.set_xlabel('') misc.save_figure( fig, filename, save_dir=save_dir) plt.close('all')
def plot_bumps_on_data(X, bumps, palette='Set1', ax=None): if ax is None: ax = plt.gca() # Plot the sphere u = np.linspace(0, 2 * np.pi, 100) v = np.linspace(0, np.pi, 100) ax.plot_surface(0.99 * np.outer(np.cos(u), np.sin(v)), 0.99 * np.outer(np.sin(u), np.sin(v)), 0.99 * np.outer(np.ones(np.size(u)), np.cos(v)), color='w', edgecolors='#AAAAAA', alpha=1) plot_data_embedded(X, palette='w', edgecolors='k', ax=ax) colors = sns.color_palette(palette, n_colors=len(bumps)) colors = [mpl_colors.to_hex(c) for c in colors] for i, (b, c) in enumerate(zip(bumps, colors)): alpha = np.maximum(b, 0) / b.max() plot_data_embedded(X, palette=c, alpha=alpha, edgecolors='none', ax=ax)
def compare_localization(factories, loc, file_name=None): locations = [k + loc for k in range(5, 20, 5)] palette = sns.color_palette('Set1', n_colors=len(locations)) if file_name is not None: file_name += '_spec{0}.pdf' for i in range(len(factories)): plt.figure() plt.hold(True) max_val = -1 for j, v in enumerate(locations): window = factories[i].get_window(v) max_val = max(max_val, np.max(window)) plt.plot(window, color=palette[j], linewidth=3) plt.plot([v, v], [0, window[v] * 1], color=palette[j], linestyle='--', linewidth=3) lim = (np.floor(max_val / 0.005) + 1) * 0.005 if lim - max_val < 0.002: lim += 0.005 plt.ylim(0, lim) if file_name is not None: plt.savefig(file_name.format(i), dpi=300)
def plot_damp_top_authors(folder, damps, top, min_year, plot_author_count=20, show_legend=True): graph = cite_graph(GRAPH_CSV) top_authors = most_cited_authors(graph, top, min_year)[:plot_author_count] author_nodes = mysql.get_authors() x_labels = [author_nodes[a[0]].name for a in top_authors] x_axis = range(1, plot_author_count + 1) top_author_ids = np.array([a[0] for a in top_authors]) folder_path = "figs/%s/%s/authors/%s" % (THE.version, THE.permitted, folder) palette = np.array(sns.color_palette("hls", plot_author_count)) legends = [] # for i, f_name in enumerate(os.listdir(folder_path)): y_axes = [] means = np.array([0.0] * plot_author_count) plt.figure(figsize=(8, 2)) for i, _ in enumerate(damps): # file_name = "%s/%s" % (folder_path, name) file_name = "%s/page_rank_%0.2f.pkl" % (folder_path, damps[i]) with open(file_name) as f: pr_scores = cPkl.load(f) y_axis = np.array([pr_scores[a] for a in top_author_ids]) y_axes.append(y_axis) means += y_axis indices = np.argsort(means)[::-1] top_author_ids = top_author_ids[indices] # sns.set_style("whitegrid", {'axes.grid': False}) sns.set_style("white") for i, y_axis in enumerate(y_axes): plt.plot(x_axis, y_axis[indices], c=palette[i]) legends.append("%0.2f" % damps[i]) if show_legend: plt.legend(legends, bbox_to_anchor=(-0.1, 1.15, 1.15, 0.2), loc="lower left", mode="expand", borderaxespad=0, ncol=10) fig_name = "figs/%s/%s/authors/damp_%s.png" % (THE.version, THE.permitted, folder) plt.ylabel("Page Rank Score", fontsize=14) plt.xlabel("Author ID", fontsize=14) plt.xticks(x_axis, top_author_ids, rotation='vertical') plt.title("Page Rank Score for top %d cited author with varying damping factors" % plot_author_count) plt.savefig(fig_name, bbox_inches='tight') plt.clf()
def plot_models(data, selection=[], s=10, marker='o'): def inner_plot_img(pos, img): pos_rc = pos + np.array(img.shape[:2], dtype=np.float) / 2 plt.hold(True) gray_image = PIL.Image.fromarray(img).convert('L') plt.imshow(gray_image, cmap='gray', interpolation='none') for g, color in zip(groups, palette): plt.scatter(pos_rc[g, 0], pos_rc[g, 1], c=color, edgecolors='face', marker=marker, s=s) labels = ['{0}'.format(i) for i in selection] pos_rc = pos_rc[selection, :] for label, x, y in zip(labels, pos_rc[:, 0], pos_rc[:, 1]): plt.annotate(label, xy=(x, y), xytext=(-10, 10), size=3, textcoords='offset points', ha='right', va='bottom', bbox=dict(boxstyle='round, pad=0.5', fc='yellow', alpha=0.5), arrowprops=dict(arrowstyle='->', linewidth=.5, color='yellow', connectionstyle='arc3,rad=0')) plt.axis('off') groups = ground_truth(data['label']) palette = sns.color_palette('Set1', len(groups) - 1) palette.insert(0, [1., 1., 1.]) x = data['data'] if not selection: selection = np.arange(x.shape[0]) plt.figure() gs = gridspec.GridSpec(1, 2) gs.update(wspace=0) plt.subplot(gs[0]) inner_plot_img(x[:, 0:2], data['img1']) plt.subplot(gs[1]) inner_plot_img(x[:, 3:5], data['img2'])
def plot(array_or_bic_list, palette='Set1'): def get_cmap(base_color, n_colors=256): colors = [np.array([1., 1., 1., 0])] + \ sns.light_palette(base_color, n_colors=n_colors - 1) return mpl_colors.ListedColormap(colors) try: plt.imshow(array_or_bic_list, interpolation='none', cmap=get_cmap('k')) except TypeError: palette = sns.color_palette(palette, len(array_or_bic_list)) for (u, v), c in zip(array_or_bic_list, palette): plt.imshow(u.dot(v), interpolation='none', cmap=get_cmap(c)) plt.tick_params( which='both', # both major and minor ticks are affected bottom='off', top='off', left='off', right='off', labelbottom='off', labelleft='off') plt.axis('image')
def plot_histogram(bincenters,bincontent,\ fig=None,savename="test.png",\ remove_empty_bins=True): """ Plot a histogram returned by TektronixDPO4104B.get_histogram Use pylab.plot Args: bincenters (np.ndarray); bincenters (x) bincontent (np.ndarray): bincontent (y) Keyword Args: fig (pylab.figure): A figure instance savename (str): where to save the figure (full path) remove_empty_bins (bool): Cut away preceeding and trailing zero bins """ if fig is None: fig = p.figure() ax = fig.gca() if remove_empty_bins: bmin = min(bincenters[bincontent > 0]) bmax = max(bincenters[bincontent > 0]) bincenters = bincenters[np.logical_and(bincenters >= bmin, bincenters <= bmax)] bincontent = bincontent[np.logical_and(bincenters >= bmin, bincenters <= bmax)] ax.plot(bincenters, bincontent, color=sb.color_palette("dark")[0]) ax.grid() sb.despine(fig) ax.set_xlabel("amplitude") ax.set_ylabel("log nevents ") p.tight_layout() fig.savefig(savename) return fig
def show_window(spectrogram, v, weight=None, pos=None, file_name=None, vertex_size=10): window = spectrogram.get_window(v) window = spectrogram.graph.new_vertex_property("double", vals=window) if weight is None: edge_pen_width = 1.0 else: edge_pen_width = weight palette = sns.color_palette("YlOrRd", n_colors=256) cmap = colors.ListedColormap(palette) gt_draw.graph_draw( spectrogram.graph, pos=pos, vertex_color=[0, 0, 0, 0.5], vertex_fill_color=window, vcmap=cmap, vertex_size=vertex_size, edge_color=[0, 0, 0, 0.7], edge_pen_width=edge_pen_width, output=file_name, output_size=(1200, 1200), )
def plot_aia_response_functions(raw_response_file,fix_response_file): """Plot AIA temperature response functions as computed by SSW""" #Load data raw_tresp,fix_tresp = np.loadtxt(raw_response_file),np.loadtxt(fix_response_file) #set labels aia_labs = [r'$94\,\,\AA$',r'$131\,\,\AA$',r'$171\,\,\AA$',r'$193\,\,\AA$',r'$211\,\,\AA$',r'$335\,\,\AA$'] #Create figure fig,ax = plt.subplots(1,2,figsize=(16,8)) for i in range(1,7): #unnormalized ax[0].plot(10**raw_tresp[:,0],raw_tresp[:,i],linewidth=2,linestyle='-',color=sns.color_palette('deep')[i-1],label=aia_labs[i-1]) ax[0].plot(10**fix_tresp[:,0],fix_tresp[:,i],linewidth=2,linestyle='--',color=sns.color_palette('deep')[i-1]) #normalized ax[1].plot(raw_tresp[:,0],raw_tresp[:,i]/np.max(raw_tresp[:,i]),linewidth=2,linestyle='-',color=sns.color_palette('deep')[i-1]) ax[1].plot(fix_tresp[:,0],fix_tresp[:,i]/np.max(fix_tresp[:,i]),linewidth=2,linestyle='--',color=sns.color_palette('deep')[i-1]) #set plot options ax[0].set_xscale('log') ax[0].set_yscale('log') ax[0].set_xlim([10**5.,10**8.]) ax[0].set_ylim([1e-28,1e-23]) ax[1].set_xlim([5,8]) ax[1].set_ylim([0,1]) #labels ax[0].set_xlabel(r'$T\,\,\mathrm{(K)}$',fontsize=22) ax[0].set_ylabel(r'Temperature Response $(\mathrm{DN}\,\mathrm{cm}^{-5}\,\mathrm{s}^{-1}\,\mathrm{pix}^{-1})$',fontsize=22) ax[1].set_xlabel(r'$\log{T}\,\,\mathrm{(K)}$',fontsize=22) ax[1].set_ylabel(r'Normalized Temperature Response',fontsize=22) #legend ax[0].legend(loc='best',fontsize=14) plt.tight_layout() plt.savefig('figures/aia_response_functions.eps',format='eps')
]].copy() mtbl_tg['GDP_95_benefit_ratio'] = mtbl_tg['GDP_95_benefit'] / mtbl_tg[ sgdp_year + '_gdp'] * 100 mtbl_tg['GDP_5_benefit_ratio'] = mtbl_tg['GDP_5_benefit'] / mtbl_tg[ sgdp_year + '_gdp'] * 100 mtbl_tg.set_index('iso', inplace=True) mtbl_tg['Ctry_Name'] = itbl_ctrylist['NAME_ENGLI'] mtbl_tg.set_index(['Ctry_Name'], inplace=True) mtbl_tg['Ctry_Name'] = mtbl_tg.index mtbl_tg['gdp_share'] = mtbl_tg['2010_gdp'] / mtbl_tg['2010_gdp'].sum() * 100 colors = sns.color_palette('RdYlBu', 5).as_hex() colors[2] = '#A9A9A9' gdp_bin = [5000, 10000, 20000, 40000, 200000] for ig, gdpcap in enumerate(gdp_bin[::-1]): mtbl_tg.loc[mtbl_tg['2010_gdpcap'] < gdpcap, 'color'] = colors[ig] mtbl_tg.sort_values(['GDP_median_benefit_ratio'], inplace=True) mtbl_tg['cum_gdp_share'] = mtbl_tg['gdp_share'].copy() for i in np.arange(1, len(mtbl_tg)): mtbl_tg['cum_gdp_share'].iloc[i] = mtbl_tg['cum_gdp_share'].iloc[ i] + mtbl_tg['cum_gdp_share'].iloc[i - 1] bins = np.array([0] + mtbl_tg['cum_gdp_share'].values.tolist())
def visualizeBilayer(self, scale_z=False, layers=['top', 'bottom'], plot_type='scatter', cmap='RdYlBu_r', point_size=100, savename=None, residue_cmap=None, twod=False, height=4, width=20, show=True): coords = { 'top': self.make_PosMat(self.layers['top']).T , 'bottom': self.make_PosMat(self.layers['bottom']).T } residue_names = { 'top': [str(x.resname) for x in self.layers['top']], 'bottom': [str(x.resname) for x in self.layers['bottom']] } if residue_cmap is None: unique_residues = Counter(residue_names['top'] + residue_names['bottom']).keys() unique_colors = sns.color_palette("hls", len(unique_residues)) self.residueCmap = {k:v for k,v in zip(unique_residues, unique_colors)} else: self.residueCmap = residue_cmap colors = { 'top': [self.residueCmap[i] for i in residue_names['top']], 'bottom': [self.residueCmap[i] for i in residue_names['bottom']] } if twod is False: fig = plt.figure() ax = fig.add_subplot(111, projection='3d') for l in layers: if twod is False: if plot_type == 'scatter': ax.scatter(coords[l][0], coords[l][1],coords[l][2], c=colors[l], s=point_size, lw=0) elif plot_type == 'mesh': ax.plot_trisurf(coords[l][0], coords[l][1], coords[l][2], cmap=cm.get_cmap(cmap), linewidth=0.2) else: print "Undefined plot type. Will NOT plot!" if scale_z is True: xmin, xmax, ymin, ymax = plt.axis() ax.set_zlim3d(xmin,xmax) else: if plot_type == 'scatter': fig, (ax1, ax2) = plt.subplots(1, 2) axes = {'top': ax1, 'bottom': ax2} for i in self.residueCmap: indices = [n for n,x in enumerate(residue_names[l]) if x==i] axes[l].scatter(coords[l][0][indices], coords[l][1][indices], c=[colors[l][x] for x in indices], s=point_size, lw=0, label=i) plt.legend() elif plot_type == 'hexbin': cms = {'POPC': 'Blues', 'POPI': 'Reds', 'PSM': 'Purples', 'POPS': 'Oranges', 'POPE': 'Greens', 'merge': 'None'} #cms = {'POPC': 'Blues', 'POPE': 'Greens', 'POPI': 'Reds', 'PMCL1': 'Oranges', 'merge': 'None'} #fig, (ax1,ax2,ax3,ax4, ax5) = plt.subplots(1,5, figsize=(width, height)) fig, (ax1,ax2,ax3,ax4,ax5,ax6) = plt.subplots(1,6, figsize=(width, height)) #axes = {'POPC': ax1, 'POPE': ax2, 'POPI': ax3, 'PMCL1': ax4, 'merge': ax5} axes = {'POPC': ax1, 'POPE': ax2, 'POPI': ax3, 'POPS': ax4, 'PSM': ax5, 'merge': ax6} for i in cms: indices = [n for n,x in enumerate(residue_names[l]) if x==i or i=='merge'] if i=='merge': axes[i].hexbin(coords[l][0], coords[l][1], cmap='Greys', alpha=0.6, gridsize=8) axes[i].scatter(coords[l][0], coords[l][1], c='black') else: axes[i].hexbin(coords[l][0][indices], coords[l][1][indices], cmap=cms[i], alpha=0.6, gridsize=8) axes[i].scatter(coords[l][0][indices], coords[l][1][indices], c='black') else: print "Undefined plot type. Will NOT plot!" if savename is not None: plt.savefig(savename, dpi=300) if show is True: plt.show()
import os, sys import cPickle import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import matplotlib.image as image # import tqdm ### use mpl 1.0 style import matplotlib as mpl mpl.style.use('classic') import seaborn.apionly as sns colors = sns.color_palette("colorblind") sns.set_palette(sns.color_palette("colorblind")) from keplerian import keplerian from display import DisplayResults # sys.path.append('/home/joao/Work/OPEN') # from OPEN.ext.keplerian import keplerian sys.path.append('.') from styler import styler # res = DisplayResults('') # res.sample = np.atleast_2d(np.loadtxt('sample.txt')) res = cPickle.load(open('BL2009_joss_figure1.pickle'))
arr_dtemp = Dataset(if_temp)['TREFHT_With-Aerosol'][:] - Dataset(if_temp)[ 'TREFHT_' + p_scen][:] if_dyr = _env.odir_root + '/sim_temperature_running_mean/Year-Delayed_RunningAvg_' + p_scen + '.nc' arr_year = Dataset(if_dyr)['TREFHT'][:] if_rgdp = _env.odir_root + '/gdp_' + ds + '/GDP_Changes_Burke_country-lag0_' + str( year) + '_' + ds + '_' + p_scen + '_gridded.nc' arr_gdp = Dataset(if_rgdp)['GDP_Ratio_Median'][:] * 100 # to percent fig = plt.figure(figsize=(5, 20)) #===============================Bar: changes in sulfate burden============================== otbl_t_b = pd.DataFrame(index=np.arange(0, 0.17, 0.01), columns=['aod', 'color']) #otbl_t_b['color'] = sns.color_palette('PuBuGn_d',17).as_hex()[::-1] otbl_t_b['color'] = sns.color_palette('magma', 17).as_hex()[::-1] for itick, tick in enumerate(otbl_t_b.index): if itick == (len(otbl_t_b) - 1): ind = np.where(arr_aod >= 0.17) otbl_t_b.loc[tick, 'aod'] = (P_grid[ind]).sum() else: ind = np.where((arr_aod >= itick * 0.01) & (arr_aod < (itick + 1) * 0.01)) otbl_t_b.loc[tick, 'aod'] = (P_grid[ind]).sum() ax = fig.add_subplot(411) (otbl_t_b['aod'] / 1e9).plot(kind='bar', width=1, colors=otbl_t_b['color']) print(plt.xlim()) plt.xlim([-0.5, 16.5]) plt.xticks(np.arange(18)[::2] - 0.5,
def registration_qc( df, anova_type=3, cmap="Set3", extra=False, extra_cmap=EXTRA_COLORSET, group={"sub": "Subject"}, model="{value} ~ C({extra}) + C({group}) + C({repeat}) -1", print_model=False, print_anova=False, repeat={"ses": "Session"}, samri_style=True, save_as=False, show=True, value={"similarity": "Similarity"}, values_rename={}, ): """Aggregate plot of similarity metrics for registration quality control Parameters ---------- df : pandas.DataFrame or str Pandas Dataframe or CSV file containing similarity scores. anova_type : int, optional Type of the ANOVA to use for model analysis. Consult [1]_ for a theoretical overview, and `statsmodels.stats.anova.anova_lm` for the implementation we use. cmap : str or list, optional If a string, the variable specifies the matplotlib colormap [2]_ (qualitative colormaps are recommended) to use for `repeat` highlighting. If a List, the variable should be a list of colors (e.g. `["#00FF00","#2222FF"]`). extra_cmap : str or list, optional If a string, the variable specifies the matplotlib colormap [2]_ (qualitative colormaps are recommended) to use for `extra` highlighting, which is applied as a contour to the `repeat`-colored pacthes. If a List, the variable should be a list of colors (e.g. `["#00FF00","#2222FF"]`). group : str or dict, optional Column of `df` to use as the group factor (values of this factor will represent the x-axis). If a dictionary is passed, the column named for the key of the dictionary is renamed to the value, and the value name is then used as the group factor. This is useful for the input of longer but clearer names for plotting. model : string, optional A string specifying the ANOVA formula as a statsmodels function [3]_. It may contain string substitutions (e.g. `"{value} ~ C({group})"`). print_model : bool, optional Whether to print the model output table. print_anova : bool, optional Whether to print the ANOVA output table. samri_style : bool, optional Whether to apply a generic SAMRI style to the plot. save_as : str, optional Path under which to save the generated plot (format is interpreted from provided extension). show : bool, optional Whether to show the plot in an interactive window. repeat : str or dict, optional Column of `df` to use as the repeat factor (values of this factor will be represent via different hues, according to `cmap`). If a dictionary is passed, the column named for the key of the dictionary is renamed to the value, and the value name is then used as the group factor. This is useful for the input of longer but clearer names for plotting. value : str or dict, optional Column of `df` to use as the value (this variable will be represented on the y-axis). If a dictionary is passed, the column named for the key of the dictionary is renamed to the value, and the value name is then used as the group factor. This is useful for the input of longer but clearer names for plotting. values_rename : dict, optional Dictionary used to rename values in `df`. This is useful for the input of longer but clearer names for plotting (this parameter will not rename column names, for renaming those, see parameters `extra`, `group`, `repeat`, and `value`). Returns ------- pandas.DataFrame ANOVA summary table in DataFrame format. Reference ---------- .. [1] http://goanna.cs.rmit.edu.au/~fscholer/anova.php .. [2] https://matplotlib.org/examples/color/colormaps_reference.html .. [3] http://www.statsmodels.org/dev/example_formulas.html """ import seaborn.apionly as sns import statsmodels.api as sm import statsmodels.formula.api as smf if samri_style: this_path = path.dirname(path.realpath(__file__)) plt.style.use(path.join(this_path, "samri.conf")) try: if isinstance(df, basestring): df = path.abspath(path.expanduser(df)) df = pd.read_csv(df) except NameError: if isinstance(df, str): df = path.abspath(path.expanduser(df)) df = pd.read_csv(df) for key in values_rename: df.replace(to_replace=key, value=values_rename[key], inplace=True) column_renames = {} if isinstance(value, dict): column_renames.update(value) value = list(value.values())[0] if isinstance(group, dict): column_renames.update(group) group = list(group.values())[0] if isinstance(repeat, dict): column_renames.update(repeat) repeat = list(repeat.values())[0] if isinstance(extra, dict): column_renames.update(extra) extra = list(extra.values())[0] df = df.rename(columns=column_renames) model = model.format(value=value, group=group, repeat=repeat, extra=extra) regression_model = smf.ols(model, data=df).fit() if print_model: print(regression_model.summary()) anova_summary = sm.stats.anova_lm(regression_model, typ=anova_type) if print_anova: print(anova_summary) if extra: myplot = sns.swarmplot( x=group, y=value, hue=extra, data=df, size=rcParams["lines.markersize"] * 1.4, palette=sns.color_palette(extra_cmap), ) myplot = sns.swarmplot( x=group, y=value, hue=repeat, data=df, edgecolor=(1, 1, 1, 0.0), linewidth=rcParams["lines.markersize"] * .4, palette=sns.color_palette(cmap), ) plt.legend(loc=rcParams["legend.loc"]) if show: sns.plt.show() if save_as: plt.savefig(path.abspath(path.expanduser(save_as)), bbox_inches='tight') return anova_summary
import numpy as np import os import seaborn.apionly as sns sns.set_palette('muted') cls = (sns.color_palette()) import matplotlib.pyplot as plt save_folder = '/Users/Adriaan/GitHubRepos/DiCarloLab_Repositories/Paper_16_RestlessTuning/Figures' save_format = 'pdf' def make_figure(fig_name='timing_tech', Acquisition_time=np.array([1.6, 0.122, 0.122]), AWG_overhead=np.array([0.093, 0.093, 0]), Processing_overhead=np.array([.164+.063, .164+.063, 0]), Overhead=np.array([0.04, 0.04, 0.04]), methods=('Conventional-', 'Restless-', 'Restless+'), ): cls = (sns.color_palette('muted')) plt.rcParams.update({'font.size': 9, 'legend.labelspacing': 0, 'legend.columnspacing': .3, 'legend.handletextpad': .2}) f, ax = plt.subplots(figsize=(3.3, .9)) y_pos = np.array([.8, 0, -.8])+.1 lefts = np.array([0, 0, 0]) ax.barh(y_pos, AWG_overhead, color=cls[2], align='center', height=0.6, label='Set pars.') lefts = lefts+np.array(AWG_overhead)
'Temp_mean_climatological', 'Temp_mean_noaero', 'Temp_Changes' ]].copy() for gc in [ 'iso', sgdp_year + '_gdp', sgdp_year + '_pop', 'GDP_median_benefit_ratio' ]: mtbl_tg[gc] = itbl_gdp[gc].copy() ############################################################################## ##########################Panel a########################### fig = plt.figure(figsize=(9, 13)) ax = plt.subplot(211) my_cmap = ListedColormap(sns.color_palette( 'viridis', 11).as_hex()) #[::-1]) #modified by yz mar21,2019, suggested by SJD pscat = plt.scatter(-mtbl_tg['Temp_Changes'], mtbl_tg['GDP_median_benefit_ratio'], c=mtbl_tg['Temp_mean_climatological'], vmin=-3, vmax=30, cmap=my_cmap, s=np.sqrt(mtbl_tg['2010_gdp'] / 1e7), edgecolors='none', alpha=0.8, label=None) ##global mean results g_pop = mtbl_tg['2010_pop'].sum()
cf = 1 itbl_temp_20_ste.loc[year, cols] = stats.sem( itbls_temp_20_sam[cols][year + 10]) / np.sqrt(cf) itbl_temp_20_avg.drop(np.arange(2001, 2020), inplace=True) itbl_temp_20_avg.index = itbl_temp_20_avg.index + 10 itbl_temp_20_ste.drop(np.arange(2001, 2020), inplace=True) itbl_temp_20_ste.index = itbl_temp_20_ste.index + 10 fig = plt.figure(figsize=(6.5, 14)) ax = fig.add_subplot(2, 1, 1) plt.hlines(0, 1850, 2020, lw=1) colors = { scen_base: sns.color_palette("Blues", 10), scen_aero: sns.color_palette("Reds", 10), 'Diff': sns.color_palette("Purples", 10) } for scen in [scen_base, scen_aero, 'Diff']: cp = colors[scen] for ens in np.arange(1, nens + 1): plt.scatter(np.arange(1950, 2020), itbl_temp.loc[np.arange(1950, 2020), scen + '%d' % ens], marker='o', c=[cp[6]], s=4, alpha=0.7)
def pairedcontrast(data, x, y, idcol, reps = 3000, statfunction = None, idx = None, figsize = None, beforeAfterSpacer = 0.01, violinWidth = 0.005, floatOffset = 0.05, showRawData = False, showAllYAxes = False, floatContrast = True, smoothboot = False, floatViolinOffset = None, showConnections = True, summaryBar = False, contrastYlim = None, swarmYlim = None, barWidth = 0.005, rawMarkerSize = 8, rawMarkerType = 'o', summaryMarkerSize = 10, summaryMarkerType = 'o', summaryBarColor = 'grey', meansSummaryLineStyle = 'solid', contrastZeroLineStyle = 'solid', contrastEffectSizeLineStyle = 'solid', contrastZeroLineColor = 'black', contrastEffectSizeLineColor = 'black', pal = None, legendLoc = 2, legendFontSize = 12, legendMarkerScale = 1, axis_title_size = None, yticksize = None, xticksize = None, tickAngle=45, tickAlignment='right', **kwargs): # Preliminaries. data = data.dropna() # plot params if axis_title_size is None: axis_title_size = 15 if yticksize is None: yticksize = 12 if xticksize is None: xticksize = 12 axisTitleParams = {'labelsize' : axis_title_size} xtickParams = {'labelsize' : xticksize} ytickParams = {'labelsize' : yticksize} rc('axes', **axisTitleParams) rc('xtick', **xtickParams) rc('ytick', **ytickParams) ## If `idx` is not specified, just take the FIRST TWO levels alphabetically. if idx is None: idx = tuple(np.unique(data[x])[0:2],) else: # check if multi-plot or not if all(isinstance(element, str) for element in idx): # if idx is supplied but not a multiplot (ie single list or tuple) if len(idx) != 2: print(idx, "does not have length 2.") sys.exit(0) else: idx = (tuple(idx, ),) elif all(isinstance(element, tuple) for element in idx): # if idx is supplied, and it is a list/tuple of tuples or lists, we have a multiplot! if ( any(len(element) != 2 for element in idx) ): # If any of the tuples contain more than 2 elements. print(element, "does not have length 2.") sys.exit(0) if floatViolinOffset is None: floatViolinOffset = beforeAfterSpacer/2 if contrastYlim is not None: contrastYlim = np.array([contrastYlim[0],contrastYlim[1]]) if swarmYlim is not None: swarmYlim = np.array([swarmYlim[0],swarmYlim[1]]) ## Here we define the palette on all the levels of the 'x' column. ## Thus, if the same pandas dataframe is re-used across different plots, ## the color identity of each group will be maintained. ## Set palette based on total number of categories in data['x'] or data['hue_column'] if 'hue' in kwargs: u = kwargs['hue'] else: u = x if ('color' not in kwargs and 'hue' not in kwargs): kwargs['color'] = 'k' if pal is None: pal = dict( zip( data[u].unique(), sns.color_palette(n_colors = len(data[u].unique())) ) ) else: pal = pal # Initialise figure. if figsize is None: if len(idx) > 2: figsize = (12,(12/np.sqrt(2))) else: figsize = (6,6) fig = plt.figure(figsize = figsize) # Initialise GridSpec based on `levs_tuple` shape. gsMain = gridspec.GridSpec( 1, np.shape(idx)[0]) # 1 row; columns based on number of tuples in tuple. # Set default statfunction if statfunction is None: statfunction = np.mean # Create list to collect all the contrast DataFrames generated. contrastList = list() contrastListNames = list() for gsIdx, xlevs in enumerate(idx): ## Pivot tempdat to get before and after lines. data_pivot = data.pivot_table(index = idcol, columns = x, values = y) # Start plotting!! if floatContrast is True: ax_raw = fig.add_subplot(gsMain[gsIdx], frame_on = False) ax_contrast = ax_raw.twinx() else: gsSubGridSpec = gridspec.GridSpecFromSubplotSpec(2, 1, subplot_spec = gsMain[gsIdx]) ax_raw = plt.Subplot(fig, gsSubGridSpec[0, 0], frame_on = False) ax_contrast = plt.Subplot(fig, gsSubGridSpec[1, 0], sharex = ax_raw, frame_on = False) ## Plot raw data as swarmplot or stripplot. if showRawData is True: swarm_raw = sns.swarmplot(data = data, x = x, y = y, order = xlevs, ax = ax_raw, palette = pal, size = rawMarkerSize, marker = rawMarkerType, **kwargs) else: swarm_raw = sns.stripplot(data = data, x = x, y = y, order = xlevs, ax = ax_raw, palette = pal, **kwargs) swarm_raw.set_ylim(swarmYlim) ## Get some details about the raw data. maxXBefore = max(swarm_raw.collections[0].get_offsets().T[0]) minXAfter = min(swarm_raw.collections[1].get_offsets().T[0]) if showRawData is True: #beforeAfterSpacer = (getSwarmSpan(swarm_raw, 0) + getSwarmSpan(swarm_raw, 1))/2 beforeAfterSpacer = 1 xposAfter = maxXBefore + beforeAfterSpacer xAfterShift = minXAfter - xposAfter ## shift the after swarmpoints closer for aesthetic purposes. offsetSwarmX(swarm_raw.collections[1], -xAfterShift) ## pandas DataFrame of 'before' group x1 = pd.DataFrame({str(xlevs[0] + '_x') : pd.Series(swarm_raw.collections[0].get_offsets().T[0]), xlevs[0] : pd.Series(swarm_raw.collections[0].get_offsets().T[1]), '_R_' : pd.Series(swarm_raw.collections[0].get_facecolors().T[0]), '_G_' : pd.Series(swarm_raw.collections[0].get_facecolors().T[1]), '_B_' : pd.Series(swarm_raw.collections[0].get_facecolors().T[2]), }) ## join the RGB columns into a tuple, then assign to a column. x1['_hue_'] = x1[['_R_', '_G_', '_B_']].apply(tuple, axis=1) x1 = x1.sort_values(by = xlevs[0]) x1.index = data_pivot.sort_values(by = xlevs[0]).index ## pandas DataFrame of 'after' group ### create convenient signifiers for column names. befX = str(xlevs[0] + '_x') aftX = str(xlevs[1] + '_x') x2 = pd.DataFrame( {aftX : pd.Series(swarm_raw.collections[1].get_offsets().T[0]), xlevs[1] : pd.Series(swarm_raw.collections[1].get_offsets().T[1])} ) x2 = x2.sort_values(by = xlevs[1]) x2.index = data_pivot.sort_values(by = xlevs[1]).index ## Join x1 and x2, on both their indexes. plotPoints = x1.merge(x2, left_index = True, right_index = True, how='outer') ## Add the hue column if hue argument was passed. if 'hue' in kwargs: h = kwargs['hue'] plotPoints[h] = data.pivot(index = idcol, columns = x, values = h)[xlevs[0]] swarm_raw.legend(loc = legendLoc, fontsize = legendFontSize, markerscale = legendMarkerScale) ## Plot the lines to join the 'before' points to their respective 'after' points. if showConnections is True: for i in plotPoints.index: ax_raw.plot([ plotPoints.ix[i, befX], plotPoints.ix[i, aftX] ], [ plotPoints.ix[i, xlevs[0]], plotPoints.ix[i, xlevs[1]] ], linestyle = 'solid', color = plotPoints.ix[i, '_hue_'], linewidth = 0.75, alpha = 0.75 ) ## Hide the raw swarmplot data if so desired. if showRawData is False: swarm_raw.collections[0].set_visible(False) swarm_raw.collections[1].set_visible(False) if showRawData is True: #maxSwarmSpan = max(np.array([getSwarmSpan(swarm_raw, 0), getSwarmSpan(swarm_raw, 1)]))/2 maxSwarmSpan = 0.5 else: maxSwarmSpan = barWidth ## Plot Summary Bar. if summaryBar is True: # Calculate means means = data.groupby([x], sort = True).mean()[y] # # Calculate medians # medians = data.groupby([x], sort = True).median()[y] ## Draw summary bar. bar_raw = sns.barplot(x = means.index, y = means.values, order = xlevs, ax = ax_raw, ci = 0, facecolor = summaryBarColor, alpha = 0.25) ## Draw zero reference line. ax_raw.add_artist(Line2D( (ax_raw.xaxis.get_view_interval()[0], ax_raw.xaxis.get_view_interval()[1]), (0,0), color='black', linewidth=0.75 ) ) ## get swarm with largest span, set as max width of each barplot. for i, bar in enumerate(bar_raw.patches): x_width = bar.get_x() width = bar.get_width() centre = x_width + width/2. if i == 0: bar.set_x(centre - maxSwarmSpan/2.) else: bar.set_x(centre - xAfterShift - maxSwarmSpan/2.) bar.set_width(maxSwarmSpan) # Get y-limits of the treatment swarm points. beforeRaw = pd.DataFrame( swarm_raw.collections[0].get_offsets() ) afterRaw = pd.DataFrame( swarm_raw.collections[1].get_offsets() ) before_leftx = min(beforeRaw[0]) after_leftx = min(afterRaw[0]) after_rightx = max(afterRaw[0]) after_stat_summary = statfunction(beforeRaw[1]) # Calculate the summary difference and CI. plotPoints['delta_y'] = plotPoints[xlevs[1]] - plotPoints[xlevs[0]] plotPoints['delta_x'] = [0] * np.shape(plotPoints)[0] tempseries = plotPoints['delta_y'].tolist() test = tempseries.count(tempseries[0]) != len(tempseries) bootsDelta = bootstrap(plotPoints['delta_y'], statfunction = statfunction, smoothboot = smoothboot, reps = reps) summDelta = bootsDelta['summary'] lowDelta = bootsDelta['bca_ci_low'] highDelta = bootsDelta['bca_ci_high'] # set new xpos for delta violin. if floatContrast is True: if showRawData is False: xposPlusViolin = deltaSwarmX = after_rightx + floatViolinOffset else: xposPlusViolin = deltaSwarmX = after_rightx + maxSwarmSpan else: xposPlusViolin = xposAfter if showRawData is True: # If showRawData is True and floatContrast is True, # set violinwidth to the barwidth. violinWidth = maxSwarmSpan xmaxPlot = xposPlusViolin + violinWidth # Plot the summary measure. ax_contrast.plot(xposPlusViolin, summDelta, marker = 'o', markerfacecolor = 'k', markersize = summaryMarkerSize, alpha = 0.75 ) # Plot the CI. ax_contrast.plot([xposPlusViolin, xposPlusViolin], [lowDelta, highDelta], color = 'k', alpha = 0.75, linestyle = 'solid' ) # Plot the violin-plot. v = ax_contrast.violinplot(bootsDelta['stat_array'], [xposPlusViolin], widths = violinWidth, showextrema = False, showmeans = False) halfviolin(v, half = 'right', color = 'k') # Remove left axes x-axis title. ax_raw.set_xlabel("") # Remove floating axes y-axis title. ax_contrast.set_ylabel("") # Set proper x-limits ax_raw.set_xlim(before_leftx - beforeAfterSpacer/2, xmaxPlot) ax_raw.get_xaxis().set_view_interval(before_leftx - beforeAfterSpacer/2, after_rightx + beforeAfterSpacer/2) ax_contrast.set_xlim(ax_raw.get_xlim()) if floatContrast is True: # Set the ticks locations for ax_raw. ax_raw.get_xaxis().set_ticks((0, xposAfter)) # Make sure they have the same y-limits. ax_contrast.set_ylim(ax_raw.get_ylim()) # Drawing in the x-axis for ax_raw. ## Set the tick labels! ax_raw.set_xticklabels(xlevs, rotation = tickAngle, horizontalalignment = tickAlignment) ## Get lowest y-value for ax_raw. y = ax_raw.get_yaxis().get_view_interval()[0] # Align the left axes and the floating axes. align_yaxis(ax_raw, statfunction(plotPoints[xlevs[0]]), ax_contrast, 0) # Add label to floating axes. But on ax_raw! ax_raw.text(x = deltaSwarmX, y = ax_raw.get_yaxis().get_view_interval()[0], horizontalalignment = 'left', s = 'Difference', fontsize = 15) # Set reference lines ## zero line ax_contrast.hlines(0, # y-coordinate ax_contrast.xaxis.get_majorticklocs()[0], # x-coordinates, start and end. ax_raw.xaxis.get_view_interval()[1], linestyle = 'solid', linewidth = 0.75, color = 'black') ## effect size line ax_contrast.hlines(summDelta, ax_contrast.xaxis.get_majorticklocs()[1], ax_raw.xaxis.get_view_interval()[1], linestyle = 'solid', linewidth = 0.75, color = 'black') # Align the left axes and the floating axes. align_yaxis(ax_raw, after_stat_summary, ax_contrast, 0.) else: # Set the ticks locations for ax_raw. ax_raw.get_xaxis().set_ticks((0, xposAfter)) fig.add_subplot(ax_raw) fig.add_subplot(ax_contrast) ax_contrast.set_ylim(contrastYlim) # Calculate p-values. # 1-sample t-test to see if the mean of the difference is different from 0. ttestresult = ttest_1samp(plotPoints['delta_y'], popmean = 0)[1] bootsDelta['ttest_pval'] = ttestresult contrastList.append(bootsDelta) contrastListNames.append( str(xlevs[1])+' v.s. '+str(xlevs[0]) ) # Turn contrastList into a pandas DataFrame, contrastList = pd.DataFrame(contrastList).T contrastList.columns = contrastListNames # Now we iterate thru the contrast axes to normalize all the ylims. for j,i in enumerate(range(1, len(fig.get_axes()), 2)): axx=fig.get_axes()[i] ## Get max and min of the dataset. lower = np.min(contrastList.ix['stat_array',j]) upper = np.max(contrastList.ix['stat_array',j]) meandiff = contrastList.ix['summary', j] ## Make sure we have zero in the limits. if lower > 0: lower = 0. if upper < 0: upper = 0. ## Get tick distance on raw axes. ## This will be the tick distance for the contrast axes. rawAxesTicks = fig.get_axes()[i-1].yaxis.get_majorticklocs() rawAxesTickDist = rawAxesTicks[1] - rawAxesTicks[0] ## First re-draw of axis with new tick interval axx.yaxis.set_major_locator(MultipleLocator(rawAxesTickDist)) newticks1 = fig.get_axes()[i].get_yticks() if floatContrast is False: if (showAllYAxes is False and i in range( 2, len(fig.get_axes())) ): axx.get_yaxis().set_visible(showAllYAxes) else: ## Obtain major ticks that comfortably encompass lower and upper. newticks2 = list() for a,b in enumerate(newticks1): if (b >= lower and b <= upper): # if the tick lies within upper and lower, take it. newticks2.append(b) # if the meandiff falls outside of the newticks2 set, add a tick in the right direction. if np.max(newticks2) < meandiff: ind = np.where(newticks1 == np.max(newticks2))[0][0] # find out the max tick index in newticks1. newticks2.append( newticks1[ind+1] ) elif meandiff < np.min(newticks2): ind = np.where(newticks1 == np.min(newticks2))[0][0] # find out the min tick index in newticks1. newticks2.append( newticks1[ind-1] ) newticks2 = np.array(newticks2) newticks2.sort() axx.yaxis.set_major_locator(FixedLocator(locs = newticks2)) ## Draw zero reference line. axx.hlines(y = 0, xmin = fig.get_axes()[i].get_xaxis().get_view_interval()[0], xmax = fig.get_axes()[i].get_xaxis().get_view_interval()[1], linestyle = contrastZeroLineStyle, linewidth = 0.75, color = contrastZeroLineColor) sns.despine(ax = fig.get_axes()[i], trim = True, bottom = False, right = True, left = False, top = True) ## Draw back the lines for the relevant y-axes. drawback_y(axx) ## Draw back the lines for the relevant x-axes. drawback_x(axx) elif floatContrast is True: ## Get the original ticks on the floating y-axis. newticks1 = fig.get_axes()[i].get_yticks() ## Obtain major ticks that comfortably encompass lower and upper. newticks2 = list() for a,b in enumerate(newticks1): if (b >= lower and b <= upper): # if the tick lies within upper and lower, take it. newticks2.append(b) # if the meandiff falls outside of the newticks2 set, add a tick in the right direction. if np.max(newticks2) < meandiff: ind = np.where(newticks1 == np.max(newticks2))[0][0] # find out the max tick index in newticks1. newticks2.append( newticks1[ind+1] ) elif meandiff < np.min(newticks2): ind = np.where(newticks1 == np.min(newticks2))[0][0] # find out the min tick index in newticks1. newticks2.append( newticks1[ind-1] ) newticks2 = np.array(newticks2) newticks2.sort() ## Re-draw the axis. axx.yaxis.set_major_locator(FixedLocator(locs = newticks2)) ## Despine and trim the axes. sns.despine(ax = axx, trim = True, bottom = False, right = False, left = True, top = True) for i in range(0, len(fig.get_axes()), 2): # Loop through the raw data swarmplots and despine them appropriately. if floatContrast is True: sns.despine(ax = fig.get_axes()[i], trim = True, right = True) else: sns.despine(ax = fig.get_axes()[i], trim = True, bottom = True, right = True) fig.get_axes()[i].get_xaxis().set_visible(False) # Draw back the lines for the relevant y-axes. ymin = fig.get_axes()[i].get_yaxis().get_majorticklocs()[0] ymax = fig.get_axes()[i].get_yaxis().get_majorticklocs()[-1] x, _ = fig.get_axes()[i].get_xaxis().get_view_interval() fig.get_axes()[i].add_artist(Line2D((x, x), (ymin, ymax), color='black', linewidth=1.5)) # Zero gaps between plots on the same row, if floatContrast is False if (floatContrast is False and showAllYAxes is False): gsMain.update(wspace = 0) else: # Tight Layout! gsMain.tight_layout(fig) # And we're done. rcdefaults() # restore matplotlib defaults. sns.set() # restore seaborn defaults. return fig, contrastList
def lic_plot(lic_data, background_data = None, F_m = 0.0, F_M = 0.0, cmap = "YlOrRd"): """ Code to visualize an LIC plot. By Susan Clark. lic_data :: output of LIC code background_data :: background color map, e.g. density or vector magnitude F_m :: contrast enhancement parameter - see below F_M :: contrast enhancement parameter - see below cmap :: matplotlib recognized colormap Contrast Enhancement from http://www.paraview.org/Wiki/ParaView/Line_Integral_Convolution#Image_LIC_CE_stages L_ij = (L_ij - m) / (M - m) L = HSL lightness. m = lightness to map to 0. M = lightness to map to 1. m = min(L) + F_m * (max(L) - min(L)) M = max(L) - F_M * (max(L) - min(L)) F_m and F_M take values between 0 and 1. Increase F_m -> darker colors. Increase F_M -> brighter colors. """ # 1. Compute nhi values # 2. Interpolate these values onto cmap to find corresponding RGBA value # 3. Convert RGB value to HSV, use these Hues + Saturations # 4. Assign Lightness as lic amplitude # 5. Display HLS map. # Normalize background data if background_data == None: background_data = np.ones(lic_data.shape) hues = background_data / np.nanmax(background_data) sats = np.ones(lic_data.shape) licmax = np.nanmax(lic_data) licmin = np.nanmin(lic_data) # Contrast enhancement m = licmin + F_m * (licmax - licmin) M = licmax - F_M * (licmax - licmin) vals = (lic_data - m) / (M - m) y, x = hues.shape # Map background data onto RGB colormap cmap = mpl.colors.ListedColormap(sns.color_palette(cmap, 256)) background_data_rgb = cmap(background_data) # Only need RGB, not RGBA background_data_rgb = background_data_rgb[:, :, 0:3] # Map to Hue - Saturation - Value hsv = mpl.colors.rgb_to_hsv(background_data_rgb) # to work in hls instead of hsv hs = hsv[:, :, 0].flatten() ls = vals.flatten() ss = hsv[:, :, 1].flatten() r = np.zeros(len(hues.flatten())) g = np.zeros(len(hues.flatten())) b = np.zeros(len(hues.flatten())) maxls = np.nanmax(ls) minls = np.nanmin(ls) # Translate HLS to RGB for i in xrange(len(hues.flatten())): r[i], g[i], b[i] = colorsys.hls_to_rgb(hs[i], ls[i], ss[i]) r = r.reshape(lic_data.shape) g = g.reshape(lic_data.shape) b = b.reshape(lic_data.shape) rgb = np.zeros((y, x, 3), np.float_) rgb[:, :, 0] = r rgb[:, :, 1] = g rgb[:, :, 2] = b return rgb
def make_figure(F_vec, idxs, Ncl, mn_eps, sem_eps, std_eps, sem_std, fig_name='signal_noise', Ncl_cont=None, simple_std=None, model_avg=None, model_std=None, proj_avg=None, proj_std=None): if Ncl_cont is None: Ncl_cont = Ncl if model_avg is not None: avg1, avg2, avg3 = model_avg if model_std is not None: std1, std2, std3 = model_std if simple_std is not None: std_fix1, std_fix2, std_fix3 = simple_std latexify() plt.rcParams.update(params) f, ax = plt.subplots(figsize=cm2inch(8.6, 7)) ncols = 1 nrows = 2 height_ratios = np.ones(nrows) height_ratios[1] = .6 width_ratios = np.ones(ncols) gs = gridspec.GridSpec(nrows, ncols, wspace=.05, hspace=0, height_ratios=height_ratios, width_ratios=width_ratios) ax = plt.subplot(gs[0]) colors = sns.color_palette() labels = [ '$F_\mathrm{Cl}^\mathrm{a}='+' {:.4f}$, '.format((F_vec[idxs[0][0]])) + r'$\Delta F_\mathrm{Cl} =' + ' {:.4f} $'.format((F_vec[idxs[0][1]]-F_vec[idxs[0][0]])), '$F_\mathrm{Cl}^\mathrm{a}='+' {:.4f}$, '.format((F_vec[idxs[1][0]])) + r'$\Delta F_\mathrm{Cl} =' + ' {:.4f} $'.format((F_vec[idxs[1][1]]-F_vec[idxs[1][0]])), '$F_\mathrm{Cl}^\mathrm{a}='+' {:.4f}$, '.format((F_vec[idxs[2][0]])) + r'$\Delta F_\mathrm{Cl} ='+' {:.4f} $'.format((F_vec[idxs[2][1]]-F_vec[idxs[2][0]]))] markers = ['o', 'd', '^'] # Model averages if model_avg is not None: ax.plot(Ncl_cont, np.array(avg1), color=colors[0]) ax.plot(Ncl_cont, np.array(avg2), color=colors[1]) ax.plot(Ncl_cont, np.array(avg3), color=colors[2]) if proj_avg is not None: ax.plot(Ncl_cont, np.array(proj_avg), color=colors[3]) # Data averages print(np.shape(mn_eps)) for i, id_pair in enumerate(idxs): ax.errorbar(Ncl, (mn_eps[:, id_pair[0]]-mn_eps[:, id_pair[1]])/100., (sem_eps[:, id_pair[1]] ** 2+sem_eps[:, id_pair[0]]**2)**.5/100., marker=markers[i], ls='', label=labels[i],) handles, labels = ax.get_legend_handles_labels() ax.legend(handles[::-1], labels[::-1], frameon=False, loc=(.0, .63)) ax.text(.65, .85, r'$\Delta F_\mathrm{Cl} = F_\mathrm{Cl}^\mathrm{b} - F_\mathrm{Cl}^\mathrm{a}$', transform=ax.transAxes, fontsize=7) ax.hlines(0, 0, 1600, linestyle='dotted') ax.set_ylim(-0.02, 0.17) ax.set_ylabel('') ax.set_xlabel(r'$N_{\mathrm{Cl}}$') ax.set_yticks([0, 0.05, 0.1, 0.15]) plt.setp(ax.get_xticklabels(), visible=False) # Model sigmas ax2 = plt.subplot(gs[1], sharex=ax) if model_std is not None: ax2.plot(Ncl_cont, np.array(std1), color=colors[0]) ax2.plot(Ncl_cont, np.array(std2), color=colors[1]) ax2.plot(Ncl_cont, np.array(std3), color=colors[2]) if proj_std is not None: ax2.plot(Ncl_cont, np.array(proj_std), color=colors[3]) # simple model if simple_std is not None: ax2.plot(Ncl_cont, np.array(std_fix1), color=colors[0], linestyle='--') ax2.plot(Ncl_cont, np.array(std_fix2), color=colors[1], linestyle='--') ax2.plot(Ncl_cont, np.array(std_fix3), color=colors[2], linestyle='--') # data sigma for i, id_pair in enumerate(idxs): ax2.errorbar(Ncl, (std_eps[:, id_pair[1]]+std_eps[:, id_pair[0]])*.5/100, (sem_std[:, id_pair[1]]+sem_std[:, id_pair[0]])*.5/100, marker=markers[i], ls='') # Dummy lines for legend if simple_std is not None: ax2.plot([1e6, 1e7], [0, 0], color='grey', linestyle='--', label='Simple model') if model_avg is not None: ax2.plot([1e6, 1e7], [0, 0], color='k', linestyle='-', label='Extensive model') ax2.legend(frameon=False, loc=(.2, .05), ncol=2) ax2.set_ylim(0., 0.0155) ax2.set_xlabel('Number of Cliffords, $N_{\mathrm{Cl}}$') ax2.set_ylabel('') ax2.set_yticks([0, 0.005, 0.01, 0.015]) ax.set_xlim(1, 2000) ax.set_xscale('log') ax.text(0.92, .88, '(a)', transform=ax.transAxes) ax2.text(0.92, .88, '(b)', transform=ax2.transAxes) ax.text(-0.14, .5, r'Signal, $ {\Delta\overline{\varepsilon_\mathrm{R}}}$', color='k', transform=ax.transAxes, ha='center', va='center', rotation='90') ax2.text(-0.14, .5, r'Noise, $\overline{\sigma_{\varepsilon _\mathrm{R}}}$', color='k', transform=ax2.transAxes, ha='center', va='center', rotation='90') plt.gcf().subplots_adjust(bottom=0.17) plt.subplots_adjust( left=0.14, bottom=0.11, right=.98, top=.99, wspace=0.1, hspace=0.1) for fmt in ['pdf']: if f is not None: save_name = os.path.abspath( os.path.join(save_folder, fig_name+'.{}'.format(fmt))) f.savefig(save_name, format=fmt, dpi=1200)
def test_circle(): size = 50 periodic = True # periodic = False graph = gt_gen.lattice([size, size], periodic=periodic) if periodic: figure_title = 'grid_periodic' else: figure_title = 'grid_non-periodic' indices = np.arange(size * size) rows = np.mod(indices, size) cols = np.floor(indices / size) v_pos = graph.new_vertex_property('vector<double>', vals=np.vstack((rows, cols)).T) radius = 10 center = (size + 1) * (size / 2) vertex_w = set([]) for i in range(-radius, radius): for j in range(-radius, radius): if i ** 2 + j ** 2 < radius ** 2: idx = j * size + i + center vertex_w.add(idx) jump = 1e-5 weight = graph.new_edge_property('double', vals=1) for idx in vertex_w: u = graph.vertex(idx) for e in u.out_edges(): if e.target() not in vertex_w: weight[e] = jump v_color = graph.new_vertex_property('vector<double>') for u in graph.vertices(): if graph.vertex_index[u] in vertex_w: v_color[u] = [1, 0, 0, 1] else: v_color[u] = [0, 0, 1, 1] vertex_w = list(vertex_w) x = np.linspace(-np.pi, np.pi, size) y = np.linspace(-np.pi, np.pi, size) xx, yy = np.meshgrid(x, y) z1 = np.sin(np.pi * xx).flatten() z2 = np.sin(2 * np.pi * yy).flatten() x_signal = z1 x_signal[vertex_w] = z2[vertex_w] palette = sns.color_palette('RdBu', n_colors=256, desat=.7) cmap = colors.ListedColormap(palette, N=256) plt.figure() plt.imshow(np.reshape(x_signal, (size, size)), interpolation='nearest', cmap=cmap) plt.savefig(figure_title + '_signal.pdf', dpi=300) n_eigs = 500 # graph.num_vertices() - 1 alpha = -1e-4 factories = [spec.ConvolutionSGFT(graph, n_eigs, tau=200, weight=weight), spec.PageRankSGFT(graph, n_eigs, alpha, weight=weight), spec.ConvolutionSGFT(graph, n_eigs, tau=5, weight=None), spec.PageRankSGFT(graph, n_eigs, alpha, weight=None)] sgft.comparison.compare_spectrograms(factories, x_signal, graph, v_pos, file_name=figure_title, show_ncomps=300) spec.show_window(factories[0], center, weight=weight, pos=v_pos, vertex_size=20, file_name=figure_title + '_w_window.png') spec.show_window(factories[1], center, weight=weight, pos=v_pos, vertex_size=20, file_name=figure_title + '_w_window_ppr.png') spec.show_window(factories[2], center, weight=None, pos=v_pos, vertex_size=20, file_name=figure_title + '_u_window.png') spec.show_window(factories[3], center, weight=None, pos=v_pos, vertex_size=20, file_name=figure_title + '_u_window_ppr.png')
def contrastplot( data, x=None, y=None, idx=None, idcol=None, alpha=0.75, axis_title_size=None, ci=95, contrastShareY=True, contrastEffectSizeLineStyle='solid', contrastEffectSizeLineColor='black', contrastYlim=None, contrastZeroLineStyle='solid', contrastZeroLineColor='black', connectPairs=True, effectSizeYLabel="Effect Size", figsize=None, floatContrast=True, floatSwarmSpacer=0.2, heightRatio=(1, 1), lineWidth=2, legend=True, legendFontSize=14, legendFontProps={}, paired=False, pairedDeltaLineAlpha=0.3, pairedDeltaLineWidth=1.2, pal=None, rawMarkerSize=8, rawMarkerType='o', reps=3000, showGroupCount=True, showCI=False, showAllYAxes=False, showRawData=True, smoothboot=False, statfunction=None, summaryBar=False, summaryBarColor='grey', summaryBarAlpha=0.25, summaryColour='black', summaryLine=True, summaryLineStyle='solid', summaryLineWidth=0.25, summaryMarkerSize=10, summaryMarkerType='o', swarmShareY=True, swarmYlim=None, tickAngle=45, tickAlignment='right', violinOffset=0.375, violinWidth=0.2, violinColor='k', xticksize=None, yticksize=None, **kwargs): '''Takes a pandas DataFrame and produces a contrast plot: either a Cummings hub-and-spoke plot or a Gardner-Altman contrast plot. Paired and unpaired options available. Keyword arguments: data: pandas DataFrame x: string column name containing categories to be plotted on the x-axis. y: string column name containing values to be plotted on the y-axis. idx: tuple flxible declaration of groupwise comparisons. idcol: string for paired plots. alpha: float alpha (transparency) of raw swarmed data points. axis_title_size=None ci=95 contrastShareY=True contrastEffectSizeLineStyle='solid' contrastEffectSizeLineColor='black' contrastYlim=None contrastZeroLineStyle='solid' contrastZeroLineColor='black' effectSizeYLabel="Effect Size" figsize=None floatContrast=True floatSwarmSpacer=0.2 heightRatio=(1,1) lineWidth=2 legend=True legendFontSize=14 legendFontProps={} paired=False pairedDeltaLineAlpha=0.3 pairedDeltaLineWidth=1.2 pal=None rawMarkerSize=8 rawMarkerType='o' reps=3000 showGroupCount=True showCI=False showAllYAxes=False showRawData=True smoothboot=False statfunction=None summaryBar=False summaryBarColor='grey' summaryBarAlpha=0.25 summaryColour='black' summaryLine=True summaryLineStyle='solid' summaryLineWidth=0.25 summaryMarkerSize=10 summaryMarkerType='o' swarmShareY=True swarmYlim=None tickAngle=45 tickAlignment='right' violinOffset=0.375 violinWidth=0.2 violinColor='k' xticksize=None yticksize=None Returns: An matplotlib Figure. Organization of figure Axes. ''' # Check that `data` is a pandas dataframe if 'DataFrame' not in str(type(data)): raise TypeError("The object passed to the command is not not a pandas DataFrame.\ Please convert it to a pandas DataFrame.") # make sure that at least x, y, and idx are specified. if x is None and y is None and idx is None: raise ValueError('You need to specify `x` and `y`, or `idx`. Neither has been specifed.') if x is None: # if x is not specified, assume this is a 'wide' dataset, with each idx being the name of a column. datatype='wide' # Check that the idx are legit columns. all_idx=np.unique([element for tupl in idx for element in tupl]) # # melt the data. # data=pd.melt(data,value_vars=all_idx) # x='variable' # y='value' else: # if x is specified, assume this is a 'long' dataset with each row corresponding to one datapoint. datatype='long' # make sure y is not none. if y is None: raise ValueError("`paired` is false, but no y-column given.") # Calculate Ns. counts=data.groupby(x)[y].count() # Get and set levels of data[x] if paired is True: violinWidth=0.1 # # Calculate Ns--which should be simply the number of rows in data. # counts=len(data) # is idcol supplied? if idcol is None and datatype=='long': raise ValueError('`idcol` has not been supplied but a paired plot is desired; please specify the `idcol`.') if idx is not None: # check if multi-plot or not if all(isinstance(element, str) for element in idx): # check that every idx is a column name. idx_not_in_cols=[n for n in idx if n not in data[x].unique()] if len(idx_not_in_cols)!=0: raise ValueError(str(idx_not_in_cols)+" cannot be found in the columns of `data`.") # data_wide_cols=[n for n in idx if n in data.columns] # if idx is supplied but not a multiplot (ie single list or tuple) if len(idx) != 2: raise ValueError(idx+" does not have length 2.") else: tuple_in=(tuple(idx, ),) widthratio=[1] elif all(isinstance(element, tuple) for element in idx): # if idx is supplied, and it is a list/tuple of tuples or lists, we have a multiplot! idx_not_in_cols=[n for tup in idx for n in tup if n not in data[x].unique()] if len(idx_not_in_cols)!=0: raise ValueError(str(idx_not_in_cols)+" cannot be found in the column "+x) # data_wide_cols=[n for tup in idx for n in tup if n in data.columns] if ( any(len(element) != 2 for element in idx) ): # If any of the tuples does not contain exactly 2 elements. raise ValueError(element+" does not have length 2.") # Make sure the widthratio of the seperate multiplot corresponds to how # many groups there are in each one. tuple_in=idx widthratio=[] for i in tuple_in: widthratio.append(len(i)) elif idx is None: raise ValueError('Please specify idx.') showRawData=False # Just show lines, do not show data. showCI=False # wait till I figure out how to plot this for sns.barplot. if datatype=='long': if idx is None: ## If `idx` is not specified, just take the FIRST TWO levels alphabetically. tuple_in=tuple(np.sort(np.unique(data[x]))[0:2],) # pivot the dataframe if it is long! data_pivot=data.pivot_table(index = idcol, columns = x, values = y) elif paired is False: if idx is None: widthratio=[1] tuple_in=( tuple(data[x].unique()) ,) if len(tuple_in[0])>2: floatContrast=False else: if all(isinstance(element, str) for element in idx): # if idx is supplied but not a multiplot (ie single list or tuple) # check all every idx specified can be found in data[x] idx_not_in_x=[n for n in idx if n not in data[x].unique()] if len(idx_not_in_x)!=0: raise ValueError(str(idx_not_in_x)+" cannot be found in the column "+x) tuple_in=(idx, ) widthratio=[1] if len(idx)>2: floatContrast=False elif all(isinstance(element, tuple) for element in idx): # if idx is supplied, and it is a list/tuple of tuples or lists, we have a multiplot! idx_not_in_x=[n for tup in idx for n in tup if n not in data[x].unique()] if len(idx_not_in_x)!=0: raise ValueError(str(idx_not_in_x)+" cannot be found in the column "+x) tuple_in=idx if ( any(len(element)>2 for element in tuple_in) ): # if any of the tuples in idx has more than 2 groups, we turn set floatContrast as False. floatContrast=False # Make sure the widthratio of the seperate multiplot corresponds to how # many groups there are in each one. widthratio=[] for i in tuple_in: widthratio.append(len(i)) else: raise TypeError("The object passed to `idx` consists of a mixture of single strings and tuples. \ Please make sure that `idx` is either a tuple of column names, or a tuple of tuples, for plotting.") # Ensure summaryLine and summaryBar are not displayed together. if summaryLine is True and summaryBar is True: summaryBar=True summaryLine=False # Turn off summary line if floatContrast is true if floatContrast: summaryLine=False # initialise statfunction if statfunction == None: statfunction=np.mean # Create list to collect all the contrast DataFrames generated. contrastList=list() contrastListNames=list() # Setting color palette for plotting. if pal is None: if 'hue' in kwargs: colorCol=kwargs['hue'] if colorCol not in data.columns: raise ValueError(colorCol+' is not a column name.') colGrps=data[colorCol].unique()#.tolist() plotPal=dict( zip( colGrps, sns.color_palette(n_colors=len(colGrps)) ) ) else: if datatype=='long': colGrps=data[x].unique()#.tolist() plotPal=dict( zip( colGrps, sns.color_palette(n_colors=len(colGrps)) ) ) if datatype=='wide': plotPal=np.repeat('k',len(data)) else: if datatype=='long': plotPal=pal if datatype=='wide': plotPal=list(map(lambda x:pal[x], data[hue])) if swarmYlim is None: # get range of _selected groups_. # u = list() # for t in tuple_in: # for i in np.unique(t): # u.append(i) # u = np.unique(u) u=np.unique([element for tupl in tuple_in for element in tupl]) if datatype=='long': tempdat=data[data[x].isin(u)] swarm_ylim=np.array([np.min(tempdat[y]), np.max(tempdat[y])]) if datatype=='wide': allMin=list() allMax=list() for col in u: allMin.append(np.min(data[col])) allMax.append(np.max(data[col])) swarm_ylim=np.array( [np.min(allMin),np.max(allMax)] ) swarm_ylim=np.round(swarm_ylim) else: swarm_ylim=np.array([swarmYlim[0],swarmYlim[1]]) if summaryBar is True: lims=swarm_ylim # check that 0 lies within the desired limits. # if not, extend (upper or lower) limit to zero. if 0 not in range( int(round(lims[0])),int(round(lims[1])) ): # turn swarm_ylim to integer range. # check if all negative:. if lims[0]<0. and lims[1]<0.: swarm_ylim=np.array([np.min(lims),0.]) # check if all positive. elif lims[0]>0. and lims[1]>0.: swarm_ylim=np.array([0.,np.max(lims)]) if contrastYlim is not None: contrastYlim=np.array([contrastYlim[0],contrastYlim[1]]) # plot params if axis_title_size is None: axis_title_size=27 if yticksize is None: yticksize=22 if xticksize is None: xticksize=22 # Set clean style sns.set(style='ticks') axisTitleParams={'labelsize' : axis_title_size} xtickParams={'labelsize' : xticksize} ytickParams={'labelsize' : yticksize} svgParams={'fonttype' : 'none'} rc('axes', **axisTitleParams) rc('xtick', **xtickParams) rc('ytick', **ytickParams) rc('svg', **svgParams) if figsize is None: if len(tuple_in)>2: figsize=(12,(12/np.sqrt(2))) else: figsize=(8,(8/np.sqrt(2))) # calculate CI. if ci<0 or ci>100: raise ValueError('ci should be between 0 and 100.') alpha_level=(100.-ci)/100. # Initialise figure, taking into account desired figsize. fig=plt.figure(figsize=figsize) # Initialise GridSpec based on `tuple_in` shape. gsMain=gridspec.GridSpec( 1, np.shape(tuple_in)[0], # 1 row; columns based on number of tuples in tuple. width_ratios=widthratio, wspace=0 ) for gsIdx, current_tuple in enumerate(tuple_in): #### FOR EACH TUPLE IN IDX if datatype=='long': plotdat=data[data[x].isin(current_tuple)] plotdat[x]=plotdat[x].astype("category") plotdat[x].cat.set_categories( current_tuple, ordered=True, inplace=True) plotdat.sort_values(by=[x]) # # Drop all nans. # plotdat.dropna(inplace=True) summaries=plotdat.groupby(x)[y].apply(statfunction) if datatype=='wide': plotdat=data[list(current_tuple)] summaries=statfunction(plotdat) plotdat=pd.melt(plotdat) ##### NOW I HAVE MELTED THE WIDE DATA. if floatContrast is True: # Use fig.add_subplot instead of plt.Subplot. ax_raw=fig.add_subplot(gsMain[gsIdx], frame_on=False) ax_contrast=ax_raw.twinx() else: # Create subGridSpec with 2 rows and 1 column. subGridSpec=gridspec.GridSpecFromSubplotSpec(2, 1, subplot_spec=gsMain[gsIdx], wspace=0) # Use plt.Subplot instead of fig.add_subplot ax_raw=plt.Subplot(fig, subGridSpec[0, 0], frame_on=False) ax_contrast=plt.Subplot(fig, subGridSpec[1, 0], sharex=ax_raw, frame_on=False) # Calculate the boostrapped contrast bscontrast=list() if paired is False: tempplotdat=plotdat[[x,y]] # only select the columns used for x and y plotting. for i in range (1, len(current_tuple)): # Note that you start from one. No need to do auto-contrast! # if datatype=='long':aas tempbs=bootstrap_contrast( data=tempplotdat.dropna(), x=x, y=y, idx=[current_tuple[0], current_tuple[i]], statfunction=statfunction, smoothboot=smoothboot, alpha_level=alpha_level, reps=reps) bscontrast.append(tempbs) contrastList.append(tempbs) contrastListNames.append(current_tuple[i]+' vs. '+current_tuple[0]) #### PLOT RAW DATA. ax_raw.set_ylim(swarm_ylim) # ax_raw.yaxis.set_major_locator(MaxNLocator(n_bins='auto')) # ax_raw.yaxis.set_major_locator(LinearLocator()) if paired is False and showRawData is True: # Seaborn swarmplot doc says to set custom ylims first. sw=sns.swarmplot( data=plotdat, x=x, y=y, order=current_tuple, ax=ax_raw, alpha=alpha, palette=plotPal, size=rawMarkerSize, marker=rawMarkerType, **kwargs) if floatContrast: # Get horizontal offset values. maxXBefore=max(sw.collections[0].get_offsets().T[0]) minXAfter=min(sw.collections[1].get_offsets().T[0]) xposAfter=maxXBefore+floatSwarmSpacer xAfterShift=minXAfter-xposAfter # shift the (second) swarmplot offsetSwarmX(sw.collections[1], -xAfterShift) # shift the tick. ax_raw.set_xticks([0.,1-xAfterShift]) elif paired is True: if showRawData is True: sw=sns.swarmplot(data=plotdat, x=x, y=y, order=current_tuple, ax=ax_raw, alpha=alpha, palette=plotPal, size=rawMarkerSize, marker=rawMarkerType, **kwargs) if connectPairs is True: # Produce paired plot with lines. before=plotdat[plotdat[x]==current_tuple[0]][y].tolist() after=plotdat[plotdat[x]==current_tuple[1]][y].tolist() linedf=pd.DataFrame( {'before':before, 'after':after} ) # to get color, need to loop thru each line and plot individually. for ii in range(0,len(linedf)): ax_raw.plot( [0,0.25], [ linedf.loc[ii,'before'], linedf.loc[ii,'after'] ], linestyle='solid', linewidth=pairedDeltaLineWidth, color=plotPal[current_tuple[0]], alpha=pairedDeltaLineAlpha, ) ax_raw.set_xlim(-0.25,0.5) ax_raw.set_xticks([0,0.25]) ax_raw.set_xticklabels([current_tuple[0],current_tuple[1]]) # if swarmYlim is None: # # if swarmYlim was not specified, tweak the y-axis # # to show all the data without losing ticks and range. # ## Get all yticks. # axxYTicks=ax_raw.yaxis.get_majorticklocs() # ## Get ytick interval. # YTickInterval=axxYTicks[1]-axxYTicks[0] # ## Get current ylim # currentYlim=ax_raw.get_ylim() # ## Extend ylim by adding a fifth of the tick interval as spacing at both ends. # ax_raw.set_ylim( # currentYlim[0]-(YTickInterval/5), # currentYlim[1]+(YTickInterval/5) # ) # ax_raw.yaxis.set_major_locator(MaxNLocator(nbins='auto')) # ax_raw.yaxis.set_major_locator(MaxNLocator(nbins='auto')) # ax_raw.yaxis.set_major_locator(LinearLocator()) if summaryBar is True: if paired is False: bar_raw=sns.barplot( x=summaries.index.tolist(), y=summaries.values, facecolor=summaryBarColor, ax=ax_raw, alpha=summaryBarAlpha) if floatContrast is True: maxSwarmSpan=2/10. xlocs=list() for i, bar in enumerate(bar_raw.patches): x_width=bar.get_x() width=bar.get_width() centre=x_width + (width/2.) if i == 0: bar.set_x(centre-maxSwarmSpan/2.) xlocs.append(centre) else: bar.set_x(centre-xAfterShift-maxSwarmSpan/2.) xlocs.append(centre-xAfterShift) bar.set_width(maxSwarmSpan) ax_raw.set_xticks(xlocs) # make sure xticklocs match the barplot. elif floatContrast is False: maxSwarmSpan=4/10. xpos=ax_raw.xaxis.get_majorticklocs() for i, bar in enumerate(bar_raw.patches): bar.set_x(xpos[i]-maxSwarmSpan/2.) bar.set_width(maxSwarmSpan) else: # if paired is true ax_raw.bar([0,0.25], [ statfunction(plotdat[current_tuple[0]]), statfunction(plotdat[current_tuple[1]]) ], color=summaryBarColor, alpha=0.5, width=0.05) ## Draw zero reference line. ax_raw.add_artist(Line2D( (ax_raw.xaxis.get_view_interval()[0], ax_raw.xaxis.get_view_interval()[1]), (0,0), color='k', linewidth=1.25) ) if summaryLine is True: if paired is True: xdelta=0 else: xdelta=summaryLineWidth for i, m in enumerate(summaries): ax_raw.plot( (i-xdelta, i+xdelta), # x-coordinates (m, m), color=summaryColour, linestyle=summaryLineStyle) if showCI is True: sns.barplot( data=plotdat, x=x, y=y, ax=ax_raw, alpha=0, ci=95) ax_raw.set_xlabel("") if floatContrast is False: fig.add_subplot(ax_raw) #### PLOT CONTRAST DATA. if len(current_tuple)==2: if paired is False: # Plot the CIs on the contrast axes. plotbootstrap(sw.collections[1], bslist=tempbs, ax=ax_contrast, violinWidth=violinWidth, violinOffset=violinOffset, markersize=summaryMarkerSize, marker=summaryMarkerType, offset=floatContrast, color=violinColor, linewidth=1) else: bootsDelta = bootstrap( plotdat[current_tuple[1]]-plotdat[current_tuple[0]], statfunction=statfunction, smoothboot=smoothboot, alpha_level=alpha_level, reps=reps) contrastList.append(bootsDelta) contrastListNames.append(current_tuple[1]+' vs. '+current_tuple[0]) summDelta = bootsDelta['summary'] lowDelta = bootsDelta['bca_ci_low'] highDelta = bootsDelta['bca_ci_high'] if floatContrast: xpos=0.375 else: xpos=0.25 # Plot the summary measure. ax_contrast.plot(xpos, bootsDelta['summary'], marker=summaryMarkerType, markerfacecolor='k', markersize=summaryMarkerSize, alpha=0.75 ) # Plot the CI. ax_contrast.plot([xpos, xpos], [lowDelta, highDelta], color='k', alpha=0.75, # linewidth=1, linestyle='solid' ) # Plot the violin-plot. v = ax_contrast.violinplot(bootsDelta['stat_array'], [xpos], widths = violinWidth, showextrema = False, showmeans = False) halfviolin(v, half = 'right', color = 'k') if floatContrast: # Set reference lines if paired is False: ## First get leftmost limit of left reference group xtemp, _=np.array(sw.collections[0].get_offsets()).T leftxlim=xtemp.min() ## Then get leftmost limit of right test group xtemp, _=np.array(sw.collections[1].get_offsets()).T rightxlim=xtemp.min() ref=tempbs['summary'] else: leftxlim=0 rightxlim=0.25 ref=bootsDelta['summary'] ax_contrast.set_xlim(-0.25, 0.5) # does this work? ## zero line ax_contrast.hlines(0, # y-coordinates leftxlim, 3.5, # x-coordinates, start and end. linestyle=contrastZeroLineStyle, linewidth=1, color=contrastZeroLineColor) ## effect size line ax_contrast.hlines(ref, rightxlim, 3.5, # x-coordinates, start and end. linestyle=contrastEffectSizeLineStyle, linewidth=1, color=contrastEffectSizeLineColor) if paired is False: es=float(tempbs['summary']) refSum=tempbs['statistic_ref'] else: es=float(bootsDelta['summary']) refSum=statfunction(plotdat[current_tuple[0]]) ## If the effect size is positive, shift the right axis up. if es>0: rightmin=ax_raw.get_ylim()[0]-es rightmax=ax_raw.get_ylim()[1]-es ## If the effect size is negative, shift the right axis down. elif es<0: rightmin=ax_raw.get_ylim()[0]+es rightmax=ax_raw.get_ylim()[1]+es ax_contrast.set_ylim(rightmin, rightmax) if gsIdx>0: ax_contrast.set_ylabel('') align_yaxis(ax_raw, refSum, ax_contrast, 0.) else: # Set bottom axes ybounds if contrastYlim is not None: ax_contrast.set_ylim(contrastYlim) if paired is False: # Set xlims so everything is properly visible! swarm_xbounds=ax_raw.get_xbound() ax_contrast.set_xbound(swarm_xbounds[0] -(summaryLineWidth * 1.1), swarm_xbounds[1] + (summaryLineWidth * 1.1)) else: ax_contrast.set_xlim(-0.05,0.25+violinWidth) else: # Plot the CIs on the bottom axes. plotbootstrap_hubspoke( bslist=bscontrast, ax=ax_contrast, violinWidth=violinWidth, violinOffset=violinOffset, markersize=summaryMarkerSize, marker=summaryMarkerType, linewidth=lineWidth) if floatContrast is False: fig.add_subplot(ax_contrast) if gsIdx>0: ax_raw.set_ylabel('') ax_contrast.set_ylabel('') # Turn contrastList into a pandas DataFrame, contrastList=pd.DataFrame(contrastList).T contrastList.columns=contrastListNames # Get number of axes in figure for aesthetic tweaks. axesCount=len(fig.get_axes()) for i in range(0, axesCount, 2): # Set new tick labels. # The tick labels belong to the SWARM axes # for both floating and non-floating plots. # This is because `sharex` was invoked. axx=fig.axes[i] newticklabs=list() for xticklab in axx.xaxis.get_ticklabels(): t=xticklab.get_text() if paired: N=str(counts) else: N=str(counts.ix[t]) if showGroupCount: newticklabs.append(t+' n='+N) else: newticklabs.append(t) axx.set_xticklabels( newticklabs, rotation=tickAngle, horizontalalignment=tickAlignment) ## Loop thru SWARM axes for aesthetic touchups. for i in range(0, axesCount, 2): axx=fig.axes[i] if floatContrast is False: axx.xaxis.set_visible(False) sns.despine(ax=axx, trim=True, bottom=False, left=False) else: sns.despine(ax=axx, trim=True, bottom=True, left=True) if i==0: drawback_y(axx) if i!=axesCount-2 and 'hue' in kwargs: # If this is not the final swarmplot, remove the hue legend. axx.legend().set_visible(False) if showAllYAxes is False: if i in range(2, axesCount): axx.yaxis.set_visible(False) else: # Draw back the lines for the relevant y-axes. # Not entirely sure why I have to do this. drawback_y(axx) else: drawback_y(axx) # Add zero reference line for swarmplots with bars. if summaryBar is True: axx.add_artist(Line2D( (axx.xaxis.get_view_interval()[0], axx.xaxis.get_view_interval()[1]), (0,0), color='black', linewidth=0.75 ) ) if legend is False: axx.legend().set_visible(False) else: if i==axesCount-2: # the last (rightmost) swarm axes. axx.legend(loc='top right', bbox_to_anchor=(1.1,1.0), fontsize=legendFontSize, **legendFontProps) ## Loop thru the CONTRAST axes and perform aesthetic touch-ups. ## Get the y-limits: for j,i in enumerate(range(1, axesCount, 2)): axx=fig.get_axes()[i] if floatContrast is False: xleft, xright=axx.xaxis.get_view_interval() # Draw zero reference line. axx.hlines(y=0, xmin=xleft-1, xmax=xright+1, linestyle=contrastZeroLineStyle, linewidth=0.75, color=contrastZeroLineColor) # reset view interval. axx.set_xlim(xleft, xright) if showAllYAxes is False: if i in range(2, axesCount): axx.yaxis.set_visible(False) else: # Draw back the lines for the relevant y-axes, only is axesCount is 2. # Not entirely sure why I have to do this. if axesCount==2: drawback_y(axx) sns.despine(ax=axx, top=True, right=True, left=False, bottom=False, trim=True) if j==0 and axesCount==2: # Draw back x-axis lines connecting ticks. drawback_x(axx) # Rotate tick labels. rotateTicks(axx,tickAngle,tickAlignment) elif floatContrast is True: if paired is True: # Get the bootstrapped contrast range. lower=np.min(contrastList.ix['stat_array',j]) upper=np.max(contrastList.ix['stat_array',j]) else: lower=np.min(contrastList.ix['diffarray',j]) upper=np.max(contrastList.ix['diffarray',j]) meandiff=contrastList.ix['summary', j] ## Make sure we have zero in the limits. if lower>0: lower=0. if upper<0: upper=0. ## Get the tick interval from the left y-axis. leftticks=fig.get_axes()[i-1].get_yticks() tickstep=leftticks[1] -leftticks[0] ## First re-draw of axis with new tick interval axx.yaxis.set_major_locator(MultipleLocator(base=tickstep)) newticks1=axx.get_yticks() ## Obtain major ticks that comfortably encompass lower and upper. newticks2=list() for a,b in enumerate(newticks1): if (b >= lower and b <= upper): # if the tick lies within upper and lower, take it. newticks2.append(b) # if the meandiff falls outside of the newticks2 set, add a tick in the right direction. if np.max(newticks2)<meandiff: ind=np.where(newticks1 == np.max(newticks2))[0][0] # find out the max tick index in newticks1. newticks2.append( newticks1[ind+1] ) elif meandiff<np.min(newticks2): ind=np.where(newticks1 == np.min(newticks2))[0][0] # find out the min tick index in newticks1. newticks2.append( newticks1[ind-1] ) newticks2=np.array(newticks2) newticks2.sort() ## Second re-draw of axis to shrink it to desired limits. axx.yaxis.set_major_locator(FixedLocator(locs=newticks2)) ## Despine the axes. sns.despine(ax=axx, trim=True, bottom=False, right=False, left=True, top=True) # Normalize bottom/right Contrast axes to each other for Cummings hub-and-spoke plots. if (axesCount>2 and contrastShareY is True and floatContrast is False): # Set contrast ylim as max ticks of leftmost swarm axes. if contrastYlim is None: lower=list() upper=list() for c in range(0,len(contrastList.columns)): lower.append( np.min(contrastList.ix['bca_ci_low',c]) ) upper.append( np.max(contrastList.ix['bca_ci_high',c]) ) lower=np.min(lower) upper=np.max(upper) else: lower=contrastYlim[0] upper=contrastYlim[1] normalizeContrastY(fig, contrast_ylim = contrastYlim, show_all_yaxes = showAllYAxes) # Zero gaps between plots on the same row, if floatContrast is False if (floatContrast is False and showAllYAxes is False): gsMain.update(wspace=0.) else: # Tight Layout! gsMain.tight_layout(fig) # And we're all done. rcdefaults() # restore matplotlib defaults. sns.set() # restore seaborn defaults. return fig, contrastList
import matplotlib.pyplot as plt from matplotlib.ticker import FormatStrFormatter from mpl_toolkits.mplot3d import Axes3D import seaborn.apionly as sns import xml.etree.ElementTree as ET from pymht.utils.xmlDefinitions import * import os import numpy as np import csv import ast from pysimulator import simulationConfig from pysimulator.scenarios.scenarios import scenarioList colors = sns.color_palette(n_colors=5) linestyleList = ['-','--','-.', ':'] legendFontsize = 7 labelFontsize = 8 titleFontsize = 10 figureWidth = 13.0*0.4 #inch fullPageHeight = 18.0*0.4 #inch halfPageHeight = 8.0 * 0.4 #inch linewidth = 1 def exportInitialState(): filePath = os.path.join(simulationConfig.path, 'plots', "Scenario_Initial_State.csv") with open(filePath, 'w') as csvfile: writer = csv.writer(csvfile) writer.writerow(["T", "NP", "EP", "NS", "ES"]) scenario = scenarioList[0] for i, target in enumerate(scenario.initialTargets): s = target.state
dim = 'y' xDim = 26 zDim = 26 current_convert = 1.6 * 10**(-19) * 10**(9) * 10**(9) pdf = 'DNA_D.pdf' png = 'DNA_D.png' pdf_1 = 'DNA_D_1.pdf' png_1 = 'DNA_D_1.png' ionListMap = np.array([[0, 'POT', 1], [1, 'MG', 2], [2, 'CLA', -1]]) current_palette = sns.color_palette("bright") #################### ## Load Currents ## #################### inFileName = 'POTFlux.dat' infile = open(inFileName, 'r') #theLines = infile.readlines() for i, line in enumerate(infile): if i == 2: gridDim = removeBlanksFromList(re.split('\s',line[15:len(line)])) #print gridDim if i == 3:
import pandas as pd import pymc3 as pm import scipy import scipy.stats as stats import seaborn.apionly as sb import statsmodels.api as sm import theano.tensor as tt from sklearn import preprocessing from numpy import exp, e, log from math import factorial from matplotlib.offsetbox import AnnotationBbox, TextArea from collections import Counter colors = sb.color_palette("muted") BASEDIR = os.path.join(os.path.expanduser("~"), "Data", "IPO", "NASDAQ",) FINALJSON = json.loads(open(BASEDIR + '/final_json.txt').read()) df = pd.read_csv(BASEDIR + "/df.csv", dtype={'cik':object, 'Year':object, 'SIC':object}) df.set_index("cik", inplace=True) df.drop(['1087294', '1368308'], inplace=1) # 1st update took longer than a year df = df[df.days_to_first_price_change > 0] df = df[df.days_to_first_price_change < 300] dfa = df[df.amends != "None"] ciks = list(df.index) # df['days_to_first_price_update'] = [-999 if np.isnan(x) else x for x in df.days_to_first_price_update] df['days_to_first_price_update'] = [0 if np.isnan(x) else x for x in df.days_to_first_price_update] CASI = 'IoT_15day_CASI_weighted_finance'
def pairedcontrast(data, x, y, idcol, reps=3000, statfunction=None, idx=None, figsize=None, beforeAfterSpacer=0.01, violinWidth=0.005, floatOffset=0.05, showRawData=False, showAllYAxes=False, floatContrast=True, smoothboot=False, floatViolinOffset=None, showConnections=True, summaryBar=False, contrastYlim=None, swarmYlim=None, barWidth=0.005, rawMarkerSize=8, rawMarkerType='o', summaryMarkerSize=10, summaryMarkerType='o', summaryBarColor='grey', meansSummaryLineStyle='solid', contrastZeroLineStyle='solid', contrastEffectSizeLineStyle='solid', contrastZeroLineColor='black', contrastEffectSizeLineColor='black', pal=None, legendLoc=2, legendFontSize=12, legendMarkerScale=1, axis_title_size=None, yticksize=None, xticksize=None, tickAngle=45, tickAlignment='right', **kwargs): # Preliminaries. data = data.dropna() # plot params if axis_title_size is None: axis_title_size = 15 if yticksize is None: yticksize = 12 if xticksize is None: xticksize = 12 axisTitleParams = {'labelsize': axis_title_size} xtickParams = {'labelsize': xticksize} ytickParams = {'labelsize': yticksize} rc('axes', **axisTitleParams) rc('xtick', **xtickParams) rc('ytick', **ytickParams) ## If `idx` is not specified, just take the FIRST TWO levels alphabetically. if idx is None: idx = tuple(np.unique(data[x])[0:2], ) else: # check if multi-plot or not if all(isinstance(element, str) for element in idx): # if idx is supplied but not a multiplot (ie single list or tuple) if len(idx) != 2: print(idx, "does not have length 2.") sys.exit(0) else: idx = (tuple(idx, ), ) elif all(isinstance(element, tuple) for element in idx): # if idx is supplied, and it is a list/tuple of tuples or lists, we have a multiplot! if (any(len(element) != 2 for element in idx)): # If any of the tuples contain more than 2 elements. print(element, "does not have length 2.") sys.exit(0) if floatViolinOffset is None: floatViolinOffset = beforeAfterSpacer / 2 if contrastYlim is not None: contrastYlim = np.array([contrastYlim[0], contrastYlim[1]]) if swarmYlim is not None: swarmYlim = np.array([swarmYlim[0], swarmYlim[1]]) ## Here we define the palette on all the levels of the 'x' column. ## Thus, if the same pandas dataframe is re-used across different plots, ## the color identity of each group will be maintained. ## Set palette based on total number of categories in data['x'] or data['hue_column'] if 'hue' in kwargs: u = kwargs['hue'] else: u = x if ('color' not in kwargs and 'hue' not in kwargs): kwargs['color'] = 'k' if pal is None: pal = dict( zip(data[u].unique(), sns.color_palette(n_colors=len(data[u].unique())))) else: pal = pal # Initialise figure. if figsize is None: if len(idx) > 2: figsize = (12, (12 / np.sqrt(2))) else: figsize = (6, 6) fig = plt.figure(figsize=figsize) # Initialise GridSpec based on `levs_tuple` shape. gsMain = gridspec.GridSpec( 1, np.shape(idx)[0]) # 1 row; columns based on number of tuples in tuple. # Set default statfunction if statfunction is None: statfunction = np.mean # Create list to collect all the contrast DataFrames generated. contrastList = list() contrastListNames = list() for gsIdx, xlevs in enumerate(idx): ## Pivot tempdat to get before and after lines. data_pivot = data.pivot_table(index=idcol, columns=x, values=y) # Start plotting!! if floatContrast is True: ax_raw = fig.add_subplot(gsMain[gsIdx], frame_on=False) ax_contrast = ax_raw.twinx() else: gsSubGridSpec = gridspec.GridSpecFromSubplotSpec( 2, 1, subplot_spec=gsMain[gsIdx]) ax_raw = plt.Subplot(fig, gsSubGridSpec[0, 0], frame_on=False) ax_contrast = plt.Subplot(fig, gsSubGridSpec[1, 0], sharex=ax_raw, frame_on=False) ## Plot raw data as swarmplot or stripplot. if showRawData is True: swarm_raw = sns.swarmplot(data=data, x=x, y=y, order=xlevs, ax=ax_raw, palette=pal, size=rawMarkerSize, marker=rawMarkerType, **kwargs) else: swarm_raw = sns.stripplot(data=data, x=x, y=y, order=xlevs, ax=ax_raw, palette=pal, **kwargs) swarm_raw.set_ylim(swarmYlim) ## Get some details about the raw data. maxXBefore = max(swarm_raw.collections[0].get_offsets().T[0]) minXAfter = min(swarm_raw.collections[1].get_offsets().T[0]) if showRawData is True: #beforeAfterSpacer = (getSwarmSpan(swarm_raw, 0) + getSwarmSpan(swarm_raw, 1))/2 beforeAfterSpacer = 1 xposAfter = maxXBefore + beforeAfterSpacer xAfterShift = minXAfter - xposAfter ## shift the after swarmpoints closer for aesthetic purposes. offsetSwarmX(swarm_raw.collections[1], -xAfterShift) ## pandas DataFrame of 'before' group x1 = pd.DataFrame({ str(xlevs[0] + '_x'): pd.Series(swarm_raw.collections[0].get_offsets().T[0]), xlevs[0]: pd.Series(swarm_raw.collections[0].get_offsets().T[1]), '_R_': pd.Series(swarm_raw.collections[0].get_facecolors().T[0]), '_G_': pd.Series(swarm_raw.collections[0].get_facecolors().T[1]), '_B_': pd.Series(swarm_raw.collections[0].get_facecolors().T[2]), }) ## join the RGB columns into a tuple, then assign to a column. x1['_hue_'] = x1[['_R_', '_G_', '_B_']].apply(tuple, axis=1) x1 = x1.sort_values(by=xlevs[0]) x1.index = data_pivot.sort_values(by=xlevs[0]).index ## pandas DataFrame of 'after' group ### create convenient signifiers for column names. befX = str(xlevs[0] + '_x') aftX = str(xlevs[1] + '_x') x2 = pd.DataFrame({ aftX: pd.Series(swarm_raw.collections[1].get_offsets().T[0]), xlevs[1]: pd.Series(swarm_raw.collections[1].get_offsets().T[1]) }) x2 = x2.sort_values(by=xlevs[1]) x2.index = data_pivot.sort_values(by=xlevs[1]).index ## Join x1 and x2, on both their indexes. plotPoints = x1.merge(x2, left_index=True, right_index=True, how='outer') ## Add the hue column if hue argument was passed. if 'hue' in kwargs: h = kwargs['hue'] plotPoints[h] = data.pivot(index=idcol, columns=x, values=h)[xlevs[0]] swarm_raw.legend(loc=legendLoc, fontsize=legendFontSize, markerscale=legendMarkerScale) ## Plot the lines to join the 'before' points to their respective 'after' points. if showConnections is True: for i in plotPoints.index: ax_raw.plot( [plotPoints.ix[i, befX], plotPoints.ix[i, aftX]], [plotPoints.ix[i, xlevs[0]], plotPoints.ix[i, xlevs[1]]], linestyle='solid', color=plotPoints.ix[i, '_hue_'], linewidth=0.75, alpha=0.75) ## Hide the raw swarmplot data if so desired. if showRawData is False: swarm_raw.collections[0].set_visible(False) swarm_raw.collections[1].set_visible(False) if showRawData is True: #maxSwarmSpan = max(np.array([getSwarmSpan(swarm_raw, 0), getSwarmSpan(swarm_raw, 1)]))/2 maxSwarmSpan = 0.5 else: maxSwarmSpan = barWidth ## Plot Summary Bar. if summaryBar is True: # Calculate means means = data.groupby([x], sort=True).mean()[y] # # Calculate medians # medians = data.groupby([x], sort = True).median()[y] ## Draw summary bar. bar_raw = sns.barplot(x=means.index, y=means.values, order=xlevs, ax=ax_raw, ci=0, facecolor=summaryBarColor, alpha=0.25) ## Draw zero reference line. ax_raw.add_artist( Line2D((ax_raw.xaxis.get_view_interval()[0], ax_raw.xaxis.get_view_interval()[1]), (0, 0), color='black', linewidth=0.75)) ## get swarm with largest span, set as max width of each barplot. for i, bar in enumerate(bar_raw.patches): x_width = bar.get_x() width = bar.get_width() centre = x_width + width / 2. if i == 0: bar.set_x(centre - maxSwarmSpan / 2.) else: bar.set_x(centre - xAfterShift - maxSwarmSpan / 2.) bar.set_width(maxSwarmSpan) # Get y-limits of the treatment swarm points. beforeRaw = pd.DataFrame(swarm_raw.collections[0].get_offsets()) afterRaw = pd.DataFrame(swarm_raw.collections[1].get_offsets()) before_leftx = min(beforeRaw[0]) after_leftx = min(afterRaw[0]) after_rightx = max(afterRaw[0]) after_stat_summary = statfunction(beforeRaw[1]) # Calculate the summary difference and CI. plotPoints['delta_y'] = plotPoints[xlevs[1]] - plotPoints[xlevs[0]] plotPoints['delta_x'] = [0] * np.shape(plotPoints)[0] tempseries = plotPoints['delta_y'].tolist() test = tempseries.count(tempseries[0]) != len(tempseries) bootsDelta = bootstrap(plotPoints['delta_y'], statfunction=statfunction, smoothboot=smoothboot, reps=reps) summDelta = bootsDelta['summary'] lowDelta = bootsDelta['bca_ci_low'] highDelta = bootsDelta['bca_ci_high'] # set new xpos for delta violin. if floatContrast is True: if showRawData is False: xposPlusViolin = deltaSwarmX = after_rightx + floatViolinOffset else: xposPlusViolin = deltaSwarmX = after_rightx + maxSwarmSpan else: xposPlusViolin = xposAfter if showRawData is True: # If showRawData is True and floatContrast is True, # set violinwidth to the barwidth. violinWidth = maxSwarmSpan xmaxPlot = xposPlusViolin + violinWidth # Plot the summary measure. ax_contrast.plot(xposPlusViolin, summDelta, marker='o', markerfacecolor='k', markersize=summaryMarkerSize, alpha=0.75) # Plot the CI. ax_contrast.plot([xposPlusViolin, xposPlusViolin], [lowDelta, highDelta], color='k', alpha=0.75, linestyle='solid') # Plot the violin-plot. v = ax_contrast.violinplot(bootsDelta['stat_array'], [xposPlusViolin], widths=violinWidth, showextrema=False, showmeans=False) halfviolin(v, half='right', color='k') # Remove left axes x-axis title. ax_raw.set_xlabel("") # Remove floating axes y-axis title. ax_contrast.set_ylabel("") # Set proper x-limits ax_raw.set_xlim(before_leftx - beforeAfterSpacer / 2, xmaxPlot) ax_raw.get_xaxis().set_view_interval( before_leftx - beforeAfterSpacer / 2, after_rightx + beforeAfterSpacer / 2) ax_contrast.set_xlim(ax_raw.get_xlim()) if floatContrast is True: # Set the ticks locations for ax_raw. ax_raw.get_xaxis().set_ticks((0, xposAfter)) # Make sure they have the same y-limits. ax_contrast.set_ylim(ax_raw.get_ylim()) # Drawing in the x-axis for ax_raw. ## Set the tick labels! ax_raw.set_xticklabels(xlevs, rotation=tickAngle, horizontalalignment=tickAlignment) ## Get lowest y-value for ax_raw. y = ax_raw.get_yaxis().get_view_interval()[0] # Align the left axes and the floating axes. align_yaxis(ax_raw, statfunction(plotPoints[xlevs[0]]), ax_contrast, 0) # Add label to floating axes. But on ax_raw! ax_raw.text(x=deltaSwarmX, y=ax_raw.get_yaxis().get_view_interval()[0], horizontalalignment='left', s='Difference', fontsize=15) # Set reference lines ## zero line ax_contrast.hlines( 0, # y-coordinate ax_contrast.xaxis.get_majorticklocs() [0], # x-coordinates, start and end. ax_raw.xaxis.get_view_interval()[1], linestyle='solid', linewidth=0.75, color='black') ## effect size line ax_contrast.hlines(summDelta, ax_contrast.xaxis.get_majorticklocs()[1], ax_raw.xaxis.get_view_interval()[1], linestyle='solid', linewidth=0.75, color='black') # Align the left axes and the floating axes. align_yaxis(ax_raw, after_stat_summary, ax_contrast, 0.) else: # Set the ticks locations for ax_raw. ax_raw.get_xaxis().set_ticks((0, xposAfter)) fig.add_subplot(ax_raw) fig.add_subplot(ax_contrast) ax_contrast.set_ylim(contrastYlim) # Calculate p-values. # 1-sample t-test to see if the mean of the difference is different from 0. ttestresult = ttest_1samp(plotPoints['delta_y'], popmean=0)[1] bootsDelta['ttest_pval'] = ttestresult contrastList.append(bootsDelta) contrastListNames.append(str(xlevs[1]) + ' v.s. ' + str(xlevs[0])) # Turn contrastList into a pandas DataFrame, contrastList = pd.DataFrame(contrastList).T contrastList.columns = contrastListNames # Now we iterate thru the contrast axes to normalize all the ylims. for j, i in enumerate(range(1, len(fig.get_axes()), 2)): axx = fig.get_axes()[i] ## Get max and min of the dataset. lower = np.min(contrastList.ix['stat_array', j]) upper = np.max(contrastList.ix['stat_array', j]) meandiff = contrastList.ix['summary', j] ## Make sure we have zero in the limits. if lower > 0: lower = 0. if upper < 0: upper = 0. ## Get tick distance on raw axes. ## This will be the tick distance for the contrast axes. rawAxesTicks = fig.get_axes()[i - 1].yaxis.get_majorticklocs() rawAxesTickDist = rawAxesTicks[1] - rawAxesTicks[0] ## First re-draw of axis with new tick interval axx.yaxis.set_major_locator(MultipleLocator(rawAxesTickDist)) newticks1 = fig.get_axes()[i].get_yticks() if floatContrast is False: if (showAllYAxes is False and i in range(2, len(fig.get_axes()))): axx.get_yaxis().set_visible(showAllYAxes) else: ## Obtain major ticks that comfortably encompass lower and upper. newticks2 = list() for a, b in enumerate(newticks1): if (b >= lower and b <= upper): # if the tick lies within upper and lower, take it. newticks2.append(b) # if the meandiff falls outside of the newticks2 set, add a tick in the right direction. if np.max(newticks2) < meandiff: ind = np.where(newticks1 == np.max(newticks2))[0][ 0] # find out the max tick index in newticks1. newticks2.append(newticks1[ind + 1]) elif meandiff < np.min(newticks2): ind = np.where(newticks1 == np.min(newticks2))[0][ 0] # find out the min tick index in newticks1. newticks2.append(newticks1[ind - 1]) newticks2 = np.array(newticks2) newticks2.sort() axx.yaxis.set_major_locator(FixedLocator(locs=newticks2)) ## Draw zero reference line. axx.hlines( y=0, xmin=fig.get_axes()[i].get_xaxis().get_view_interval()[0], xmax=fig.get_axes()[i].get_xaxis().get_view_interval()[1], linestyle=contrastZeroLineStyle, linewidth=0.75, color=contrastZeroLineColor) sns.despine(ax=fig.get_axes()[i], trim=True, bottom=False, right=True, left=False, top=True) ## Draw back the lines for the relevant y-axes. drawback_y(axx) ## Draw back the lines for the relevant x-axes. drawback_x(axx) elif floatContrast is True: ## Get the original ticks on the floating y-axis. newticks1 = fig.get_axes()[i].get_yticks() ## Obtain major ticks that comfortably encompass lower and upper. newticks2 = list() for a, b in enumerate(newticks1): if (b >= lower and b <= upper): # if the tick lies within upper and lower, take it. newticks2.append(b) # if the meandiff falls outside of the newticks2 set, add a tick in the right direction. if np.max(newticks2) < meandiff: ind = np.where(newticks1 == np.max(newticks2))[0][ 0] # find out the max tick index in newticks1. newticks2.append(newticks1[ind + 1]) elif meandiff < np.min(newticks2): ind = np.where(newticks1 == np.min(newticks2))[0][ 0] # find out the min tick index in newticks1. newticks2.append(newticks1[ind - 1]) newticks2 = np.array(newticks2) newticks2.sort() ## Re-draw the axis. axx.yaxis.set_major_locator(FixedLocator(locs=newticks2)) ## Despine and trim the axes. sns.despine(ax=axx, trim=True, bottom=False, right=False, left=True, top=True) for i in range(0, len(fig.get_axes()), 2): # Loop through the raw data swarmplots and despine them appropriately. if floatContrast is True: sns.despine(ax=fig.get_axes()[i], trim=True, right=True) else: sns.despine(ax=fig.get_axes()[i], trim=True, bottom=True, right=True) fig.get_axes()[i].get_xaxis().set_visible(False) # Draw back the lines for the relevant y-axes. ymin = fig.get_axes()[i].get_yaxis().get_majorticklocs()[0] ymax = fig.get_axes()[i].get_yaxis().get_majorticklocs()[-1] x, _ = fig.get_axes()[i].get_xaxis().get_view_interval() fig.get_axes()[i].add_artist( Line2D((x, x), (ymin, ymax), color='black', linewidth=1.5)) # Zero gaps between plots on the same row, if floatContrast is False if (floatContrast is False and showAllYAxes is False): gsMain.update(wspace=0) else: # Tight Layout! gsMain.tight_layout(fig) # And we're done. rcdefaults() # restore matplotlib defaults. sns.set() # restore seaborn defaults. return fig, contrastList
dcd_file = sys.argv[3] dat_file = sys.argv[4] + '.dat' out_file = sys.argv[4] + '.png' u = mda.Universe(psf_file, dcd_file) ref = mda.Universe(psf_file, pdb_file) # default the 0th frame R = MDAnalysis.analysis.rms.RMSD(u, ref, select = "backbone", filename=dat_file) R.run() R.save() rmsd = R.rmsd.T time = rmsd[1] import seaborn.apionly as sns #matplotlib inline plt.style.use('ggplot') rcParams.update({'figure.autolayout': True}) sns.set_style('ticks') fig = plt.figure(figsize=(5,3)) ax = fig.add_subplot(111) color = sns.color_palette()[2] #ax.fill_between(ca.residues.resids, rmsf, alpha=0.3, color=color) ax.plot(time, rmsd[2], lw=1, color=color) sns.despine(ax=ax) ax.set_xlabel("Time (ps)") ax.set_ylabel(r"RMSD ($\AA$)") ax.set_xlim(0, max(time)) ax.set_ylim(0, 10) fig.savefig(out_file)
def plot_roi_per_session( df, x='Session', y='Mean t-Statistic', condition='treatment', unit='subject', ci=90, palette=["#56B4E9", "#E69F00"], dodge=True, order=[], feature_map=True, roi_left=0.02, roi_bottom=0.74, roi_width=0.3, roi_height=0.2, roi_anat="/usr/share/mouse-brain-atlases/dsurqec_40micron_masked.nii", roi_threshold=None, cut_coords=None, samri_style=True, renames=[], save_as='', ax=None, fig=None, ): """Plot a ROI t-values over the session timecourse """ if samri_style: plt.style.use(u'seaborn-darkgrid') plt.style.use('ggplot') try: df = path.abspath(path.expanduser(df)) except AttributeError: pass # definitions for the axes height = rcParams['figure.subplot.top'] bottom = rcParams['figure.subplot.bottom'] left = rcParams['figure.subplot.left'] width = rcParams['figure.subplot.right'] session_coordinates = [left, bottom, width, height] roi_coordinates = [ left + roi_left, bottom + roi_bottom, roi_width, roi_height ] if not fig: fig = plt.figure(1) if renames: for key in renames: for subkey in renames[key]: df.loc[df[key] == subkey, key] = renames[key][subkey] if not ax: ax1 = plt.axes(session_coordinates) else: ax1 = ax ax = sns.pointplot( x=x, y=y, units=unit, data=df, hue=condition, dodge=dodge, palette=sns.color_palette(palette), order=order, ax=ax1, ci=ci, ) ax.set_ylabel(y) if isinstance(feature_map, str): ax2 = plt.axes(roi_coordinates) if roi_threshold and cut_coords: maps.stat( feature, cut_coords=cut_coords, template=roi_anat, annotate=False, scale=0.3, show_plot=False, interpolation=None, threshold=roi_threshold, draw_colorbar=False, ax=ax2, ) else: maps.atlas_label( feature_map, scale=0.3, color="#E69F00", ax=ax2, annotate=False, alpha=0.8, ) elif feature_map: try: features = df['feature'].unique() except KeyError: pass else: if len(features) > 1: print( 'WARNING: The features list contains more than one feature. We will highlight the first one in the list. This may be incorrect.' ) feature = features[0] ax2 = plt.axes(roi_coordinates) if path.isfile(feature): if roi_threshold and cut_coords: maps.stat( stat_maps=feature, cut_coords=cut_coords, template=roi_anat, annotate=False, scale=0.3, show_plot=False, interpolation=None, threshold=roi_threshold, draw_colorbar=False, ax=ax2, ) else: maps.atlas_label( feature, scale=0.3, color="#E69F00", ax=ax2, annotate=False, alpha=0.8, ) else: atlas = df['atlas'].unique()[0] mapping = df['mapping'].unique()[0] if isinstance(feature, str): feature = [feature] maps.atlas_label( atlas, scale=0.3, color="#E69F00", ax=ax2, mapping=mapping, label_names=feature, alpha=0.8, annotate=False, ) if save_as: plt.savefig(path.abspath(path.expanduser(save_as)), bbox_inches='tight') return fig, ax
llcrnrlon=-180,llcrnrlat=-90, urcrnrlon=177.5,urcrnrlat=90., suppress_ticks=False) m.drawmapboundary() lat = Dataset(if_aod)['lat'][:] lon = Dataset(if_aod)['lon'][:] #rearrange matrix for plot lon = shift_lon(lon) arr_aod = shift_lon(arr_aod) x,y = np.meshgrid(lon,lat) x,y = m(x,y) my_cmap = ListedColormap(sns.color_palette('magma',17).as_hex()[::-1]) cs = m.pcolormesh(lon,lat,np.squeeze(arr_aod),cmap=my_cmap, vmin=0, vmax=0.17) # add colorbar. cbar = m.colorbar(cs,location='right',pad="5%",ticks=[0,0.02,0.04,0.06,0.08,0.1,0.12,0.14,0.16]) cbar.set_label(' ',fontsize = 14,rotation=270,labelpad=18) cbar.ax.set_yticklabels([0,0.02,0.04,0.06,0.08,0.1,0.12,0.14,0.16],size=14) m.readshapefile(_env.idir_root + '/shape/kx-world-coastline-110-million-SHP/world-coastline-110-million', 'coastline',drawbounds=True,linewidth=0.8,color='k', zorder=2) plt.title('Sulfate-induced aerosol optical depth (at 550 nm) changes',size=18) set_latlon_ticks(ax,m) plt.text(0.03,0.98, (chr(ord('a') + 0)),size=16, horizontalalignment='center',#fontweight = 'bold', verticalalignment='top',transform=ax.transAxes,fontweight='bold')
def plot_params(self, print_fig_filename=None, **kwargs): # set up figure fig, ax = plt.subplots(3, 1, figsize=(1.5 * self.figsize[0], self.figsize[1]), sharex=True) ax_n = ax[1].twinx() ax_na = ax[2].twinx() if self.two_fluid: tlab = r"$T_e$" else: tlab = r"$T$" # plot heating ax[0].plot(self.time, self.heat, color=sns.color_palette("deep")[0]) ax[0].set_ylabel(r"$h$ (erg cm$^{-3}$ s$^{-1}$)", fontsize=self.fontsize) ax[0].set_xlim([self.time[0], self.time[-1]]) ax[0].locator_params(nbins=5) ax[0].ticklabel_format(axis="y", style="sci", scilimits=(-2, 2)) ax[0].tick_params(axis="both", labelsize=self.alfs * self.fontsize, pad=8) # plot average temperature and density line_te = ax[1].plot(self.time, self.temp_e / 10 ** 6, label=tlab, color=sns.color_palette("deep")[0]) if self.two_fluid: line_ti = ax[1].plot(self.time, self.temp_i / 10 ** 6, color=sns.color_palette("deep")[2], label=r"$T_i$") ax[1].set_ylabel(r"$T$ (MK)", fontsize=self.fontsize) ax[1].yaxis.set_major_locator(MaxNLocator(prune="lower")) ax[1].locator_params(nbins=5) ax[1].ticklabel_format(axis="y", style="sci", scilimits=(-2, 2)) ax[1].tick_params(axis="both", labelsize=self.alfs * self.fontsize, pad=8) line_n = ax_n.plot( self.time, self.dens / 10 ** 8, color=sns.color_palette("deep")[0], linestyle="--", label=r"$n$" ) ax_n.set_ylabel(r"$n$ (10$^8$ cm$^{-3}$)", fontsize=self.fontsize) ax_n.yaxis.set_major_locator(MaxNLocator(prune="lower")) ax_n.locator_params(nbins=5) ax_n.ticklabel_format(axis="y", style="sci", scilimits=(-2, 2)) ax_n.tick_params(axis="both", labelsize=self.alfs * self.fontsize, pad=8) ax[1].set_xlim([self.time[0], self.time[-1]]) # plot apex temperature and density ax[2].plot(self.time, self.temp_apex_e / 10 ** 6, color=sns.color_palette("deep")[0]) if self.two_fluid: ax[2].plot(self.time, self.temp_apex_i / 10 ** 6, color=sns.color_palette("deep")[2]) ax[2].set_ylabel(r"$T_a$ (MK)", fontsize=self.fontsize) ax[2].yaxis.set_major_locator(MaxNLocator(prune="lower")) ax[2].locator_params(nbins=5) ax[2].ticklabel_format(axis="y", style="sci", scilimits=(-2, 2)) ax[2].tick_params(axis="both", labelsize=self.alfs * self.fontsize, pad=8) ax_na.plot(self.time, self.dens_apex / 10 ** 8, color=sns.color_palette("deep")[0], linestyle="--") ax_na.set_ylabel(r"$n_a$ (10$^8$ cm$^{-3}$)", fontsize=self.fontsize) ax_na.yaxis.set_major_locator(MaxNLocator(prune="lower")) ax_na.locator_params(nbins=5) ax_na.ticklabel_format(axis="y", style="sci", scilimits=(-2, 2)) ax_na.tick_params(axis="both", labelsize=self.alfs * self.fontsize, pad=8) ax[2].set_xlim([self.time[0], self.time[-1]]) ax[2].set_xlabel(r"$t$ (s)", fontsize=self.fontsize) # configure legend lines = line_te + line_n if self.two_fluid: lines = line_te + line_ti + line_n labels = [l.get_label() for l in lines] ax[1].legend(lines, labels, loc=1) # Check if output filename is specified if print_fig_filename is not None: plt.savefig(print_fig_filename + "." + self.fformat, format=self.fformat, dpi=self.dpi) else: plt.show()
#check dimensions _, c = np.shape(results) if c - 4 != args.spec_to - args.spec_from + 1: print("Mismatch between spectroscopic indices(%d) and results file(%d)." % (args.spec_to - args.spec_from + 1, c - 4)) print("Exiting...") sys.exit() num_ipf = c - 4 spec_labs = [] [ spec_labs.append(roman.toRoman(i)) for i in range(args.spec_from, args.spec_to + 1) ] spec_colors = [] cpal = sns.color_palette('husl', num_ipf) [spec_colors.append(cpal[i]) for i in range(num_ipf)] #aesthetics fs = 18 fs_eps = 0.65 #slice results t = results[:, 0] T = results[:, 1] Teff = results[:, 2] n = results[:, 3] Yz = results[:, 4:] #setup figure fig, axes = plt.subplots(3, 1, figsize=(10, 8), sharex=True)
def f(fig, *args, **kwargs): gs = gridspec.GridSpec(3, 6) # gs.update(hspace=0.4, wspace=0.3, bottom=0.08, top=0.97, left=0.08, right=0.98) ax1 = plt.subplot(gs[:2, :4]) ax2 = plt.subplot(gs[1, 4:6]) ax3 = plt.subplot(gs[2, 0:2]) ax4 = plt.subplot(gs[2, 2:4]) ax5 = plt.subplot(gs[2, 4:6]) samples = res.get_sorted_planet_samples() samples, mask = \ res.apply_cuts_period(samples, 90, None, return_mask=True) t, y, yerr = res.data.T over = 0.1 tt = np.linspace(t[0]-over*t.ptp(), t[-1]+over*t.ptp(), 10000+int(100*over)) y = res.data[:,1].copy() yerr = res.data[:,2].copy() # select random `ncurves` indices # from the (sorted, period-cut) posterior samples ncurves = 10 ii = np.random.randint(samples.shape[0], size=ncurves) ## plot the Keplerian curves for i in ii: v = np.zeros_like(tt) pars = samples[i, :].copy() nplanets = pars.size / res.n_dimensions for j in range(nplanets): P = pars[j + 0*res.max_components] K = pars[j + 1*res.max_components] phi = pars[j + 2*res.max_components] t0 = t[0] - (P*phi)/(2.*np.pi) ecc = pars[j + 3*res.max_components] w = pars[j + 4*res.max_components] v += keplerian(tt, P, K, ecc, w, t0, 0.) vsys = res.posterior_sample[mask][i, -1] v += vsys ax1.plot(tt, v, alpha=0.2, color='k') ax1.errorbar(*res.data.T, fmt='o', mec='none', capsize=0, ms=4, color=sns.color_palette()[2]) ax1.set(xlabel='Time [days]', ylabel='RV [m/s]',) n, bins, _ = ax2.hist(res.posterior_sample[:, res.index_component], bins=np.arange(2, 4)-0.5, align='mid', rwidth=0.5, color='k', alpha=0.5) ax2.set(#title=r'posterior for $N_p$', xlabel=r'$N_p$', ylabel='Posterior', yticks=[], xticks=range(3),)# xticklabels=map(str, range(3))) ax2.set_xlim([-0.5, res.max_components+.5]) # bins = 10 ** np.linspace(np.log10(90), np.log10(1e3), 100) ax31 = plt.subplot(gs[2, 0]) ax32 = plt.subplot(gs[2, 1]) ax31.hist(samples[:,0], histtype='stepfilled', bins=np.linspace(90,110,50)) ax32.hist(samples[:,1], bins=np.linspace(600,800,30), histtype='stepfilled', color=colors[1]) # ax3.set_xlim(70, 1000) for ax in [ax31, ax32]: ax.set_yticks([]) ax.xaxis.tick_bottom() ax31.set_xlim(90, 112) ax31.set_xticks([90, 100, 110]) ax32.set_xlim(590, 800) ax32.set_xticks([600, 700, 800]) ax31.spines['right'].set_visible(False) ax32.spines['left'].set_visible(False) ax31.set_ylabel('Posterior') # ax2.spines['top'].set_visible(False) # ax.xaxis.tick_top() # ax.tick_params(labeltop='off') # don't put tick labels at the top # xlabel='Period [days]', fig.text(0.215, 0.017, 'Period [days]', ha='center') ax41 = plt.subplot(gs[2, 2]) ax42 = plt.subplot(gs[2, 3]) # bins = 10 ** np.linspace(np.log10(1), np.log10(1e3), 40) ax41.hist(samples[:,2], histtype='stepfilled') ax42.hist(samples[:,3], histtype='stepfilled', color=colors[1]) for ax in [ax41, ax42]: ax.set_yticks([]) ax.xaxis.tick_bottom() ax41.set_xlim(5, 16) ax41.set_xticks([5, 10, 15]) ax42.set_xlim(54, 65) ax42.set_xticks([55, 60, 65]) ax41.spines['right'].set_visible(False) ax42.spines['left'].set_visible(False) ax41.set_ylabel('Posterior') fig.text(0.53, 0.017, 'Semi-amplitude [m/s]', ha='center') ax5.hist(samples[:,6], bins=np.linspace(0, 0.5, 30), histtype='stepfilled') ax5.hist(samples[:,7], bins=np.linspace(0, 0.5, 30), histtype='stepfilled') ax5.set(xlabel='Eccentricity', yticks=[], ylabel='Posterior') ax5.xaxis.labelpad = 6 im = image.imread('../../logo/logo_small.png') # aximg = plt.subplot(gs[0, 5]) aximg = plt.axes([0.85, 0.85, 0.12, 0.12]) aximg.axis('off') aximg.imshow(im, alpha=1, extent=(0, 10, 0, 10))
if_temp = _env.odir_root + '/summary_' + ds + '/country_specific_statistics_Temp_' + ds + '_' + p_scen + '.csv' if_gdp = _env.odir_root + '/summary_' + ds + '/country_specific_statistics_GDP_' + ds + '_' + p_scen + '_Burke.xls' if_ctrylist = _env.idir_root + '/regioncode/Country_List.xls' odir_plot = _env.odir_root + '/plot/' _env.mkdirs(odir_plot) of_plot = odir_plot + 'ED_F8.Bar_GDP_Impacts_G20.png' ctry_g20 = [ 'United States', 'Australia', 'Canada', 'Saudi Arabia', 'India', 'Russia', 'South Africa', 'Turkey', 'Argentina', 'Brazil', 'Mexico', 'France', 'Germany', 'Italy', 'United Kingdom', 'China', 'Indonesia', 'Japan', 'South Korea' ] cmap_virdis = (sns.color_palette('viridis', 11).as_hex()) itbl_temp = pd.read_csv(if_temp, index_col=0) itbl_gdp = pd.read_excel(if_gdp, 'country-lag0') itbl_ctrylist = pd.read_excel(if_ctrylist) itbl_ctrylist.set_index('ISO', inplace=True) mtbl_tg = itbl_temp[['Temp_mean_climatological']].copy() for gc in [ 'iso', sgdp_year + '_gdpcap', sgdp_year + '_gdp', sgdp_year + '_pop', 'GDP_median_benefit', 'GDP_median_benefit_ratio' ]: mtbl_tg[gc] = itbl_gdp[gc].copy() mtbl_tg.set_index('iso', inplace=True)
def contrastplot_test(data, x, y, idx=None, alpha=0.75, axis_title_size=None, barWidth=5, contrastShareY=True, contrastEffectSizeLineStyle='solid', contrastEffectSizeLineColor='black', contrastYlim=None, contrastZeroLineStyle='solid', contrastZeroLineColor='black', effectSizeYLabel="Effect Size", figsize=None, floatContrast=True, floatSwarmSpacer=0.2, heightRatio=(1, 1), idcol=None, lineWidth=2, legend=True, legendFontSize=14, legendFontProps={}, paired=False, pal=None, rawMarkerSize=8, rawMarkerType='o', reps=3000, showGroupCount=True, show95CI=False, showAllYAxes=False, showRawData=True, smoothboot=False, statfunction=None, summaryBar=False, summaryBarColor='grey', summaryBarAlpha=0.25, summaryColour='black', summaryLine=True, summaryLineStyle='solid', summaryLineWidth=0.25, summaryMarkerSize=10, summaryMarkerType='o', swarmShareY=True, swarmYlim=None, tickAngle=45, tickAlignment='right', violinOffset=0.375, violinWidth=0.2, violinColor='k', xticksize=None, yticksize=None, **kwargs): '''Takes a pandas dataframe and produces a contrast plot: either a Cummings hub-and-spoke plot or a Gardner-Altman contrast plot. ----------------------------------------------------------------------- Description of flags upcoming.''' # Check that `data` is a pandas dataframe if 'DataFrame' not in str(type(data)): raise TypeError( "The object passed to the command is not not a pandas DataFrame.\ Please convert it to a pandas DataFrame.") # Get and set levels of data[x] if idx is None: widthratio = [1] allgrps = np.sort(data[x].unique()) if paired: # If `idx` is not specified, just take the FIRST TWO levels alphabetically. tuple_in = tuple(allgrps[0:2], ) else: # No idx is given, so all groups are compared to the first one in the DataFrame column. tuple_in = (tuple(allgrps), ) if len(allgrps) > 2: floatContrast = False else: if all(isinstance(element, str) for element in idx): # if idx is supplied but not a multiplot (ie single list or tuple) tuple_in = (idx, ) widthratio = [1] if len(idx) > 2: floatContrast = False elif all(isinstance(element, tuple) for element in idx): # if idx is supplied, and it is a list/tuple of tuples or lists, we have a multiplot! tuple_in = idx if (any(len(element) > 2 for element in tuple_in)): # if any of the tuples in idx has more than 2 groups, we turn set floatContrast as False. floatContrast = False # Make sure the widthratio of the seperate multiplot corresponds to how # many groups there are in each one. widthratio = [] for i in tuple_in: widthratio.append(len(i)) else: raise TypeError( "The object passed to `idx` consists of a mixture of single strings and tuples. \ Please make sure that `idx` is either a tuple of column names, or a tuple of tuples for plotting." ) # initialise statfunction if statfunction == None: statfunction = np.mean # Create list to collect all the contrast DataFrames generated. contrastList = list() contrastListNames = list() # # Calculate the bootstraps according to idx. # for ix, current_tuple in enumerate(tuple_in): # bscontrast=list() # for i in range (1, len(current_tuple)): # # Note that you start from one. No need to do auto-contrast! # tempbs=bootstrap_contrast( # data=data, # x=x, # y=y, # idx=[current_tuple[0], current_tuple[i]], # statfunction=statfunction, # smoothboot=smoothboot, # reps=reps) # bscontrast.append(tempbs) # contrastList.append(tempbs) # contrastListNames.append(current_tuple[i]+' vs. '+current_tuple[0]) # Setting color palette for plotting. if pal is None: if 'hue' in kwargs: colorCol = kwargs['hue'] colGrps = data[colorCol].unique() nColors = len(colGrps) else: colorCol = x colGrps = data[x].unique() nColors = len([element for tupl in tuple_in for element in tupl]) plotPal = dict(zip(colGrps, sns.color_palette(n_colors=nColors))) else: plotPal = pal # Ensure summaryLine and summaryBar are not displayed together. if summaryLine is True and summaryBar is True: summaryBar = True summaryLine = False # Turn off summary line if floatContrast is true if floatContrast: summaryLine = False if swarmYlim is None: # get range of _selected groups_. u = list() for t in idx: for i in np.unique(t): u.append(i) u = np.unique(u) tempdat = data[data[x].isin(u)] swarm_ylim = np.array([np.min(tempdat[y]), np.max(tempdat[y])]) else: swarm_ylim = np.array([swarmYlim[0], swarmYlim[1]]) if contrastYlim is not None: contrastYlim = np.array([contrastYlim[0], contrastYlim[1]]) barWidth = barWidth / 1000 # Not sure why have to reduce the barwidth by this much! if showRawData is True: maxSwarmSpan = 0.25 else: maxSwarmSpan = barWidth # Expand the ylim in both directions. ## Find half of the range of swarm_ylim. swarmrange = swarm_ylim[1] - swarm_ylim[0] pad = 0.1 * swarmrange x2 = np.array([swarm_ylim[0] - pad, swarm_ylim[1] + pad]) swarm_ylim = x2 # plot params if axis_title_size is None: axis_title_size = 25 if yticksize is None: yticksize = 18 if xticksize is None: xticksize = 18 # Set clean style sns.set(style='ticks') axisTitleParams = {'labelsize': axis_title_size} xtickParams = {'labelsize': xticksize} ytickParams = {'labelsize': yticksize} svgParams = {'fonttype': 'none'} rc('axes', **axisTitleParams) rc('xtick', **xtickParams) rc('ytick', **ytickParams) rc('svg', **svgParams) if figsize is None: if len(tuple_in) > 2: figsize = (12, (12 / np.sqrt(2))) else: figsize = (8, (8 / np.sqrt(2))) # Initialise figure, taking into account desired figsize. fig = plt.figure(figsize=figsize) # Initialise GridSpec based on `tuple_in` shape. gsMain = gridspec.GridSpec( 1, np.shape(tuple_in)[0], # 1 row; columns based on number of tuples in tuple. width_ratios=widthratio, wspace=0) for gsIdx, current_tuple in enumerate(tuple_in): #### FOR EACH TUPLE IN IDX plotdat = data[data[x].isin(current_tuple)] plotdat[x] = plotdat[x].astype("category") plotdat[x].cat.set_categories(current_tuple, ordered=True, inplace=True) plotdat.sort_values(by=[x]) # Drop all nans. plotdat = plotdat.dropna() # Calculate summaries. summaries = plotdat.groupby([x], sort=True)[y].apply(statfunction) if floatContrast is True: # Use fig.add_subplot instead of plt.Subplot ax_raw = fig.add_subplot(gsMain[gsIdx], frame_on=False) ax_contrast = ax_raw.twinx() else: # Create subGridSpec with 2 rows and 1 column. subGridSpec = gridspec.GridSpecFromSubplotSpec( 2, 1, subplot_spec=gsMain[gsIdx], wspace=0) # Use plt.Subplot instead of fig.add_subplot ax_raw = plt.Subplot(fig, subGridSpec[0, 0], frame_on=False) ax_contrast = plt.Subplot(fig, subGridSpec[1, 0], sharex=ax_raw, frame_on=False) # Calculate the boostrapped contrast bscontrast = list() for i in range(1, len(current_tuple)): # Note that you start from one. No need to do auto-contrast! tempbs = bootstrap_contrast( data=data, x=x, y=y, idx=[current_tuple[0], current_tuple[i]], statfunction=statfunction, smoothboot=smoothboot, reps=reps) bscontrast.append(tempbs) contrastList.append(tempbs) contrastListNames.append(current_tuple[i] + ' vs. ' + current_tuple[0]) #### PLOT RAW DATA. if showRawData is True: # Seaborn swarmplot doc says to set custom ylims first. ax_raw.set_ylim(swarm_ylim) sw = sns.swarmplot(data=plotdat, x=x, y=y, order=current_tuple, ax=ax_raw, alpha=alpha, palette=plotPal, size=rawMarkerSize, marker=rawMarkerType, **kwargs) if summaryBar is True: bar_raw = sns.barplot(x=summaries.index.tolist(), y=summaries.values, facecolor=summaryBarColor, ax=ax_raw, alpha=summaryBarAlpha) if floatContrast: # Get horizontal offset values. maxXBefore = max(sw.collections[0].get_offsets().T[0]) minXAfter = min(sw.collections[1].get_offsets().T[0]) xposAfter = maxXBefore + floatSwarmSpacer xAfterShift = minXAfter - xposAfter # shift the swarmplots offsetSwarmX(sw.collections[1], -xAfterShift) ## get swarm with largest span, set as max width of each barplot. for i, bar in enumerate(bar_raw.patches): x_width = bar.get_x() width = bar.get_width() centre = x_width + (width / 2.) if i == 0: bar.set_x(centre - maxSwarmSpan / 2.) else: bar.set_x(centre - xAfterShift - maxSwarmSpan / 2.) bar.set_width(maxSwarmSpan) ## Set the ticks locations for ax_raw. ax_raw.xaxis.set_ticks((0, xposAfter)) firstTick = ax_raw.xaxis.get_ticklabels()[0].get_text() secondTick = ax_raw.xaxis.get_ticklabels()[1].get_text() ax_raw.set_xticklabels( [ firstTick, #+' n='+count[firstTick], secondTick ], #+' n='+count[secondTick]], rotation=tickAngle, horizontalalignment=tickAlignment) if summaryLine is True: for i, m in enumerate(summaries): ax_raw.plot( (i - summaryLineWidth, i + summaryLineWidth), # x-coordinates (m, m), color=summaryColour, linestyle=summaryLineStyle) if show95CI is True: sns.barplot(data=plotdat, x=x, y=y, ax=ax_raw, alpha=0, ci=95) ax_raw.set_xlabel("") if floatContrast is False: fig.add_subplot(ax_raw) #### PLOT CONTRAST DATA. if len(current_tuple) == 2: # Plot the CIs on the contrast axes. plotbootstrap(sw.collections[1], bslist=tempbs, ax=ax_contrast, violinWidth=violinWidth, violinOffset=violinOffset, markersize=summaryMarkerSize, marker=summaryMarkerType, offset=floatContrast, color=violinColor, linewidth=1) if floatContrast: # Set reference lines ## First get leftmost limit of left reference group xtemp, _ = np.array(sw.collections[0].get_offsets()).T leftxlim = xtemp.min() ## Then get leftmost limit of right test group xtemp, _ = np.array(sw.collections[1].get_offsets()).T rightxlim = xtemp.min() ## zero line ax_contrast.hlines( 0, # y-coordinates leftxlim, 3.5, # x-coordinates, start and end. linestyle=contrastZeroLineStyle, linewidth=0.75, color=contrastZeroLineColor) ## effect size line ax_contrast.hlines( tempbs['summary'], rightxlim, 3.5, # x-coordinates, start and end. linestyle=contrastEffectSizeLineStyle, linewidth=0.75, color=contrastEffectSizeLineColor) ## If the effect size is positive, shift the right axis up. if float(tempbs['summary']) > 0: rightmin = ax_raw.get_ylim()[0] - float(tempbs['summary']) rightmax = ax_raw.get_ylim()[1] - float(tempbs['summary']) ## If the effect size is negative, shift the right axis down. elif float(tempbs['summary']) < 0: rightmin = ax_raw.get_ylim()[0] + float(tempbs['summary']) rightmax = ax_raw.get_ylim()[1] + float(tempbs['summary']) ax_contrast.set_ylim(rightmin, rightmax) if gsIdx > 0: ax_contrast.set_ylabel('') align_yaxis(ax_raw, tempbs['statistic_ref'], ax_contrast, 0.) else: # Set bottom axes ybounds if contrastYlim is not None: ax_contrast.set_ylim(contrastYlim) # Set xlims so everything is properly visible! swarm_xbounds = ax_raw.get_xbound() ax_contrast.set_xbound( swarm_xbounds[0] - (summaryLineWidth * 1.1), swarm_xbounds[1] + (summaryLineWidth * 1.1)) else: # Plot the CIs on the bottom axes. plotbootstrap_hubspoke(bslist=bscontrast, ax=ax_contrast, violinWidth=violinWidth, violinOffset=violinOffset, markersize=summaryMarkerSize, marker=summaryMarkerType, linewidth=lineWidth) if floatContrast is False: fig.add_subplot(ax_contrast) if gsIdx > 0: ax_raw.set_ylabel('') ax_contrast.set_ylabel('') # Turn contrastList into a pandas DataFrame, contrastList = pd.DataFrame(contrastList).T contrastList.columns = contrastListNames ######## axesCount = len(fig.get_axes()) ## Loop thru SWARM axes for aesthetic touchups. for i in range(0, axesCount, 2): axx = fig.axes[i] if i != axesCount - 2 and 'hue' in kwargs: # If this is not the final swarmplot, remove the hue legend. axx.legend().set_visible(False) if floatContrast is False: axx.xaxis.set_visible(False) sns.despine(ax=axx, trim=True, bottom=False, left=False) else: sns.despine(ax=axx, trim=True, bottom=True, left=True) if showAllYAxes is False: if i in range(2, axesCount): axx.yaxis.set_visible(showAllYAxes) else: # Draw back the lines for the relevant y-axes. # Not entirely sure why I have to do this. drawback_y(axx) # Add zero reference line for swarmplots with bars. if summaryBar is True: axx.add_artist( Line2D((axx.xaxis.get_view_interval()[0], axx.xaxis.get_view_interval()[1]), (0, 0), color='black', linewidth=0.75)) # I don't know why the swarm axes controls the contrast axes ticks.... if showGroupCount: count = data.groupby(x).count()[y] newticks = list() for ix, t in enumerate(axx.xaxis.get_ticklabels()): t_text = t.get_text() nt = t_text + ' n=' + str(count[t_text]) newticks.append(nt) axx.xaxis.set_ticklabels(newticks) if legend is False: axx.legend().set_visible(False) else: if i == axesCount - 2: # the last (rightmost) swarm axes. axx.legend(loc='top right', bbox_to_anchor=(1.1, 1.0), fontsize=legendFontSize, **legendFontProps) ## Loop thru the CONTRAST axes and perform aesthetic touch-ups. ## Get the y-limits: for j, i in enumerate(range(1, axesCount, 2)): axx = fig.get_axes()[i] if floatContrast is False: xleft, xright = axx.xaxis.get_view_interval() # Draw zero reference line. axx.hlines(y=0, xmin=xleft - 1, xmax=xright + 1, linestyle=contrastZeroLineStyle, linewidth=0.75, color=contrastZeroLineColor) # reset view interval. axx.set_xlim(xleft, xright) # # Draw back x-axis lines connecting ticks. # drawback_x(axx) if showAllYAxes is False: if i in range(2, axesCount): axx.yaxis.set_visible(False) else: # Draw back the lines for the relevant y-axes. # Not entirely sure why I have to do this. drawback_y(axx) sns.despine(ax=axx, top=True, right=True, left=False, bottom=False, trim=True) # Rotate tick labels. rotateTicks(axx, tickAngle, tickAlignment) else: # Re-draw the floating axis to the correct limits. lower = np.min(contrastList.ix['diffarray', j]) upper = np.max(contrastList.ix['diffarray', j]) meandiff = contrastList.ix['summary', j] ## Make sure we have zero in the limits. if lower > 0: lower = 0. if upper < 0: upper = 0. ## Get the tick interval from the left y-axis. leftticks = fig.get_axes()[i - 1].get_yticks() tickstep = leftticks[1] - leftticks[0] ## First re-draw of axis with new tick interval axx.yaxis.set_major_locator(MultipleLocator(base=tickstep)) newticks1 = axx.get_yticks() ## Obtain major ticks that comfortably encompass lower and upper. newticks2 = list() for a, b in enumerate(newticks1): if (b >= lower and b <= upper): # if the tick lies within upper and lower, take it. newticks2.append(b) # if the meandiff falls outside of the newticks2 set, add a tick in the right direction. if np.max(newticks2) < meandiff: ind = np.where(newticks1 == np.max(newticks2))[0][ 0] # find out the max tick index in newticks1. newticks2.append(newticks1[ind + 1]) elif meandiff < np.min(newticks2): ind = np.where(newticks1 == np.min(newticks2))[0][ 0] # find out the min tick index in newticks1. newticks2.append(newticks1[ind - 1]) newticks2 = np.array(newticks2) newticks2.sort() ## Second re-draw of axis to shrink it to desired limits. axx.yaxis.set_major_locator(FixedLocator(locs=newticks2)) ## Despine the axes. sns.despine(ax=axx, trim=True, bottom=False, right=False, left=True, top=True) # Normalize bottom/right Contrast axes to each other for Cummings hub-and-spoke plots. if (axesCount > 2 and contrastShareY is True and floatContrast is False): # Set contrast ylim as max ticks of leftmost swarm axes. if contrastYlim is None: lower = list() upper = list() for c in range(0, len(contrastList.columns)): lower.append(np.min(contrastList.ix['bca_ci_low', c])) upper.append(np.max(contrastList.ix['bca_ci_high', c])) lower = np.min(lower) upper = np.max(upper) else: lower = contrastYlim[0] upper = contrastYlim[1] normalizeContrastY(fig, contrast_ylim=contrastYlim, show_all_yaxes=showAllYAxes) # if (axesCount==2 and # floatContrast is False): # drawback_x(fig.get_axes()[1]) # drawback_y(fig.get_axes()[1]) # if swarmShareY is False: # for i in range(0, axesCount, 2): # drawback_y(fig.get_axes()[i]) # if contrastShareY is False: # for i in range(1, axesCount, 2): # if floatContrast is True: # sns.despine(ax=fig.get_axes()[i], # top=True, right=False, left=True, bottom=True, # trim=True) # else: # sns.despine(ax=fig.get_axes()[i], trim=True) # Zero gaps between plots on the same row, if floatContrast is False if (floatContrast is False and showAllYAxes is False): gsMain.update(wspace=0.) else: # Tight Layout! gsMain.tight_layout(fig) # And we're all done. rcdefaults() # restore matplotlib defaults. sns.set() # restore seaborn defaults. return fig, contrastList
def compare_spectrograms(factories, x_signal, graph, pos, weight=None, file_name=None, show_ncomps=None): palette = sns.cubehelix_palette(256, start=2, rot=0, dark=0.15, light=1) cmap = colors.ListedColormap(palette) stem_palette = sns.color_palette('Set1', n_colors=2) def show_spectrogram(s): s /= np.atleast_2d(np.max(s, axis=0)) s_range = np.max(s) - np.min(s) s = utils.smoothstep(s, min_edge=np.min(s) + s_range / 3, max_edge=np.max(s) - s_range / 10) if show_ncomps is None: spec.plot(s, cmap) else: spec.plot(s[:show_ncomps, :], cmap) def show_argmax_spectrogram_graph(s, vertex_size=20, amax_file_name=None): amax = np.argmax(np.abs(s), axis=0) n_values = np.unique(amax).size assignment = graph.new_vertex_property('double', vals=amax) if weight is None: edge_pen_width = 1.0 else: edge_pen_width = weight palette = sns.color_palette('BuGn', n_colors=n_values) cmap = colors.ListedColormap(palette) gt_draw.graph_draw(graph, pos=pos, vertex_color=[0, 0, 0, 0.5], vertex_fill_color=assignment, vcmap=cmap, vertex_size=vertex_size, edge_color=[0, 0, 0, 0.7], edge_pen_width=edge_pen_width, output=amax_file_name, output_size=(1200, 1200)) def show_argmax_spectrogram_1d(s): amax = np.argmax(np.abs(s), axis=0) _, stemlines, baseline = plt.stem(amax, markerfmt=' ') plt.setp(stemlines, 'color', stem_palette[1]) plt.setp(baseline, 'color','k') plt.ylim((0, s.shape[0])) if file_name is None: plt.figure() for i in range(len(factories)): spectrogram = factories[i].compute(x_signal) plt.subplot(2, 4, i + 1) show_spectrogram(spectrogram) plt.subplot(2, 4, 5 + i) show_argmax_spectrogram_1d(spectrogram) else: file_name += '_{0}_{1}' for i in range(len(factories)): spectrogram = factories[i].compute(x_signal) plt.figure() show_spectrogram(spectrogram) plt.savefig(file_name.format(i, 'spec.pdf'), dpi=300) plt.figure() show_argmax_spectrogram_1d(spectrogram) plt.savefig(file_name.format(i, 'spec_amax.pdf'), dpi=300) amax_file_name = file_name.format(i, 'spec_amax.png') show_argmax_spectrogram_graph(spectrogram, amax_file_name=amax_file_name)
R_tot_shuffling_Culture_median = np.median(R_tot_shuffling_Culture) R_tot_shuffling_Culture_median_loCI, R_tot_shuffling_Culture_median_hiCI = plots.get_CI_median( R_tot_shuffling_Culture) R_tot_fivebins_Culture_median = np.median(R_tot_fivebins_Culture) R_tot_fivebins_Culture_median_loCI, R_tot_fivebins_Culture_median_hiCI = plots.get_CI_median( R_tot_fivebins_Culture) R_tot_onebin_Culture_median = np.median(R_tot_onebin_Culture) R_tot_onebin_Culture_median_loCI, R_tot_onebin_Culture_median_hiCI = plots.get_CI_median( R_tot_onebin_Culture) R_tot_glm_Culture_median = np.median(R_tot_glm_Culture) R_tot_glm_Culture_median_loCI, R_tot_glm_Culture_median_hiCI = plots.get_CI_median( R_tot_glm_Culture) # Colors main_red = sns.color_palette("RdBu_r", 15)[12] main_blue = sns.color_palette("RdBu_r", 15)[1] soft_red = sns.color_palette("RdBu_r", 15)[10] soft_blue = sns.color_palette("RdBu_r", 15)[4] violet = sns.cubehelix_palette(8)[4] green = sns.cubehelix_palette(8, start=.5, rot=-.75)[3] fig = plt.figure(figsize=(5., 3.)) ax = plt.subplot2grid((17, 1), (0, 0), colspan=1, rowspan=15) ax2 = plt.subplot2grid((17, 1), (16, 0), colspan=1, rowspan=1, sharex=ax) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['bottom'].set_visible(False)
args = parser.parse_args() #import results results=np.loadtxt(args.output_file) #check dimensions _,c = np.shape(results) if c-4 != args.spec_to-args.spec_from+1: print("Mismatch between spectroscopic indices(%d) and results file(%d)."%(args.spec_to-args.spec_from+1,c-4)) print("Exiting...") sys.exit() num_ipf = c-4 spec_labs = [] [spec_labs.append(roman.toRoman(i)) for i in range(args.spec_from,args.spec_to+1)] spec_colors = [] cpal = sns.color_palette('husl',num_ipf) [spec_colors.append(cpal[i]) for i in range(num_ipf)] #aesthetics fs=18 fs_eps=0.65 #slice results t=results[:,0] T=results[:,1] Teff=results[:,2] n=results[:,3] Yz=results[:,4:] #setup figure fig,axes = plt.subplots(3,1,figsize=(10,8),sharex=True)