Ejemplo n.º 1
0
def _plot_warning_message(ax: plt.Axes, label: str, keys: List[str]) -> None:
    text = "Unable to plot {}.\nRelevant information not available in history object.\nNeed history keys: {}".format(
        label, ", ".join(keys))
    ax.text(0.5, 0.5, text, ha="center", va="center")
    ax.set_xlim(0, 1)
    ax.set_ylim(0, 1)
    ax.axis("off")
Ejemplo n.º 2
0
    def __init__(self,
                 ax: plt.Axes = None,
                 set_ax=False,
                 img_path: str = None,
                 **kwargs):
        """
            Renders an image of the hairpin maze on a matplotlib axis
        """
        ax = ax or plt.gca()

        image = self.get_image(img_path)

        ax.imshow(
            image,
            extent=[self.x_0, self.x_1, self.y_0, self.y_1],
            origin="lower",
            zorder=-100,
            **kwargs,
        )

        if set_ax:
            ax.set(
                xlim=[self.x_0, self.x_1],
                ylim=[self.y_0, self.y_1],
                xlabel="cm",
                ylabel="cm",
                xticks=[self.x_0, self.x_1],
                yticks=[self.y_0, self.y_1],
            )
        clean_axes(ax.figure)
        ax.axis("equal")
Ejemplo n.º 3
0
def show_image(img:PIL.Image, ax:plt.Axes=None, figsize:tuple=(3,3), hide_axis:bool=True, cmap:str='binary',
                alpha:float=None, **kwargs)->plt.Axes:
    "Display `Image` in notebook."
    if ax is None: fig,ax = plt.subplots(figsize=figsize)
    ax.imshow(pil2np(img), cmap=cmap, alpha=alpha, **kwargs)
    if hide_axis: ax.axis('off')
    return ax
Ejemplo n.º 4
0
def show_image(img: NiiImage,
               ax: plt.Axes = None,
               figsize: tuple = (3, 3),
               hide_axis: bool = True,
               cmap: str = 'gray',
               cmap_y: str = 'jet',
               alpha: float = 0.5,
               y=None,
               anatomical_plane: str = None,
               title: str = None,
               **kwargs) -> plt.Axes:
    "Display `Image` in notebook."
    if ax is None: fig, ax = plt.subplots(figsize=figsize)
    show_slice_img(img=img,
                   ax=ax,
                   cmap=cmap,
                   anatomical_plane=anatomical_plane,
                   title=title,
                   **kwargs)

    if y is not None:
        show_slice_img(img=y,
                       ax=ax,
                       cmap=cmap_y,
                       alpha=alpha,
                       anatomical_plane=anatomical_plane,
                       title=title,
                       **kwargs)  #TODO change cmap

    if hide_axis: ax.axis('off')
    return ax
Ejemplo n.º 5
0
def manual_auto_scatter(manual, auto, title=None, ax: plt.Axes = None):
    if not ax:
        _, ax = plt.subplots()

    if title:
        ax.set_title(title)

    ax.set_xlabel("manual")
    ax.set_ylabel("auto")
    ax.axis("equal")

    ax.scatter(manual, auto)

    coeffs, residuals, rank, singular_values, rcond = np.polyfit(manual,
                                                                 auto,
                                                                 1,
                                                                 full=True)
    x = np.unique(manual)
    y = np.poly1d(coeffs)(x)

    f = np.poly1d(coeffs)(manual)
    ss_tot = np.sum((np.array(auto) - np.mean(y))**2)
    ss_res = np.sum((np.array(auto) - f)**2)
    r2 = 1 - (ss_res / ss_tot)

    ax.plot(
        x,
        y,
        label=r"linear best fit \newline $y = ({})x {}$ \newline $R^2 = {:.3f}$"
        .format(latex_float(coeffs[0]), ensure_sign(latex_float(coeffs[1])),
                r2),
    )

    ax.legend()
Ejemplo n.º 6
0
    def __setup_subplot__(self, rhythm_loop: RhythmLoop, axes: plt.Axes, **kw):
        box_notation_grid_info = plot_box_notation_grid(
            axes, rhythm_loop, self.unit, self.position, self.text_box_width,
            self.line_width, self.line_color)

        container = box_notation_grid_info['container']  # type: Rectangle2D

        # get viewport dimensions
        x_padding = (self.rel_pad_x *
                     box_notation_grid_info['container'].width) / 2
        x_bounds = [
            container.x_bounds[0] - x_padding,
            container.x_bounds[1] + x_padding
        ]
        y_padding = (abs(x_bounds[0] - x_bounds[1]) - container.height) / 2
        y_bounds = [
            container.y_bounds[0] - y_padding,
            container.y_bounds[1] + y_padding
        ]

        # setup viewport
        axes.axis("equal")  # equal axis for perfectly "squared" squares.. :)
        axes.set_xlim(*x_bounds)
        axes.set_ylim(*reversed(
            y_bounds))  # reversed to have (0, 0) in upper-left position

        return {
            **box_notation_grid_info, 'viewport':
            Rectangle2D(x=x_bounds[0],
                        y=y_bounds[0],
                        width=abs(x_bounds[0] - x_bounds[1]),
                        height=abs(y_bounds[0] - y_bounds[1]))
        }
Ejemplo n.º 7
0
    def plot_analyzed_subimage(self, subimage: str='wobble', ax: plt.Axes=None, show: bool=True):
        """Plot a subimage of the starshot analysis. Current options are the zoomed out image and the zoomed in image.

        Parameters
        ----------
        subimage : str
            If 'wobble', will show a zoomed in plot of the wobble circle.
            Any other string will show the zoomed out plot.
        ax : None, matplotlib Axes
            If None (default), will create a new figure to plot on, otherwise plot to the passed axes.
        """
        if ax is None:
            fig, ax = plt.subplots()
        # show analyzed image
        ax.imshow(self.image.array, cmap=get_dicom_cmap())
        self.lines.plot(ax)
        self.wobble.plot2axes(ax, edgecolor='green')
        self.circle_profile.plot2axes(ax, edgecolor='green')
        ax.autoscale(tight=True)
        ax.axis('off')

        # zoom in if wobble plot
        if subimage == 'wobble':
            xlims = [self.wobble.center.x + self.wobble.diameter, self.wobble.center.x - self.wobble.diameter]
            ylims = [self.wobble.center.y + self.wobble.diameter, self.wobble.center.y - self.wobble.diameter]
            ax.set_xlim(xlims)
            ax.set_ylim(ylims)
            ax.axis('on')

        if show:
            plt.show()
Ejemplo n.º 8
0
def imshow(img: np.ndarray, axis: str = 'on', ax: plt.Axes = None, add_colorbar: bool = True,
           **kwargs) -> (plt.Figure, plt.Axes):
    """Imshow wrapper to plot images in various image spaces. Constructs a figure object under the hood.
    Arguments
    ---------
        img: the input image
        axis: whether to display the axis with ticks and everything by default
        ax: if None, create new plt Axes, otherwise take this one for plotting
        kwargs: those will be forwarded into the setup_plt_figure function
    Returns
    -------
        fig, ax: a tuple of a matplotlib Figure and Axes object
    """

    if ax is None:
        fig, ax = setup_plt_figure(**kwargs)
    else:
        fig = ax.get_figure()
        ax.set_title(kwargs.get('title', ''))
    ax.axis(axis)
    imshow_kwargs = {'cmap': kwargs['cmap'] if 'cmap' in kwargs else 'hot'}
    for key in ['vmin', 'vmax']:
        if key in kwargs:
            imshow_kwargs[key] = kwargs.get(key)
    im = ax.imshow(img, **imshow_kwargs)
    if add_colorbar:
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", size="2%", pad=0.05)
        plt.colorbar(im, cax=cax)
    font = {'family': 'normal',
            'weight': 'bold',
            'size': 12}
    matplotlib.rc('font', **font)
    return fig, ax
Ejemplo n.º 9
0
def show_image(img: Image,
               ax: plt.Axes = None,
               figsize: tuple = (3, 3),
               hide_axis: bool = True) -> plt.Axes:
    """Show image using Matplotlib

    Parameters
    ----------
    img
        Image object
    ax
        Axes to use for showing image (default = None, will be created)
    figsize
        Figure size to use (default = (3, 3))
    hide_axis
        Flag to decide to show axis or not (default = True, hide it)

    Returns
    -------
    Axes with plotted image
    """
    if ax is None:
        fig, ax = plt.subplots(figsize=figsize)
    ax.imshow(img.data)
    if hide_axis:
        ax.axis('off')
    return ax
Ejemplo n.º 10
0
def show_image(img:Tensor, ax:plt.Axes=None, figsize:tuple=(3,3), hide_axis:bool=True,
               title:Optional[str]=None, cmap:str='binary', alpha:Optional[float]=None)->plt.Axes:
    "plot tensor `img` using matplotlib axis `ax`.  `figsize`,`axis`,`title`,`cmap` and `alpha` pass to `ax.imshow`"
    if ax is None: fig,ax = plt.subplots(figsize=figsize)
    ax.imshow(image2np(img), cmap=cmap, alpha=alpha)
    if hide_axis: ax.axis('off')
    if title: ax.set_title(title)
    return ax
Ejemplo n.º 11
0
def plot_table_from_df(df: pd.DataFrame, colors: List[str], axis: plt.Axes):
    """Plot table from dataframe in mmatplotlib axis."""
    cell_text = []
    for row in range(len(df)):
        cell_text.append(df.iloc[row])
    cell_colors = [colors for _ in range(len(df.columns))]
    head_colors = ["#FF0000" for _ in range(len(df.columns))]
    axis.table(cellText=cell_text, colLabels=df.columns, cellColours=cell_colors, colColours=head_colors, loc='center')
    axis.axis('off')
Ejemplo n.º 12
0
def draw_segmentation(
        img: np.ndarray,
        mask: np.ndarray,
        idx_name_dict: Dict[int, str],
        colors: List = None,
        title: str = '',
        ax: plt.Axes = None,
        figsize: Tuple[int, int] = (16, 8),
):
    if colors is None:
        colors = generate_colormap(len(idx_name_dict) + 1)

    if ax is None:
        _, ax = plt.subplots(figsize=figsize)

    width, height = img.size
    ax.set_ylim(height + 10, -10)
    ax.set_xlim(-10, width + 10)
    ax.axis('off')
    ax.set_title(title)

    out_image = np.array(img).astype(np.uint8)

    for cat in np.unique(mask)[1:]:
        mask_cat = (mask == cat)
        cat_name = idx_name_dict[cat]
        color = colors[cat]

        # draw text in the center (defined by median) when box is not drawn
        # median is less sensitive to outliers.
        text_pos = np.median(mask_cat.nonzero(), axis=1)[::-1] - 20
        # horiz_align = "left"

        lighter_color = change_color_brightness(color, brightness_factor=0.7)
        font_size = 10
        draw_text(ax,
                  cat_name,
                  text_pos,
                  font_size,
                  horizontal_alignment='left')

        padded_mask = np.zeros((mask_cat.shape[0] + 2, mask_cat.shape[1] + 2),
                               dtype=np.uint8)
        padded_mask[1:-1, 1:-1] = mask_cat
        contours = measure.find_contours(padded_mask, 0.5)
        for verts in contours:
            verts = np.fliplr(verts) - 1
            p = Polygon(
                verts,
                facecolor=color,
                edgecolor=lighter_color,    # 'black',
                fill=True,
                alpha=.5)
            ax.add_patch(p)
    ax.imshow(out_image)
    return ax
Ejemplo n.º 13
0
def show_image(img, ax: plt.Axes = None, figsize: tuple = (3, 3), hide_axis: bool = True, cmap: str = 'viridis',
               alpha: float = None, **kwargs) -> plt.Axes:
    """Display `Image` in notebook."""
    if ax is None:
        fig, ax = plt.subplots(figsize=figsize)
    xtr = dict(cmap=cmap, alpha=alpha, **kwargs)
    ax.imshow(image2np(img.data), **xtr) if (hasattr(img, 'data')) else ax.imshow(img, **xtr)
    if hide_axis:
        ax.axis('off')
    return ax
Ejemplo n.º 14
0
def measureTau(abf: pyabf.ABF,
               sweep: int,
               epoch: int = 3,
               percentile: float = .05,
               ax: plt.Axes = None):

    abf.setSweep(sweep)

    # use epoch table to determine puff times
    puffTimeStart = abf.sweepEpochs.p1s[epoch] / abf.sampleRate
    puffTimeEnd = abf.sweepEpochs.p2s[epoch] / abf.sampleRate

    # calculate baseline level
    baselineStart = puffTimeStart - .1
    baselineEnd = puffTimeStart
    baselineMean = getMean(abf, baselineStart, baselineEnd)

    # find antipeak
    antipeakIndex = getAntiPeakIndex(abf.sweepY, abf.sampleRate, puffTimeStart,
                                     puffTimeStart + .5)
    antipeakLevel = abf.sweepY[antipeakIndex]

    # find portion of curve to fit
    curveIndex1, curveIndex2 = getCurveIndexes(abf.sweepY, antipeakIndex,
                                               baselineMean, percentile)
    curveYs = -abf.sweepY[curveIndex1:curveIndex2]
    curveXs = np.arange(len(curveYs)) / abf.sampleRate

    try:
        p0 = (500, 15, 0)  # start with values near those we expect
        params, cv = scipy.optimize.curve_fit(monoExp, curveXs, curveYs, p0)
    except:
        print(f"FIT FAILED (sweep {sweep})")
        return None
    m, t, b = params
    curveYsIdeal = monoExp(curveXs, m, t, b)
    tauMS = 1000 / t
    if (tauMS < 0):
        return None

    if ax:
        yPad = abs(antipeakLevel - baselineMean) * .1
        ax.plot(abf.sweepX, abf.sweepY, alpha=.5)
        ax.grid(alpha=.5, ls='--')
        ax.axhline(baselineMean, ls='--', color='k')
        ax.plot(abf.sweepX[curveIndex1:curveIndex2], -curveYsIdeal, color='k')
        ax.set(title=f"first sweep tau = {tauMS:.02f} ms")
        ax.axis([
            baselineStart - .1, baselineStart + 1, antipeakLevel - yPad,
            baselineMean + yPad
        ])
        ax.axvspan(puffTimeEnd, puffTimeEnd + .5, color='g', alpha=.1)
        ax.axvspan(puffTimeEnd + .5, puffTimeEnd + .6, color='m', alpha=.1)

    return tauMS
Ejemplo n.º 15
0
def plot_text(axes: plt.Axes, text: str):
    """Plot text on an axes

    Args:
        axes (plt.Axes): an axes object
        text (str): the text
    """

    axes.axis('off')
    axes.grid('off')
    axes.text(x=0, y=0, s=text, horizontalalignment='left', fontdict=FONT)
Ejemplo n.º 16
0
 def make_plot(
         self,
         axes: pyplot.Axes = None,
         vmin: float = None,
         vmax: float = None,
         show: bool = False,
         title: str = None,
         # figsize=rcParams["figure.figsize"],
         extent: (float, float, float, float) = None,
         cbar_label: str = None,
         **kwargs
 ):
     if vmin is None:
         vmin = np.min(self.values)
     if vmax is None:
         vmax = np.max(self.values)
     kwargs.update(**fig.get_topobathy_kwargs(self.values, vmin, vmax))
     kwargs.pop('col_val')
     levels = kwargs.pop('levels')
     if vmin != vmax:
         self.tricontourf(
             axes=axes,
             levels=levels,
             vmin=vmin,
             vmax=vmax,
             **kwargs
         )
     else:
         self.tripcolor(axes=axes, **kwargs)
     self.quadface(axes=axes, **kwargs)
     axes.axis('scaled')
     if extent is not None:
         axes.axis(extent)
     if title is not None:
         axes.set_title(title)
     mappable = ScalarMappable(cmap=kwargs['cmap'])
     mappable.set_array([])
     mappable.set_clim(vmin, vmax)
     divider = make_axes_locatable(axes)
     cax = divider.append_axes("bottom", size="2%", pad=0.5)
     cbar = plt.colorbar(
         mappable,
         cax=cax,
         orientation='horizontal'
     )
     cbar.set_ticks([vmin, vmax])
     cbar.set_ticklabels([np.around(vmin, 2), np.around(vmax, 2)])
     if cbar_label is not None:
         cbar.set_label(cbar_label)
     if show:
         pyplot.show()
     return axes
Ejemplo n.º 17
0
 def show(self, ax: plt.Axes = None, figsize: tuple = (3, 3), title: Optional[str] = None, hide_axis: bool = True,
          annotate=False, plot_lines=True, colors='r', **kwargs):
     if ax is None:
         _, ax = plt.subplots(figsize=figsize)
     data = self.data
     pnt = data[:, :2]
     visible = data[:, 2]
     pnt = scale_flow(FlowField(self.size, pnt), to_unit=False).flow.flip(1)
     lip_utils.plot_joint(ax, pnt, visible, annotate=annotate, plot_lines=plot_lines, colors=colors)
     if hide_axis:
         ax.axis('off')
     if title:
         ax.set_title(title)
Ejemplo n.º 18
0
    def plot_mpl(self,
                 ax: plt.Axes = None,
                 key: str = None,
                 **kwargs) -> plt.Axes:
        """Simple mesh plot using `matplotlib`.

        Parameters
        ----------
        ax : plt.Axes, optional
            Axes to use for plotting.
        key : str, optional
            Label of cell data item to plot, defaults to the
            first key in `.cell_data`.
        fields : dict
            Maps cell data value to string for legend.
        **kwargs
            Extra keyword arguments passed to `ax.triplot`

        Returns
        -------
        plt.Axes
        """
        if not ax:
            fig, ax = plt.subplots()

        if key is None:
            try:
                key = tuple(self.cell_data.keys())[0]
            except IndexError:
                pass

        # https://github.com/python/mypy/issues/9430
        cell_data = self.cell_data.get(key, self.zero_labels)  # type: ignore

        for cell_data_val in np.unique(cell_data):
            vert_x, vert_y = self.points.T

            name = self.number_to_field.get(cell_data_val, cell_data_val)

            ax.triplot(vert_y,
                       vert_x,
                       triangles=self.cells,
                       mask=cell_data != cell_data_val,
                       label=name)

        ax.set_title(f'{self._cell_type} mesh')
        ax.axis('equal')

        _legend_with_triplot_fix(ax, title=key)

        return ax
Ejemplo n.º 19
0
def plot2d(
    mesh: BaseMesh,
    *,
    metric: str,
    ax: plt.Axes = None,
    **kwargs,
) -> plt.Axes:
    """Create a mesh plot with the cells are colored by the cell quality.

    Parameters
    ----------
    mesh : BaseMesh
        Input mesh
    metric : str
        Metric to calculate.
    ax : `matplotlib.Axes`
        If specified, `ax` will be used to create the subplot.
    vmin, vmax : int, float
        Set the lower/upper boundary for the color value.
        Defaults to the 1st and 99th percentile, respectively.
    cmap : str
        Set the color map.
    **kwargs
        Keyword arguments passed on to `ax.tripcolor`.

    Returns
    -------
    ax : `matplotlib.Axes`
    """
    descriptor = _metric_dispatch[metric]
    quality = descriptor.func(mesh)  # type: ignore

    kwargs.setdefault('vmin', np.percentile(quality, 1))
    kwargs.setdefault('vmax', np.percentile(quality, 99))

    fig, ax = plt.subplots()

    x = mesh.points[:, 0]
    y = mesh.points[:, 1]

    cells = mesh.cells

    tpc = ax.tripcolor(x, y, quality, triangles=cells, **kwargs)
    ax.figure.colorbar(tpc)
    ax.axis('scaled')

    ax.set_title(f'Triplot of {descriptor.name.lower()}')

    return ax
Ejemplo n.º 20
0
def plot_2G(ax: plt.Axes):
    # data from analysis.analyze_shuffling.ipynb
    import pickle
    with open('../data/shuffled.dat', 'rb') as f:
        x = pickle.load(f)
        y = pickle.load(f)
    plt.scatter(x, y, fc='gray', ec='k', linewidths=0.5, s=5, alpha=0.5)
    xy_min, xy_max = min(min(x), min(y)), max(max(x), max(y))
    plt.plot([xy_min, xy_max], [xy_min, xy_max], ':', color='gray')
    ax.axis('equal')
    ax.set_xlabel(r'$\mathcal{L}$(human choices)')
    ax.set_ylabel(r'$\mathcal{L}$(shuffled choices)')
    plt.yticks([-200, -150], rotation=90, va='center')
    ax.spines['right'].set_visible(False)
    ax.spines['top'].set_visible(False)
    plt.tight_layout()
Ejemplo n.º 21
0
    def __setup_subplot__(self, rhythm_loop: RhythmLoop, axes: plt.Axes, **kw):
        # avoid stretching the aspect ratio
        axes.axis('equal')
        # noinspection PyTypeChecker
        axes.axis([0, 1, 0, 1])

        # add base rhythm circle
        main_radius = 0.3
        main_center = 0.5, 0.5

        # draws a wedge from the given start pulse to the given end pulse
        def draw_wedge(pulse_start,
                       pulse_end,
                       center=main_center,
                       radius=main_radius,
                       **kw_):
            theta_1, theta_2 = (((90 - (pulse / n_pulses * 360)) % 360)
                                for pulse in (pulse_end, pulse_start))
            axes.add_artist(Wedge(center, radius, theta_1, theta_2, **kw_))

        unit = self.get_unit()
        n_pulses = kw['n_pulses']
        n_pulses_per_measure = int(rhythm_loop.get_measure_duration(unit))

        try:
            n_measures = int(n_pulses / n_pulses_per_measure)
        except ZeroDivisionError:
            n_measures = 0

        # measure wedges
        for i_measure in range(0, n_measures, 2):
            from_pulse = i_measure * n_pulses_per_measure
            to_pulse = (i_measure + 1) * n_pulses_per_measure
            draw_wedge(from_pulse,
                       to_pulse,
                       radius=1.0,
                       fc=to_rgba("gray", 0.25))

        # main circle
        circle = plt.Circle(main_center, main_radius, fc="white")
        axes.add_artist(circle)

        # draw the pulse wedges
        for i_pulse in range(0, n_pulses, 2):
            draw_wedge(i_pulse, i_pulse + 1, fc=to_rgba("gray", 0.25))

        return circle
Ejemplo n.º 22
0
    def plot(self, ax: plt.Axes = None) -> None:
        for key in self.keys:
            if self._odict[key] is None:
                continue
            elif key == 'roc_curve':
                fpr, tpr, thresholds = self._odict[key]

                if ax is None:
                    fig = plt.figure(figsize=(6, 6))
                    ax = plt.subplot(1, 1, 1)
                ax.plot(fpr, tpr)
                ax.set_title("ROC Curve")
                ax.set_xlabel("False Positive Rate")
                ax.set_ylabel("True Positive Rate")
                ax.axis('equal')
                if ax is None:
                    plt.show()
Ejemplo n.º 23
0
def info(
    data: SWIFTDataset, ax: plt.Axes, radial_bins: np.array, center: np.array
) -> None:

    metadata = data.metadata

    try:
        viscosity = metadata.viscosity_info
    except:
        viscosity = "No info"

    try:
        diffusion = metadata.diffusion_info
    except:
        diffusion = "No info"

    output = (
        "$\\bf{SWIFT}$\n"
        + metadata.code_info
        + "\n\n"
        + "$\\bf{Compiler}$\n"
        + metadata.compiler_info
        + "\n\n"
        + "$\\bf{Hydrodynamics}$\n"
        + metadata.hydro_info
        + "\n\n"
        + "$\\bf{Viscosity}$\n"
        + viscosity
        + "\n\n"
        + "$\\bf{Diffusion}$\n"
        + diffusion
    )

    ax.text(
        0.5,
        0.45,
        output,
        ha="center",
        va="center",
        fontsize=info_fontsize,
        transform=ax.transAxes,
    )

    ax.axis("off")
Ejemplo n.º 24
0
def scatter_pred_vs_tag(y_hat, y_gt, title, ax:plt.Axes=None, save_path="plots/new scatter pred tag"):
    """
    plot scatter of predict vs real tag
    @param y_hat: predict
    @param y_gt: real tag
    @param title: plot title
    @param save_path: where to save plot
    @return:
    """
    if ax is None:
        fig, ax = plt.subplots(1)
    ax.scatter(y_hat, y_gt)
    ax.set_title("predict vs real tag " + title)
    ax.set_xlabel("predict")
    ax.set_ylabel("real tag")
    ax.axis('square')
    if ax is None:
        fig.savefig(f"{save_path}/new scatter pred vs tag  " + title + ".svg")
        plt.show(fig)
Ejemplo n.º 25
0
def hexplot(
        ax: plt.Axes,
        grid: np.ndarray,
        data: np.ndarray,
        hex_size: float=11.5,
        cmap: str='viridis'
) -> plt.Axes:
    '''
    Plot grid and data on a hexagon grid. Useful for SOMs.

    Parameters
    ----------
    ax : Axes to plot on.
    grid : Array of (x, y) tuples.
    data : Array of len(grid) with datapoint.
    hex_size : Radius in points determining the hexagon size.
    cmap : Colormap to use for colouring.

    Returns
    -------
    ax : Axes with hexagon plot.

    '''

    # Create hexagons
    collection = RegularPolyCollection(
        numsides=6,
        sizes=(2 * np.pi * hex_size ** 2,),
        edgecolors=(0, 0, 0, 0),
        transOffset=ax.transData,
        offsets=grid,
        array=data,
        cmap=plt.get_cmap(cmap)
    )

    # Scale the plot properly
    ax.add_collection(collection, autolim=True)
    ax.set_xlim(grid[:, 0].min() - 0.75, grid[:, 0].max() + 0.75)
    ax.set_ylim(grid[:, 1].min() - 0.75, grid[:, 1].max() + 0.75)
    ax.axis('off')

    return ax
Ejemplo n.º 26
0
def hexplot(
        ax: plt.Axes,
        grid: np.ndarray,
        data: np.ndarray,
        hex_size: float=11.5,
        cmap: str='viridis'
) -> plt.Axes:
    """
    Plot grid and data on a hexagon grid. Useful for SOMs.

    Parameters
    ----------
    ax : Axes to plot on.
    grid : Array of (x, y) tuples.
    data : Array of len(grid) with datapoint.
    hex_size : Radius in points determining the hexagon size.
    cmap : Colormap to use for colouring.

    Returns
    -------
    ax : Axes with hexagon plot.

    """

    # Create hexagons
    collection = RegularPolyCollection(
        numsides=6,
        sizes=(2 * np.pi * hex_size ** 2,),
        edgecolors=(0, 0, 0, 0),
        transOffset=ax.transData,
        offsets=grid,
        array=data,
        cmap=plt.get_cmap(cmap)
    )

    # Scale the plot properly
    ax.add_collection(collection, autolim=True)
    ax.set_xlim(grid[:, 0].min() - 0.75, grid[:, 0].max() + 0.75)
    ax.set_ylim(grid[:, 1].min() - 0.75, grid[:, 1].max() + 0.75)
    ax.axis('off')

    return ax
Ejemplo n.º 27
0
def plot_board(ax_board: plt.Axes, board: Board, nums: IntPair,
               num_offsets: IntPair, index: int):
    ax_board.clear()
    ax_board.set_title(str(index))
    for num, offset, top_y in zip(nums, num_offsets, PlotConst.col_top_y):
        # for loop by raw

        col_top_x = np.linspace(0, 1, num + 2)[1:-1]
        for cc in range(num):
            # flor loop by column

            column = board.get_board()[cc + offset]
            for ee in range(Column.LEN):
                ax_board.plot([col_top_x[cc]],
                              [top_y - ee * PlotConst.y_pitch],
                              color=column[ee].to_color_string(),
                              **PlotConst.plot_args)
    ax_board.set_xlim([0, 1.1])
    ax_board.set_ylim([0, 1.1])
    ax_board.axis("off")
Ejemplo n.º 28
0
def imshow(img: np.ndarray,
           title: str = None,
           color: bool = True,
           cmap: str = "gray",
           axis: bool = False,
           ax: plt.Axes = None):
    if not ax:
        ax = plt
    # Plot Image
    if color:
        ax.imshow(img)
    else:
        ax.imshow(img, cmap=cmap)

    # Ask about the axis
    if not axis:
        ax.axis("off")

    # Ask about the title
    if title:
        ax.title(title)
Ejemplo n.º 29
0
    def plot_analyzed_subimage(self,
                               subimage: str = 'wobble',
                               ax: plt.Axes = None,
                               show: bool = True):
        """Plot a subimage of the starshot analysis. Current options are the zoomed out image and the zoomed in image.

        Parameters
        ----------
        subimage : str
            If 'wobble', will show a zoomed in plot of the wobble circle.
            Any other string will show the zoomed out plot.
        ax : None, matplotlib Axes
            If None (default), will create a new figure to plot on, otherwise plot to the passed axes.
        """
        if ax is None:
            fig, ax = plt.subplots()
        # show analyzed image
        ax.imshow(self.image.array, cmap=get_dicom_cmap())
        self.lines.plot(ax)
        self.wobble.plot2axes(ax, edgecolor='green')
        self.circle_profile.plot2axes(ax, edgecolor='green')
        ax.autoscale(tight=True)
        ax.axis('off')

        # zoom in if wobble plot
        if subimage == 'wobble':
            xlims = [
                self.wobble.center.x + self.wobble.diameter,
                self.wobble.center.x - self.wobble.diameter
            ]
            ylims = [
                self.wobble.center.y + self.wobble.diameter,
                self.wobble.center.y - self.wobble.diameter
            ]
            ax.set_xlim(xlims)
            ax.set_ylim(ylims)
            ax.axis('on')

        if show:
            plt.show()
Ejemplo n.º 30
0
def draw_gridlike(graph: nx.Graph,
                  ax: plt.Axes = None,
                  tilted: bool = True,
                  **kwargs) -> Dict[Any, Tuple[int, int]]:
    """Draw a grid-like graph using Matplotlib.

    This wraps nx.draw_networkx to produce a matplotlib drawing of the graph. Nodes
    should be two-dimensional gridlike objects.

    Args:
        graph: A NetworkX graph whose nodes are (row, column) coordinates or cirq.GridQubits.
        ax: Optional matplotlib axis to use for drawing.
        tilted: If True, directly position as (row, column); otherwise,
            rotate 45 degrees to accommodate google-style diagonal grids.
        **kwargs: Additional arguments to pass to `nx.draw_networkx`.

    Returns:
        A positions dictionary mapping nodes to (x, y) coordinates suitable for future calls
        to NetworkX plotting functionality.
    """
    if ax is None:
        ax = plt.gca()  # coverage: ignore

    if tilted:
        pos = {
            node: (y, -x)
            for node, (x, y) in _node_and_coordinates(graph.nodes)
        }
    else:
        pos = {
            node: (x + y, y - x)
            for node, (x, y) in _node_and_coordinates(graph.nodes)
        }

    nx.draw_networkx(graph, pos=pos, ax=ax, **kwargs)
    ax.axis('equal')
    return pos
Ejemplo n.º 31
0
    def __init__(self, ax: plt.Axes, attitude_data: SO3):
        if not isinstance(ax, plt.Axes):
            raise TypeError("The axes must be of plt.Axes type.")
        if not isinstance(attitude_data, SO3):
            raise TypeError("The attitude_data must be an SO3 element.")

        # Background
        ah_circle = Circle((0, 0), radius=1.0, color='w', ec='w')
        ah_colouring = Circle((0, 0), radius=5.0, color='k')
        ax.add_patch(ah_colouring)
        ax.add_patch(ah_circle)

        # Horizon line
        self._attitude_data = attitude_data
        true_horizon = self._compute_horizon(attitude_data)
        self._horizon_line, = ax.plot(true_horizon[0, :], true_horizon[1, :])

        # Horizon shading
        height = self._compute_horizon_height(attitude_data)
        slope = self._compute_horizon_slope(attitude_data) * 180.0 / np.pi
        self._shade = Wedge((0, height), 2.0, -180 + slope, slope, alpha=0.5)
        ax.add_patch(self._shade)

        # Clip path
        clip_circle = Circle((0, 0), radius=1.0, transform=ax.transData)
        self._horizon_line.set_clip_path(clip_circle)
        self._shade.set_clip_path(clip_circle)

        # Center Overlay
        ax.add_patch(Arc((0, 0), 0.3, 0.3, theta1=180, lw=2.0))
        ax.plot([0.15, 0.6], [0, 0], color='k', lw=2.0)
        ax.plot([-0.15, -0.6], [0, 0], color='k', lw=2.0)

        # Axes settings
        ax.axis('square')
        ax.set_xlim([-1, 1])
        ax.set_ylim([-1, 1])
Ejemplo n.º 32
0
    def show_contour(self, ax: plt.Axes = None):
        """Plot contours on image.

        Parameters
        ----------
        ax : matplotlib.Axes
            Axes to use for plotting.

        Returns
        -------
        ax : matplotlib.Axes
        """
        if not ax:
            fig, ax = plt.subplots()

        ax.set_title('Contours')
        self.contour.plot_mpl(ax=ax)

        ax.imshow(self.image)
        ax.axis('image')
        ax.set_xticks([])
        ax.set_yticks([])

        return ax