Exemple #1
0
def plot_2pcf(ax: matplotlib.axes.Axes,
              dr: np.ndarray,
              xi0: np.ndarray,
              xi1: np.ndarray) -> None:
    """
    Plot the two-point correlation function for the x- and y-components of
    the astrometric residual field as a function of distance between
    points.

    Parameters
    ----------
    ax:
        Matplotlib axis in which to plot
    dr:
        separations at which the 2-point correlation functions were
        calculated
    xi0:
        2-point correlation function of the x-component of the astrometric
        residual field
    xi1:
        2-point correlation function of the y-component of the astrometric
        residual field

    Returns
    -------
    None
    """
    # Plot the two-point correlation functions as a function of distance
    ax.axhline(y=0, ls='--', lw=1, c='gray')
    ax.plot(dr, xi0, marker='o', ms=5, ls='-', lw=1, label=r'$\xi_{xx}$')
    ax.plot(dr, xi1, marker='o', ms=5, ls='-', lw=1, label=r'$\xi_{yy}$')
    ax.legend()
    ax.set_xlabel(r'$\Delta$ [degrees]', fontsize=12)
    ax.set_ylabel(r'$\xi(\Delta)$ [degrees$^2$]', fontsize=12)
Exemple #2
0
def spm_plot(ax: matplotlib.axes.Axes, x: np.ndarray, spm_test: _SPM0Dinference, shaded_kwargs: Dict[str, Any],
             line_kwargs: Dict[str, Any]) -> List[matplotlib.lines.Line2D]:
    """Create SPM plot."""
    ax.axhline(spm_test.zstar, ls='--', color='grey')
    ax.axhline(-spm_test.zstar, ls='--', color='grey')
    ax.fill_between(x, spm_test.zstar, spm_test.z, where=(spm_test.z > spm_test.zstar), **shaded_kwargs)
    ax.fill_between(x, -spm_test.zstar, spm_test.z, where=(spm_test.z < -spm_test.zstar), **shaded_kwargs)
    return ax.plot(x, spm_test.z, **line_kwargs)
Exemple #3
0
def hist2d_scatter(x,
                   y,
                   bg_x,
                   bg_y,
                   axis: matplotlib.axes.Axes,
                   dataset_name: str,
                   normalize=True,
                   marker_color: str = 'k',
                   bins=300,
                   colormap_name: str = 'jet',
                   color_bar=False,
                   hist2dkw={},
                   scatterkw={}):
    """Plots 2D histogram with two parameters (e.g. BxGSM and ByGSM).
    x, y (array_like): Values of the TPAs for the parameter that will be plotted on the x- or y-axis.
                       This data will correspond to the dots in the plot.
    bg_x, bg_y (array_like): Values of the IMF over the period of the dataset.
                             These will form the background (colored tiles) of the plot
    """
    colormap = cm.get_cmap(colormap_name)
    axis.axhline(0, color='grey', zorder=1)
    axis.axvline(0, color='grey', zorder=1)
    omit_index = np.isnan(x) | np.isnan(y)
    x = x[~omit_index]
    y = y[~omit_index]
    bg_omit_index = np.isnan(bg_x) | np.isnan(bg_y)
    bg_x = bg_x[~bg_omit_index]
    bg_y = bg_y[~bg_omit_index]
    counts, xedges, yedges, im = axis.hist2d(bg_x,
                                             bg_y,
                                             bins=bins,
                                             cmap=colormap,
                                             density=normalize,
                                             zorder=0,
                                             **hist2dkw)

    if color_bar:
        cbar = plt.colorbar(im, ax=axis)
        cbar.set_label('IMF probability distribution',
                       rotation=270,
                       labelpad=10)

    scatter = axis.scatter(x,
                           y,
                           s=30,
                           marker='P',
                           edgecolors='w',
                           linewidth=0.5,
                           label=dataset_name,
                           c=marker_color[~omit_index] if isinstance(
                               marker_color, np.ndarray) else marker_color,
                           zorder=2,
                           **scatterkw)

    axis.set_facecolor(colormap(0))
    axis.legend(loc='upper left')
    return scatter, counts, xedges, yedges, im
Exemple #4
0
def customize_ax(ax: matplotlib.axes.Axes,
                 title=None,
                 xlabel=None,
                 ylabel=None,
                 xlim=None,
                 ylim=None,
                 invert_yaxis=False,
                 xticks_maj_freq=None,
                 xticks_min_freq=None,
                 yticks_maj_freq=None,
                 yticks_min_freq=None,
                 with_hline=False,
                 hline_height=None,
                 hline_color='r',
                 hline_style='--'):
    """
    : ax (matplotlib.axes.Axes): plot to customize.
    : Use to customize a plot with labels, ticks, etc.
    """
    if xlabel is not None:
        ax.set_xlabel(xlabel)
    if ylabel is not None:
        ax.set_ylabel(ylabel)

    if xlim is not None:
        ax.set_xlim(xlim)
    if ylim is not None:
        ax.set_ylim(ylim)

    if invert_yaxis:
        ax.invert_yaxis()

    if title is not None:
        ax.set_title(title)

    if xticks_maj_freq is not None:
        ax.xaxis.set_major_locator(ticker.MultipleLocator(xticks_maj_freq))

    if xticks_min_freq is not None:
        ax.xaxis.set_minor_locator(ticker.MultipleLocator(xticks_min_freq))

    if yticks_maj_freq is not None:
        ax.yaxis.set_major_locator(ticker.MultipleLocator(yticks_maj_freq))

    if yticks_min_freq is not None:
        ax.yaxis.set_minor_locator(ticker.MultipleLocator(yticks_min_freq))

    if with_hline:
        if hline_height is None:
            ylim = plt.ylim()
            hline_height = max(ylim) / 2
        ax.axhline(y=hline_height, color=hline_color, linestyle=hline_style)
Exemple #5
0
def plot_step_analyzer(axes: matplotlib.axes.Axes, result: dict, title: str,
                       legends: list, colorset: int):
    colors = [
        ('red', 'green', 'blue'),  # TODO: add more colors
        ('tomato', 'lightgreen', 'steelblue'),
    ]
    c = colors[colorset]

    n = len(result['states'])

    for i in range(n):
        if legends:
            axes.plot(result['times'],
                      result['states'][i],
                      color=c[i],
                      label=legends[i])
        else:
            axes.plot(result['times'], result['states'][i], color=c[i])

        if result['references'][i] != 0.0:
            axes.axhline(result['references'][i], linestyle='--', color=c[i])
            axes.axhline(result['references'][i] - result['thresholds'][i],
                         linestyle='-.',
                         color=c[i])
            axes.axhline(result['references'][i] + result['thresholds'][i],
                         linestyle='-.',
                         color=c[i])
            axes.axhline(result['references'][i] + result['overshoots'][i],
                         linestyle=':',
                         color=c[i])
        if result['risetimes'][i] > 0.0:
            axes.axvline(result['risetimes'][i], linestyle='--', color=c[i])
        if result['settletimes'][i] > 0.0:
            axes.axvline(result['settletimes'][i], linestyle='-.', color=c[i])

    if legends:
        axes.legend()

    if title:
        axes.set_title(title)

    axes.set_xlim(result['times'][0], result['times'][-1])
    axes.figure.tight_layout()
Exemple #6
0
    def plot(self, ax: matplotlib.axes.Axes):
        # individual points
        ax.scatter(self.mean, self.diff, s=20, alpha=0.6, color=self.color_points,
                   **self.point_kws)

        # mean difference and SD lines
        ax.axhline(self.mean_diff, color=self.color_mean, linestyle='-')
        ax.axhline(self.mean_diff + self.loa_sd, color=self.color_loa, linestyle='--')
        ax.axhline(self.mean_diff - self.loa_sd, color=self.color_loa, linestyle='--')

        if self.reference:
            ax.axhline(0, color='grey', linestyle='-', alpha=0.4)

        # confidence intervals (if requested)
        if self.CI is not None:
            ax.axhspan(self.CI_mean[0],  self.CI_mean[1], color=self.color_mean, alpha=0.2)
            ax.axhspan(self.CI_upper[0], self.CI_upper[1], color=self.color_loa, alpha=0.2)
            ax.axhspan(self.CI_lower[0], self.CI_lower[1], color=self.color_loa, alpha=0.2)

        # text in graph
        trans: matplotlib.transform = transforms.blended_transform_factory(
            ax.transAxes, ax.transData)
        offset: float = (((self.loa * self.sd_diff) * 2) / 100) * 1.2
        ax.text(0.98, self.mean_diff + offset, 'Mean', ha="right", va="bottom", transform=trans)
        ax.text(0.98, self.mean_diff - offset, f'{self.mean_diff:.2f}', ha="right", va="top", transform=trans)
        ax.text(0.98, self.mean_diff + self.loa_sd + offset,
                f'+{self.loa:.2f} SD', ha="right", va="bottom", transform=trans)
        ax.text(0.98, self.mean_diff + self.loa_sd - offset,
                f'{self.mean_diff + self.loa_sd:.2f}', ha="right", va="top", transform=trans)
        ax.text(0.98, self.mean_diff - self.loa_sd - offset,
                f'-{self.loa:.2f} SD', ha="right", va="top", transform=trans)
        ax.text(0.98, self.mean_diff - self.loa_sd + offset,
                f'{self.mean_diff - self.loa_sd:.2f}', ha="right", va="bottom", transform=trans)

        # transform graphs
        ax.spines['right'].set_visible(False)
        ax.spines['top'].set_visible(False)

        # set X and Y limits
        if self.xlim is not None:
            ax.set_xlim(self.xlim[0], self.xlim[1])
        if self.ylim is not None:
            ax.set_ylim(self.ylim[0], self.ylim[1])

        # graph labels
        ax.set_ylabel(self.y_title)
        ax.set_xlabel(self.x_title)
        if self.graph_title is not None:
            ax.set_title(self.graph_title)
Exemple #7
0
def annotate_confidence_plot(ax: mpl.axes.Axes):
    """Adds annotations to indicate over/underconfidence."""
    line = ax.axhline(1.0, linestyle="--", color="k", zorder=1)
    disp_coords = line.get_transform().transform([0, line.get_ydata()[0]])
    line_y_ax = ax.transAxes.inverted().transform(disp_coords)[1]
    offset = 0.02
    shared_kws = {
        "color": "gray",
        "zorder": 2,
        "transform": ax.transAxes,
        "fontsize": 4
    }
    ax.text(1.0 - offset,
            line_y_ax + offset,
            "overconfident",
            va="bottom",
            ha="right",
            **shared_kws)
    ax.text(1.0 - offset,
            line_y_ax - offset,
            "underconfident",
            va="top",
            ha="right",
            **shared_kws)
Exemple #8
0
def draw_horizontal_line(ax: mpl.axes.Axes, y: float, linestyle: str,
                         color: Optional[str]) -> mpl.lines.Line2D:
    '''Draw horizontal line on a subplot'''
    return ax.axhline(y=y, linestyle=linestyle, color=color)
Exemple #9
0
 def draw(self, ax: matplotlib.axes.Axes):
     xmin = (1 - self.width) / 2
     xmax = 1 - xmin
     ax.axhline(self.position, color=self.color, xmin=xmin, xmax=xmax)
Exemple #10
0
    def plot(
        self,
        x_label: str = "Mean of methods",
        y_label: str = "Difference between methods",
        graph_title: str = None,
        reference: bool = False,
        xlim: Tuple = None,
        ylim: Tuple = None,
        color_mean: str = "#008bff",
        color_loa: str = "#FF7000",
        color_points: str = "#000000",
        point_kws: Dict = None,
        ci_alpha: float = 0.2,
        loa_linestyle: str = "--",
        ax: matplotlib.axes.Axes = None,
    ):
        """Provide a method comparison using Bland-Altman plotting.
        This is an Axis-level function which will draw the Bland-Altman plot
        onto the current active Axis object unless ``ax`` is provided.
        Parameters
        ----------
        x_label : str, optional
            The label which is added to the X-axis. If None is provided, a standard
            label will be added.
        y_label : str, optional
            The label which is added to the Y-axis. If None is provided, a standard
            label will be added.
        graph_title : str, optional
            Title of the Bland-Altman plot.
            If None is provided, no title will be plotted.
        reference : bool, optional
            If True, a grey reference line at y=0 will be plotted in the Bland-Altman.
        xlim : list, optional
            Minimum and maximum limits for X-axis. Should be provided as list or tuple.
            If not set, matplotlib will decide its own bounds.
        ylim : list, optional
            Minimum and maximum limits for Y-axis. Should be provided as list or tuple.
            If not set, matplotlib will decide its own bounds.
        color_mean : str, optional
            Color of the mean difference line that will be plotted.
        color_loa : str, optional
            Color of the limit of agreement lines that will be plotted.
        color_points : str, optional
            Color of the individual differences that will be plotted.
        point_kws : dict of key, value mappings, optional
            Additional keyword arguments for `plt.scatter`.
        ci_alpha: float, optional
            Alpha value of the confidence interval.
        loa_linestyle: str, optional
            Linestyle of the limit of agreement lines.
        ax : matplotlib Axes, optional
            Axes in which to draw the plot, otherwise use the currently-active
            Axes.

        Returns
        -------
        ax : matplotlib Axes
            Axes object with the Bland-Altman plot.
        """

        ax = ax or plt.gca()

        pkws = self.DEFAULT_POINTS_KWS.copy()
        pkws.update(point_kws or {})

        # Get parameters
        mean, mean_CI = self.result["mean"], self.result["mean_CI"]
        loa_upper, loa_upper_CI = self.result["loa_upper"], self.result[
            "loa_upper_CI"]
        loa_lower, loa_lower_CI = self.result["loa_lower"], self.result[
            "loa_lower_CI"]
        sd_diff = self.result["sd_diff"]

        # individual points
        ax.scatter(self.mean, self.diff, **pkws)

        # mean difference and SD lines
        ax.axhline(mean, color=color_mean, linestyle=loa_linestyle)
        ax.axhline(loa_upper, color=color_loa, linestyle=loa_linestyle)
        ax.axhline(loa_lower, color=color_loa, linestyle=loa_linestyle)

        if reference:
            ax.axhline(0, color="grey", linestyle="-", alpha=0.4)

        # confidence intervals (if requested)
        if self.CI is not None:
            ax.axhspan(*mean_CI, color=color_mean, alpha=ci_alpha)
            ax.axhspan(*loa_upper_CI, color=color_loa, alpha=ci_alpha)
            ax.axhspan(*loa_lower_CI, color=color_loa, alpha=ci_alpha)

        # text in graph
        trans: matplotlib.transform = transforms.blended_transform_factory(
            ax.transAxes, ax.transData)
        offset: float = (((self.loa * sd_diff) * 2) / 100) * 1.2
        ax.text(
            0.98,
            mean + offset,
            "Mean",
            ha="right",
            va="bottom",
            transform=trans,
        )
        ax.text(
            0.98,
            mean - offset,
            f"{mean:.2f}",
            ha="right",
            va="top",
            transform=trans,
        )
        ax.text(
            0.98,
            loa_upper + offset,
            f"+{self.loa:.2f} SD",
            ha="right",
            va="bottom",
            transform=trans,
        )
        ax.text(
            0.98,
            loa_upper - offset,
            f"{loa_upper:.2f}",
            ha="right",
            va="top",
            transform=trans,
        )
        ax.text(
            0.98,
            loa_lower - offset,
            f"-{self.loa:.2f} SD",
            ha="right",
            va="top",
            transform=trans,
        )
        ax.text(
            0.98,
            loa_lower + offset,
            f"{loa_lower:.2f}",
            ha="right",
            va="bottom",
            transform=trans,
        )

        # transform graphs
        ax.spines["right"].set_visible(False)
        ax.spines["top"].set_visible(False)

        # set X and Y limits
        if xlim is not None:
            ax.set_xlim(xlim[0], xlim[1])
        if ylim is not None:
            ax.set_ylim(ylim[0], ylim[1])

        # graph labels
        ax.set(xlabel=x_label, ylabel=y_label, title=graph_title)

        return ax