Ejemplo n.º 1
0
def plot_openness_by_hour(data: list, period: dict, ax: Axes):
    """
    Plots the openness by hour from the raw data.

    :param data: Raw data
    :param period: Period over which to average the openness
    :param ax: Axes object in which to put the plot
    :return: None
    """
    num_hrs = 24

    # Get data
    hour_bins = get_openness_by_hour(data, period)

    # Plot bar chart
    ax.bar(range(num_hrs + 1), hour_bins)

    # Decorate the axes
    ax.yaxis.grid(True, which="both", linestyle="-.")
    ax.set_xlim(1, num_hrs)
    ax.set_xticks(range(num_hrs + 1))
    ax.set_xticklabels([f"{t:02d}" for t in ax.get_xticks()])
    ax.set_yticklabels([f"{o * 100:.1f}{percent()}" for o in ax.get_yticks()])
    ax.set_ylabel("Andel åpen")
    ax.set_xlabel("Tid på døgnet")
Ejemplo n.º 2
0
 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
Ejemplo n.º 3
0
def plotPRITransformVal(ax: axes,
                        bins: np.array,
                        vals: np.array,
                        title: str = None,
                        plot_ylabel: bool = False) -> None:
    ax.plot(bins, vals, linewidth=2)
    ax.set_title(title, fontsize=10)
    ax.set_xlabel('pri[us]', fontsize=8, loc='right')
    if plot_ylabel:
        ax.set_ylabel('interval values', fontsize=10)
Ejemplo n.º 4
0
def _plotIDStrip(ax: matplotlib.axes, id_array: np.ndarray, label: str,
                 x_extents: List[float]) -> None:
    '''
    Plot a strip above the data sequence image that represents class labels at each time.
    '''

    id_array = np.reshape(id_array, (1, len(id_array)))
    ax.imshow(id_array, aspect="auto", interpolation="none", extent=x_extents + [0, 1])
    ax.set_ylabel(label)
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_ticks([])
Ejemplo n.º 5
0
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)
Ejemplo n.º 6
0
def make_stats_plot(cohort_averages: dict,
                    observable: str,
                    in_ax: matplotlib.axes,
                    geo: bool = False,
                    labelsize: int = 12,
                    ticksize: int = 10,
                    legendsize: int = 8,
                    box=False) -> None:
    """Plots an observable for all cohorts on a single axes object.

    Parameters
    ----------
    cohort_averages : dict
        Dictionary of averages and variations within a cohort for all severities.
    observable : str
        The quantity which is going to be plotted.
    in_ax : matplotlib.axes
        The axes on which values are going to be plotted.
    geo: bool, optional
        Specifies geometric or arithmetic averaging.
    labelsize : int, optional
        Size of axes labels.
    ticksize : int, optional
        Size of tick labels.
    legendsize : int, optional
        Specifies font size of strings in legend.
    box : bool, optional
        Specifies whether or not a box plot has been plotted.

    Returns
    -------
    None
    """

    cohort_plot(cohort_averages, observable, in_ax=in_ax, geo=geo)

    #  Name of xlabel for each observable.
    xlabels = {
        'cdr3 length': 'HCDR3 length [aa]',
        'vd ins': 'VD insertions [nt]',
        'vd del': 'VD deletions [nt]',
        'dj ins': 'DJ insertions [nt]',
        'dj del': 'DJ deletions [nt]'
    }
    in_ax.set_xlabel(xlabels[observable], fontname="Arial")
    in_ax.set_ylabel("relative counts", family="Arial")
    format_axes(in_ax,
                labelsize=labelsize,
                ticksize=ticksize,
                legendsize=legendsize,
                box=False)
Ejemplo n.º 7
0
def plot_openness_by_weekday_by_semester(period: dict, ax: Axes):
    """
    Plot openness by semester.

    :param period: Period over which to average the openness
    :param ax: Axes object in which to put the plot
    :return: None
    """
    # Configuration
    num_weekdays = 5
    init_year = 2015
    init_semester = "Vår"

    # Get data for plot
    dataseries = get_openness_by_weekday_by_semester(period)
    num_series = len(dataseries)
    bar_width = 1 / (num_series + 1)

    # Create plot
    cur_year = init_year
    cur_semester = init_semester
    legend = []
    for semester_index, week_bins in enumerate(dataseries):
        # Add bars
        ax.bar(
            [
                weekday_index + semester_index * bar_width
                for weekday_index in range(num_weekdays)
            ],
            height=week_bins[:num_weekdays],
            width=bar_width,
        )

        # Add to legend
        legend.append(f"{cur_semester} {cur_year}")

        # Update semester and year for next bars
        if cur_semester == "Høst":
            cur_semester = "Vår"
            cur_year += 1
        else:
            cur_semester = "Høst"

    # Place legend and labels
    ax.legend(legend, loc="lower right")
    ax.set_xticklabels(("", "Mandag", "Tirsdag", "Onsdag", "Torsdag", "Fredag"))
    ax.set_yticklabels(
        [f"{openness * 100:.1f}{percent()}" for openness in ax.get_yticks()]
    )
    ax.set_ylabel("Andel åpen")
Ejemplo n.º 8
0
def plot_openness(data: list, period: dict, ax: Axes):
    """
    Plots the openness from the raw data.

    :param data: Raw data
    :param period: Period over which to average the openness
    :param ax: Axes object in which to put the plot
    :return: None
    """
    # Get data
    datetimes, openness = get_openness(data, period)

    # Make filled line plot
    ax.fill_between(datetimes, openness)

    # Decorate axes
    ax.xaxis.set_major_locator(MonthLocator((1, 4, 7, 10), bymonthday=1))
    ax.xaxis.set_major_formatter(DateFormatter("%b '%y"))
    ax.set_yticklabels([f"{o * 100:.0f}{percent()}" for o in ax.get_yticks()])
    ax.set_ylabel("Andel åpen")
    ax.grid(linestyle="-.")
Ejemplo n.º 9
0
def plot_openness_by_weekday(data: list, period: dict, ax: Axes):
    """
    Plot the openness by weekday from the raw data.

    :param data: Raw data
    :param period: Period over which to average the openness
    :param ax: Axes object in which to put the plot
    :return: None
    """
    week_bins = get_openness_by_weekday(data, period)
    weekday_avg = sum(week_bins[0:5]) / 5
    weekend_avg = sum(week_bins[5:7]) / 2

    # Plot bar
    ax.bar(range(7), week_bins)

    # Plot averages
    ax.text(
        2,
        weekday_avg * 1.05,
        f"Gjennomsnitt ukedager: {weekday_avg * 100:.0f}{percent()}",
    )
    ax.text(
        4.5,
        weekend_avg * 1.1,
        f"Gjennomsnitt helgedager: {weekend_avg * 100:.0f}{percent()}",
    )
    ax.plot((0, 5 - 1), (weekday_avg, weekday_avg), "k--")
    ax.plot((5, 7 - 1), (weekend_avg, weekend_avg), "k--")

    # Decorate axes
    ax.set_xticklabels(
        ("", "Mandag", "Tirsdag", "Onsdag", "Torsdag", "Fredag", "Lørdag", "Søndag")
    )
    ax.set_yticklabels(
        [f"{openness * 100:.1f}{percent()}" for openness in ax.get_yticks()]
    )
    ax.set_ylabel("Andel åpen")
Ejemplo n.º 10
0
def plot_visit_durations(data: list, ax: Axes):
    """
    Plot the visit durations from the raw data.

    :param data: Raw data
    :param ax: Axes object in which to put the plot
    :return: None
    """
    # Histogram options
    min_visit_s = 30
    max_visit_s = 60 * 60 * 3
    nbins = 150

    # Regression line options
    fit_start = 6
    fit_stop = 144

    # Create histogram
    durations = get_visit_durations(data)
    n, bins, _ = ax.hist(durations, bins=linspace(min_visit_s, max_visit_s, nbins))

    # Create regression line
    bin_width = (bins[fit_stop - 1] - bins[fit_start]) / (fit_start - fit_stop)
    lin_fitting_bins = [b + bin_width / 2 for b in bins[fit_start:fit_stop]]
    lin_fitting_n = n[fit_start:fit_stop]
    [a, b] = polyfit(lin_fitting_bins, log(lin_fitting_n), 1, w=sqrt(lin_fitting_n))
    fitted_n = [exp(b + a * t) for t in lin_fitting_bins]
    regression_line_opts = {"linestyle": "--", "color": "black", "linewidth": 2}
    regression_label_text = "y={:.0f}exp({:.6f}*t)".format(exp(b), a)
    regression_label_coords = (max_visit_s * 0.6, max(n) * 0.5)
    ax.plot(lin_fitting_bins, fitted_n, **regression_line_opts)
    ax.text(*regression_label_coords, regression_label_text)

    # Label axes
    ax.set_xlabel("Varighet for visitt (s)")
    ax.set_ylabel("Andel visitter (vilkårlig)")
    ax.set_yscale("log")
Ejemplo n.º 11
0
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)
Ejemplo n.º 12
0
def plot_histogram(data: List[np.float64], bins: int, axes: matplotlib.axes):
    axes.hist(x=data, bins=bins)
    axes.set_title('KDE plot')
    axes.set_xlabel('x')
    axes.set_ylabel('f')
Ejemplo n.º 13
0
def plot_kdeplot(data: List[np.float64], axes: matplotlib.axes):
    sns.kdeplot(data=data, kernel='gau', bw='scott', ax=axes)
    axes.set_title('KDE plot')
    axes.set_xlabel('x')
    axes.set_ylabel('f')