def stacked_area_chart( data: dict, ax: mpl.axes, domains_in_focus: Optional[list] = None, percentage: bool = False, colormap: Optional[mpl.colors.LinearSegmentedColormap] = None, color_default: Optional[np.array] = None, ): """ Parameters ---------- data : Dictionary with a format {'x_axis_labels': {'y_axis_labels': y_values}} domains_in_focus : percentage : """ x = list(data.keys()) y = data_transformation(data, percentage) ylabels = get_ylabels(data) colors = utils.create_color_palette( ylabels, domains_in_focus, colormap, include_dof=True, return_dict=False, ) ax.stackplot( x, y, colors=colors, ) ax.set_xlim(np.min(x), np.max(x)) ax.set_ylim(np.min(y), np.max(y)) return ax
def makePowerSpectrum( self, freqs: np.array, power: np.array, sm_power: np.array, band_max_power: float, freq_at_band_max_power: float, max_freq: int = 50, theta_range: tuple = [6, 12], ax: matplotlib.axes = None, **kwargs) -> matplotlib.axes: # downsample frequencies and power freqs = freqs[0::50] power = power[0::50] sm_power = sm_power[0::50] if ax is None: fig = plt.figure() ax = fig.add_subplot(111) ax.plot(freqs, power, alpha=0.5, color=[0.8627, 0.8627, 0.8627]) ax.plot(freqs, sm_power) ax.set_xlim(0, max_freq) ylim = [0, band_max_power / 0.8] if 'ylim' in kwargs: ylim = kwargs['ylim'] ax.set_ylim(ylim) ax.set_ylabel('Power') ax.set_xlabel('Frequency') ax.text( x=theta_range[1] / 0.9, y=band_max_power, s=str(freq_at_band_max_power)[0:4], fontsize=20) from matplotlib.patches import Rectangle r = Rectangle(( theta_range[0], 0), width=np.diff(theta_range)[0], height=np.diff(ax.get_ylim())[0], alpha=0.25, color='r', ec='none') ax.add_patch(r) return ax
def evolution_of_participation_1D( data: dict, ax: mpl.axes, entity_in_focus: Optional[list] = None, percentage: bool = False, colormap: mpl.colors.LinearSegmentedColormap = mpl.cm.jet, ) -> mpl.axes: """ Parameters ---------- data : Dictionary with a format {'x_axis_labels': {'y_axis_labels': y_values}} entity_in_focus : percentage : """ x = list(data.keys()) ylabels = stackedareachart.get_ylabels(data) y = stackedareachart.data_transformation(data, ylabels, percentage) colors = utils.create_color_palette( ylabels, entity_in_focus, colormap, include_dof=False, return_dict=True, ) for iy, ylab in enumerate(ylabels): if ylab in entity_in_focus: ax.plot( x, y[iy, :], color="w", linewidth=4, zorder=1, ) ax.plot( x, y[iy, :], color=colors[ylab], linewidth=3, zorder=1, label=ylab, ) else: ax.plot( x, y[iy, :], color="grey", linewidth=1, zorder=0, alpha=0.2, ) if np.isfinite(np.max(x)): ax.set_xlim(np.min(x), np.max(x)) if np.isfinite(np.max(y)): ax.set_ylim(np.min(y), np.max(y)) return ax
def plotTTPMat(ax: axes, toa: np.array, ttp: np.array, title: str = None, plot_ylabel: bool = False) -> None: ax.scatter(toa, ttp, marker='o', c=ttp, alpha=0.75) ax.set_ylim(PRI_DETECTED_RANGE[0], PRI_DETECTED_RANGE[1]) ax.xaxis.get_major_formatter().set_powerlimits((0, 1)) ax.set_title(title, fontsize=10) ax.set_xlabel('toa[us]', fontsize=8, loc='right') if plot_ylabel: ax.set_ylabel('pri[us]', fontsize=9)
def plot_chromatograph( seq: SeqRecord, region: Tuple[int, int] = None, ax: mpl.axes = None ) -> plt.axes: """Plot Sanger chromatograph. region: include both start and end (1-based) """ if seq is None: return ax if region is None: # turn into 0 based for better indexing region_start, region_end = 0, len(seq) else: region_start = max(region[0], 0) region_end = min(region[1], len(seq) - 1) if ax is None: _, ax = plt.subplots(1, 1, figsize=(16, 6)) _colors = defaultdict( lambda: "purple", {"A": "g", "C": "b", "G": "k", "T": "r"} ) # Get signals peaks = seq.annotations["peak positions"] trace_x = seq.annotations["trace_x"] traces_y = [seq.annotations["channel " + str(i)] for i in range(1, 5)] bases = seq.annotations["channels"] xlim_left, xlim_right = peaks[region_start] - 1, peaks[region_end] + 0.5 # subset peak and sequence # TODO: this might fix the bug peak_start = peaks[0] peak_zip = [ (p, s) for i, (p, s) in enumerate(zip(peaks, seq)) if region_start <= i <= region_end ] peaks, seq = list(zip(*peak_zip)) # subset trace_x and traces_y together trace_zip = [ (x + peak_start, *ys) for x, *ys in zip(trace_x, *traces_y) if xlim_left <= x <= xlim_right ] if not trace_zip: return ax trace_x, *traces_y = list(zip(*trace_zip)) # Plot traces trmax = max(map(max, traces_y)) for base in bases: trace_y = [1.0 * ci / trmax for ci in traces_y[bases.index(base)]] ax.plot(trace_x, trace_y, color=_colors[base], lw=2, label=base) ax.fill_between( trace_x, 0, trace_y, facecolor=_colors[base], alpha=0.125 ) # Plot bases at peak positions for i, peak in enumerate(peaks): # LOGGER.debug(f"{i}, {peak}, {seq[i]}, {xlim_left + i}") ax.text( peak, -0.11, seq[i], color=_colors[seq[i]], va="center", ha="center", alpha=0.66, fontsize="x-large", fontweight="bold", ) ax.set_ylim(bottom=-0.15, top=1.05) # peaks[0] - max(2, 0.02 * (peaks[-1] - peaks[0])), # right=peaks[-1] + max(2, 0.02 * (peaks[-1] - peaks[0])), ax.set_xlim(xlim_left + 0.5, xlim_right) ax.set_xticks(peaks) ax.set_xticklabels(list(range(region_start + 1, region_end + 2))) # hide y axis ax.set_yticklabels([]) ax.get_yaxis().set_visible(False) # hide border ax.spines["left"].set_visible(False) ax.spines["right"].set_visible(False) ax.spines["top"].set_visible(False) # hide grid ax.grid(False) # set legend ax.legend(loc="upper left", bbox_to_anchor=(0.95, 0.99)) return ax
def evolution_of_participation_2D( xdata: dict, ydata: dict, ax: mpl.axes, entity_in_focus: Optional[list] = None, percentage: bool = False, colormap: mpl.colors.LinearSegmentedColormap = mpl.cm.jet, ) -> mpl.axes: """ Parameters ---------- data : Dictionary with a format {'x_axis_labels': {'y_axis_labels': y_values}} entity_in_focus : percentage : """ # TODO: include time indication xlabels = stackedareachart.get_ylabels(xdata) ylabels = stackedareachart.get_ylabels(ydata) # ensure uniform order labels = list(set(xlabels + ylabels)) xindx = [xlabels.index(lab) if lab in xlabels else None for lab in labels] xlabels = [xlabels[i] if i is not None else None for i in xindx] yindx = [ylabels.index(lab) if lab in ylabels else None for lab in labels] ylabels = [ylabels[i] if i is not None else None for i in yindx] # create arrays with format (# of ylabels, # of xlabels) x = stackedareachart.data_transformation(xdata, xlabels, percentage) y = stackedareachart.data_transformation(ydata, ylabels, percentage) colors = utils.create_color_palette( ylabels, entity_in_focus, colormap, include_dof=False, return_dict=True, ) ax.plot([0, np.max(y)], [0, np.max(y)], c="k", linestyle="--", zorder=0) for i, lab in enumerate(labels): if lab in entity_in_focus: ax.plot( x[i, :], y[i, :], color="w", linewidth=4, zorder=1, ) ax.plot( x[i, :], y[i, :], color=colors[lab], linewidth=3, zorder=1, label=lab, ) else: ax.plot( x[i, :], y[i, :], color="grey", linewidth=1, zorder=0, alpha=0.2, ) ax.set_xlim(np.min(x), np.max(x)) ax.set_ylim(np.min(y), np.max(y)) return ax
def cohort_bar(cohort_averages: dict, cohort_data: dict, observable: str, yaxis_upper: int = None, ax: matplotlib.axes = None, labelsize: int = 12, ticksize: int = 10, legendsize: int = 8, markersize=15) -> None: """Plots either the V- or J-gene usages. Parameters ---------- cohort_averages : dict Dictionary of averages and variations within a cohort for all severities. cohort_dict : dict Dictionary of all statistics of all individuals in a cohort for all severities. observable : str The quantity which is going to be plotted. yaxis_upper : int, optional Specifies the upper limit of the y-axis on the plot. ax : matplotlib.axes, optional Used to modify an already existing axes when creating a figure with a grid. labelsize : int, optional Size of axes labels. ticksize : int, optional Size of tick labels. legendsize : int, optional Specifies font size of strings in legend. Returns ------- None """ if ax is None: fig = plt.figure(dpi=300, figsize=(16, 4)) ax = fig.add_subplot(111) # Give the bars for each gene some space among each other. width = 1.0 / len(cohort_averages) - 0.02 bars = [] if 'Asymptomatic' in cohort_averages: ordering = ['Healthy', 'Mild', 'Moderate', 'Severe', 'Asymptomatic'] else: ordering = sorted(cohort_averages.keys()) # Sort the genes by descending usage in the healthy cohort. if 'Briney/GRP' in cohort_averages: sorted_genes = [ gene for _, gene in sorted(zip( cohort_averages['Briney/GRP'][observable][0], cohort_averages['Briney/GRP'][observable][-1]), key=lambda pair: pair[0], reverse=True) ] else: sorted_genes = [ gene for _, gene in sorted(zip( cohort_averages['Healthy'][observable][0], cohort_averages['Healthy'][observable][-1]), key=lambda pair: pair[0], reverse=True) ] # Because there are so many V genes, plot only those which have at least # 1% average usage in at least one cohort. if 'v' in observable: good_genes = [] for gene in sorted_genes: bools = 0 for severity in cohort_averages: idx = cohort_averages[severity][observable][-1].index(gene) value = cohort_averages[severity][observable][0][idx] bools += value >= 0.01 if bools != 0: good_genes.append(gene) else: good_genes = sorted_genes xlabels = good_genes default_x = np.arange(0, len(good_genes), 1) xs, ys = [], [] for i, severity in enumerate(ordering): x = default_x + width * i xs.append(x) indices = [ cohort_averages[severity][observable][-1].index(gene) for gene in good_genes ] y = [cohort_averages[severity][observable][0][k] for k in indices] ys.append(y) if observable == 'v gene': ax.set_xlim(-0.3, xs[0][-1] + 1.0) if yaxis_upper is not None: ax.set_ylim(0, yaxis_upper) else: ax.set_ylim(0, 0.35) else: ax.set_xlim(-0.3, xs[0][-1] + 1.0) if yaxis_upper is not None: ax.set_ylim(0, yaxis_upper) else: ax.set_ylim(0, 0.55) # Specifiy location of xticks as being in the middle of the grouping of bars. middle = np.mean(np.arange(0, len(cohort_averages))) middle_xticks = default_x + middle * width ax.set_xticks(middle_xticks) ax.set_xticklabels(xlabels, rotation=90, family='Arial') ax.set_ylabel('relative counts', fontname="Arial") # Plot the bars. for i, severity in enumerate(ordering): bar = ax.bar(xs[i], ys[i], width, color=colors[severity], label=severity) for d in cohort_data[severity][observable]: # Plot the full distributions of values to get a better sense # of variation within cohorts. for gidx, rect in enumerate(bar): ax.scatter(xs[i][gidx], d[good_genes[gidx]], marker='.', color=lightercolors[severity], zorder=3, s=markersize, edgecolors='black', linewidths=0.3) format_axes(ax, labelsize=labelsize, ticksize=ticksize, legendsize=legendsize)