示例#1
0
def plot_gtf(panel: plt.Axes, data: list, y_offset: float,
             linewidths: list) -> plt.Axes:
    """Apply gtf data to specified data axis."""
    # initialize y_index
    y_index = y_offset
    # This dictionary is used to plot hte width based on type
    lwdd = {
        "transcript": linewidths[0],
        "exon": linewidths[1],
        "CDS": linewidths[2]
    }
    # This dictionary holds the last valued plotted at each y_index.
    y_index_dict = {}
    # Groups by each transcript ID
    for _, group in groupby(data, itemgetter(0)):
        # Convert from iterator to list.
        group = list(group)
        new_start = min([x[2] for x in group])
        new_end = max([x[3] for x in group])
        # set the y_index
        if y_index_dict.keys():
            y_index = max(y_index_dict.keys()) + y_offset
        for dict_key in y_index_dict:
            if new_start > y_index_dict[dict_key]:
                y_index = min(dict_key, y_index)
        for feature in group:
            panel.add_patch(
                mplpatches.Rectangle(xy=(feature[2],
                                         (y_index - (lwdd[feature[1]] / 2))),
                                     width=(feature[3] - feature[2]),
                                     height=lwdd[feature[1]],
                                     edgecolor=None,
                                     facecolor='Black'))
        y_index_dict[y_index] = new_end
    return panel
示例#2
0
    def draw_bbox_rectangle(ax: plt.Axes, box: Bbox):
        """Draws a green rectangle around the specified Bbox"""

        rect = Rectangle(xy=(box.x0, box.y0), width=box.width, height=box.height,
                                  transform=ax.get_transform(), clip_on=False, color="green", fill=False)
        rect.set_in_layout(False)
        ax.add_patch(rect)
示例#3
0
    def _add_rectangle(
        self,
        axes: plt.Axes,
        label: Optional[str],
        rectangle_dims: Mapping[str, Union[float, Tuple[float, float]]],
        alpha: float = 0.1,
    ):
        """Plot a rectangle on given coordinates around reaction forces.

        Args:
            forces_legend: the description of the forces that appears on the
                legend.

            rectangle_dims: a mapping that should have the following keys:
                `"xy"`, `"width"`, `"height"`. The first should be the `(x_pos,
                y_pos)` coordinates of the rectangle's bottom-left corner, the
                other two single numbers.

            box_legend: the description of the rectangle that appears on the
                legend.

            alpha: transparency of the rectangle.

            kwargs: passed to :py:meth:`SegmentPlotter.plot_reactions`.
        """
        rect = patches.Rectangle(**rectangle_dims, alpha=alpha, label=label)
        axes.add_patch(rect)
示例#4
0
    def plot2axes(self,
                  axes: plt.Axes = None,
                  edgecolor: str = 'black',
                  fill: bool = False,
                  plot_peaks: bool = True):
        """Add 2 circles to the axes: one at the maximum and minimum radius of the ROI.

        See Also
        --------
        :meth:`~pylinac.core.profile.CircleProfile.plot2axes` : Further parameter info.
        """
        if axes is None:
            fig, axes = plt.subplots()
            axes.imshow(self.image_array)
        axes.add_patch(
            mpl_Circle((self.center.x, self.center.y),
                       edgecolor=edgecolor,
                       radius=self.radius * (1 + self.width_ratio),
                       fill=fill))
        axes.add_patch(
            mpl_Circle((self.center.x, self.center.y),
                       edgecolor=edgecolor,
                       radius=self.radius * (1 - self.width_ratio),
                       fill=fill))
        if plot_peaks:
            x_locs = [peak.x for peak in self.peaks]
            y_locs = [peak.y for peak in self.peaks]
            axes.autoscale(enable=False)
            axes.scatter(x_locs, y_locs, s=20, marker='x', c=edgecolor)
示例#5
0
    def plot2axes(self,
                  axes: plt.Axes,
                  edgecolor: str = 'black',
                  angle: float = 0.0,
                  fill: bool = False,
                  alpha: float = 1,
                  facecolor: str = 'g'):
        """Plot the Rectangle to the axes.

        Parameters
        ----------
        axes : matplotlib.axes.Axes
            An MPL axes to plot to.
        edgecolor : str
            The color of the circle.
        angle : float
            Angle of the rectangle.
        fill : bool
            Whether to fill the rectangle with color or leave hollow.
        """
        axes.add_patch(
            mpl_Rectangle((self.bl_corner.x, self.bl_corner.y),
                          width=self.width,
                          height=self.height,
                          angle=angle,
                          edgecolor=edgecolor,
                          alpha=alpha,
                          facecolor=facecolor,
                          fill=fill))
示例#6
0
    def __plot_bunches(self,
                       fig: plt.Figure,
                       ax: plt.Axes,
                       point: FiniteMetricVertex,
                       name: str = "u") -> None:
        """
        Plot all points and highlight the bunches for the given point on
        the provided figure/axes.

        :param fig: The matplotlib figure to plot on.
        :param ax: The matplotlib axes to plot on.
        :param point: The vertex whose bunches we wish to plot.
        :param name: The name to use to label the vertex/bunches.
        """
        ax.cla()

        # Plot all points and color by set A_i
        ax.scatter([v.i for v in self.vertices], [v.j for v in self.vertices],
                   s=4,
                   color="black",
                   marker=".",
                   label="Points")

        # Plot and label the point itself
        ax.scatter([point.i], [point.j],
                   s=12,
                   color="red",
                   marker="*",
                   label=name)
        ax.annotate(name, (point.i, point.j), color="red")

        # Force the xlim and ylim to become fixed
        ax.set_xlim(*ax.get_xlim())
        ax.set_ylim(*ax.get_ylim())

        # For the current point, mark and label its p_i s
        # and add circles
        p_i = [self.p[point][i] for i in range(self.k)]
        for i in range(1, self.k):
            if p_i[i] is None:
                continue
            ax.annotate("p_{}({})".format(i, name), (p_i[i][0].i, p_i[i][0].j),
                        xytext=(5, 5),
                        textcoords="offset pixels",
                        color="violet")
            circ = plt.Circle((point.i, point.j), p_i[i][1], fill=False)
            ax.add_patch(circ)

        # Plot the points in the bunch
        B = [w for w in self.B[point]]
        ax.scatter([w.i for w in B], [w.j for w in B],
                   s=12,
                   color="lime",
                   marker="*",
                   label="B({})".format(name))

        ax.set_title("Bunch B({})".format(name))
        ax.legend(bbox_to_anchor=(1.05, 1.0), loc='upper left')
        plt.tight_layout()
        fig.show()
示例#7
0
    def plot2axes(self,
                  axes: plt.Axes = None,
                  edgecolor: str = 'black',
                  fill: bool = False,
                  plot_peaks: bool = True):
        """Plot the circle to an axes.

        Parameters
        ----------
        axes : matplotlib.Axes, None
            The axes to plot on. If None, will create a new figure of the image array.
        edgecolor : str
            Color of the Circle; must be a valid matplotlib color.
        fill : bool
            Whether to fill the circle. matplotlib keyword.
        plot_peaks : bool
            If True, plots the found peaks as well.
        """
        if axes is None:
            fig, axes = plt.subplots()
            axes.imshow(self.image_array)
        axes.add_patch(
            mpl_Circle((self.center.x, self.center.y),
                       edgecolor=edgecolor,
                       radius=self.radius,
                       fill=fill))
        if plot_peaks:
            x_locs = [peak.x for peak in self.peaks]
            y_locs = [peak.y for peak in self.peaks]
            axes.autoscale(enable=False)
            axes.scatter(x_locs, y_locs, s=40, marker='x', c=edgecolor)
示例#8
0
def plot_psl(panel: plt.Axes, data: list, y_offset: float,
             linewidths: list) -> plt.Axes:
    """Apply psl data to specified data axis."""
    # initialize the offset
    y_index = y_offset
    # Dict holds Y values and furthest right point of any line.
    y_index_dict = {}
    # checks to see if line overlaps other line(s) and sets y index accordingly
    for _, record in enumerate(data):
        if y_index_dict.keys():
            y_index = max(y_index_dict.keys()) + y_offset
        for dict_key in y_index_dict:
            if record[1] > y_index_dict[dict_key]:
                y_index = min(dict_key, y_index)
        # Adds the main rectangle
        panel.add_patch(
            mplpatches.Rectangle(xy=(record[1], y_index),
                                 width=record[2] - record[1],
                                 height=linewidths[0],
                                 edgecolor=None,
                                 facecolor='Black'))
        # Adds all the features of the main rectangle.
        for feature in zip(record[3], record[4]):
            panel.add_patch(
                mplpatches.Rectangle(xy=(feature[0],
                                         (y_index - (linewidths[1] / 2))),
                                     width=feature[1],
                                     height=linewidths[1],
                                     edgecolor=None,
                                     facecolor='Black'))
        # updates dictionary
        y_index_dict[y_index] = record[2]
    return panel
示例#9
0
def plot_radius_circle(fig: plt.Figure, ax: plt.Axes, R: PlanarTriangle,
                       P: Triangle, i: int):
    sol = R.min_max_traversal_triangle(P)
    circle = Circle(R.points[i],
                    np.linalg.norm(sol.points[i] - R.points[i]),
                    linestyle="--",
                    fill=None)
    ax.add_patch(circle)
示例#10
0
def draw_objects(axes: plt.Axes, objects: list):
    for obj in objects:
        x_bounds = obj.bounds['x']
        y_bounds = obj.bounds['y']
        x = x_bounds[0]
        w = x_bounds[1] - x
        y = y_bounds[0]
        h = y_bounds[1] - y
        axes.add_patch(patches.Rectangle((x, y), w, h, color='gray'))
示例#11
0
 def draw_path(self, ax: plt.Axes, path, properties: Properties, z: float):
     vertices, codes = _get_path_patch_data(path)
     patch = PathPatch(Path(vertices, codes),
                       linewidth=self.lineweight(properties),
                       linestyle=self.pattern(properties),
                       fill=False,
                       color=properties.color,
                       zorder=z)
     ax.add_patch(patch)
示例#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
示例#13
0
def plot_arrow(fig: plt.Figure, ax: plt.Axes, R: PlanarTriangle, P: Triangle,
               i: int, scale: bool):
    triv = get_triv(R, P, i)
    length = triv.points[2] - R.points[i]
    if scale:
        length *= P.sides[(i + 1) % 3]
    arrow = FancyArrow(*R.points[i],
                       *length,
                       length_includes_head=True,
                       head_width=0.035,
                       color="black")
    ax.add_patch(arrow)
示例#14
0
    def __plot_p_i(self,
                   fig: plt.Figure,
                   ax: plt.Axes,
                   point: FiniteMetricVertex,
                   name: str = "u") -> None:
        """
        Plot all points and highlight the witnesses p_i for the given point
        along with corresponding rings on the given figure and axes.

        :param fig: The matplotlib figure to plot on.
        :param ax: The matplotlib axes to plot on.
        :param point: The vertex whose witnesses/rings we wish to plot.
        :param name: The name to use to label the vertex/bunches.
        """
        ax.cla()

        # Plot all points and color by set A_i
        for i, a_i in enumerate(self.A):
            ax.scatter([v.i for v in a_i], [v.j for v in a_i],
                       s=8,
                       marker="o",
                       label="A_{}".format(i))

        # Plot and label the point itself
        ax.scatter([point.i], [point.j],
                   s=12,
                   color="red",
                   marker="*",
                   label=name)
        ax.annotate(name, (point.i, point.j), color="red")

        # Force the xlim and ylim to become fixed
        ax.set_xlim(*ax.get_xlim())
        ax.set_ylim(*ax.get_ylim())

        # For the current point, mark and label its p_i s
        # and add circles
        p_i = [self.p[point][i] for i in range(self.k)]
        for i in range(1, self.k):
            if p_i[i] is None:
                continue
            ax.annotate("p_{}({})".format(i, name), (p_i[i][0].i, p_i[i][0].j),
                        xytext=(5, 5),
                        textcoords="offset pixels",
                        color="violet")
            circ = plt.Circle((point.i, point.j), p_i[i][1], fill=False)
            ax.add_patch(circ)

        ax.set_title("Witnesses p_i({}) and rings.".format(name))
        ax.legend(bbox_to_anchor=(1.05, 1.0), loc='upper left')
        plt.tight_layout()
        fig.show()
示例#15
0
def plot_bb_image(image: np.ndarray,
                  bbs: List[List[float]] = [],
                  relative_size_bb=True,
                  ax: plt.Axes = None):
    """
    Plot an image and a set of bounding boxes.
    :param image: The image as a numpy array
    :param bbs:  A list of lists, which inner list having five values. The first one being the class and then
                        [xmin, xmax, ymin, ymax]
    :param relative_size_bb: When True the bounding boxes are assumed to be relative to the size of the image. So
                            values between 0 and 1.
    :param ax: A plt.Axes object where to plot the image and bounding boxes when required. If not passed, it will create
                one.
    :return: None.
    """
    pass_ax = True
    if ax is None:
        pass_ax = False
        # Create figure and axes
        fig, ax = plt.subplots(1)

    # Display the image
    ax.imshow(image.astype(np.uint8))

    h, w = image.shape[:2]
    sizes = [w, h, w, h]

    colors = ['r', 'g', 'b', 'k']
    for bb in bbs:
        label = bb[0]
        color = colors[label]

        if relative_size_bb:
            #Convert bounding boxes from relative to absolute values
            bb = [
                int(round(size * coord)) for coord, size in zip(bb[1:], sizes)
            ]

        # Create a Rectangle patch
        rect = patches.Rectangle((bb[0], bb[1]),
                                 bb[2] - bb[0],
                                 bb[3] - bb[1],
                                 linewidth=2,
                                 edgecolor=color,
                                 facecolor='none')

        # Add the patch to the Axes
        ax.add_patch(rect)

    if not pass_ax:
        plt.axis('off')
        plt.show()
示例#16
0
    def __init__(
        self, *points, ax: plt.Axes = None, color=grey_dark, **kwargs,
    ):
        """
            Given a list of tuples/lists of XY coordinates of each point, 
            this class draws a polygon
        """
        ax = ax or plt.gca()

        xy = np.vstack(points)

        patch = Polygon_patch(xy, color=color, **kwargs)
        ax.add_patch(patch)
示例#17
0
    def plot_init(self, ax: plt.Axes):
        """Copied from https://matplotlib.org/3.1.1/gallery/animation/animated_histogram.html"""
        import matplotlib.patches as patches
        import matplotlib.path as path

        self.artists = []
        ax.clear()
        _apply_hook(ax, self.hook)
        init_data = self.data.flatten()
        n, bins = np.histogram(init_data, self.num_bins)

        # get the corners of the rectangles for the histogram
        left = np.array(bins[:-1])
        right = np.array(bins[1:])
        self._bottom = np.zeros(len(left))
        top = self._bottom + n / (self.num_frames * 0.9)
        nrects = len(left)

        # here comes the tricky part -- we have to set up the vertex and path
        # codes arrays using moveto, lineto and closepoly

        # for each rect: 1 for the MOVETO, 3 for the LINETO, 1 for the
        # CLOSEPOLY; the vert for the closepoly is ignored but we still need
        # it to keep the codes aligned with the vertices
        nverts = nrects * (1 + 3 + 1)
        self._verts = np.zeros((nverts, 2))
        codes = np.ones(nverts, int) * path.Path.LINETO
        codes[0::5] = path.Path.MOVETO
        codes[4::5] = path.Path.CLOSEPOLY

        self._verts[0::5, 0] = left
        self._verts[1::5, 0] = left

        self._verts[2::5, 0] = right
        self._verts[3::5, 0] = right

        self._verts[1::5, 1] = top
        self._verts[2::5, 1] = top

        self._verts[0::5, 1] = self._bottom
        self._verts[3::5, 1] = self._bottom

        barpath = path.Path(self._verts, codes)
        patch = patches.PathPatch(barpath, facecolor="green", edgecolor="yellow", alpha=0.5)
        ax.add_patch(patch)

        ax.set_xlim(left[0], right[-1])
        ax.set_ylim(self._bottom.min(), top.max())
        self.artists.append(patch)
示例#18
0
 def __init__(
     self,
     x_0,
     x_1,
     y_0,
     y_1,
     ax: plt.Axes = None,
     color=blue_grey_dark,
     **kwargs,
 ):
     ax = ax or plt.gca()
     rect = Rectangle_patch(
         (x_0, y_0), x_1 - x_0, y_1 - y_0, color=color, **kwargs
     )
     ax.add_patch(rect)
示例#19
0
def plot_cube_2D(ax: plt.Axes, cube: Cube):
    """Plots the :class:`Rubix Cube <Cube>` on a
    :class:`matplotlib Axes <matplotlib.axes.Axes>` on a flattened 2-D
    representation.

    Args:
        ax (plt.Axes): The :class:`matplotlib Axes <matplotlib.axes.Axes>`
            on which the plotting will be done.
        cube (Cube): :class:`Rubix Cube <Cube>` that will be plotted in a
            flattened 2-D representation of all 6 sides.

    Returns:
        None.

    """

    # Ensures the arguments are well-formed.
    if cube.is_well_formed()\
    and isinstance(ax , plt.Axes):

        for face_name in cube.faces:

            # Grabs the local coordinates for each face
            face_local_coords = FACE_COORDS[face_name]

            # Grabs the face values for filling in the plot for each tile
            # in the 2-D representation.
            face_values = cube.faces[face_name]

            #print(f"{face_name} : ")

            for row_idx, row in enumerate(face_values):

                for col_idx, color_val in enumerate(row):

                    tile_coords = (face_local_coords[0] + 100 * col_idx,
                                   face_local_coords[1] - 100 * row_idx)

                    #print(f"\t[{row_idx},{col_idx}] : {tile_coords}")

                    rect = patches.Rectangle(xy=tile_coords,
                                             width=100,
                                             height=100,
                                             facecolor=str(color_val),
                                             lw=2,
                                             edgecolor='black')

                    ax.add_patch(rect)
示例#20
0
def draw_ellipse(position: List[float],
                 covariance: List[float],
                 ax: plt.Axes = None):
    """Draw an ellipse with a given position and covariance"""
    angle = 0
    width, height = 2 * np.sqrt(covariance)

    # Draw the Ellipse
    for n in range(1, 4):
        ax.add_patch(
            Ellipse(position,
                    n * width,
                    n * height,
                    angle,
                    alpha=1 / (width + height),
                    color='red'))
示例#21
0
def _plot_ellipse_covariance(mean,
                             cov,
                             ax: plt.Axes,
                             confidence=.9,
                             facecolor='none',
                             edgecolor="k",
                             linestyle='--',
                             **kwargs):
    if type(confidence) is not list:
        confidence = [confidence]
    eigvals, eigvecs = np.linalg.eigh(cov)
    if np.min(eigvals) < 0:
        print(f"Found a negative eigenvalue. Aborting. ({eigvals})")
        return
    eigvals = np.sqrt(eigvals)
    if eigvecs[1, 0] == 0:
        angle = np.sign(eigvecs[1, 1]) * 90
    else:
        angle = np.arctan(eigvecs[1, 1] / eigvecs[1, 0]) * 360 / (2 * np.pi)

    patches = []
    for conf in confidence:
        s = np.sqrt(chi2.ppf(conf, df=2))
        ellipse = Ellipse(mean,
                          width=2 * eigvals[1] * s,
                          height=2 * eigvals[0] * s,
                          angle=angle,
                          facecolor=facecolor,
                          alpha=.3,
                          edgecolor=edgecolor,
                          linestyle=linestyle,
                          **kwargs)
        patches.append(ax.add_patch(ellipse))
    return patches
示例#22
0
def _draw_rect(ax:plt.Axes, b:Collection[int], color:str='white', text=None, text_size=14):
    "Draw bounding box on `ax`."
    patch = ax.add_patch(patches.Rectangle(b[:2], *b[-2:], fill=False, edgecolor=color, lw=2))
    _draw_outline(patch, 4)
    if text is not None:
        patch = ax.text(*b[:2], text, verticalalignment='top', color=color, fontsize=text_size, weight='bold')
        _draw_outline(patch,1)
示例#23
0
def plot_cov_ellipse2d(
    ax: plt.Axes,
    mean: np.ndarray = np.zeros(2),
    cov: np.ndarray = np.eye(2),
    n_sigma: float = 1,
    *,
    edgecolor: "Color" = "C0",
    facecolor: "Color" = "none",
    **kwargs,  # extra Ellipse keyword arguments
) -> matplotlib.patches.Ellipse:
    """Plot a n_sigma covariance ellipse centered in mean into ax."""
    ell_trans_mat = np.zeros((3, 3))
    ell_trans_mat[:2, :2] = np.linalg.cholesky(cov)
    ell_trans_mat[:2, 2] = mean
    ell_trans_mat[2, 2] = 1

    ell = matplotlib.patches.Ellipse(
        (0.0, 0.0),
        2.0 * n_sigma,
        2.0 * n_sigma,
        edgecolor=edgecolor,
        facecolor=facecolor,
        **kwargs,
    )
    trans = matplotlib.transforms.Affine2D(ell_trans_mat)
    ell.set_transform(trans + ax.transData)
    return ax.add_patch(ell)
示例#24
0
def plot_cov_ellipse2d(
        ax: plt.Axes = None,
        mean: np.ndarray = np.zeros(2),
        cov: np.ndarray = np.eye(2),
        n_sigma: float = 1,
        *,
        edgecolor: Color = 'C0',
        facecolor: Color = 'none',
        **kwargs,  # other Ellipse keyword arguments
) -> Optional[Ellipse]:
    """Plot a n_sigma covariance ellipse centered in mean into ax."""
    if ax is None:
        ax = plt.gca()

    if mean is None or cov is None:
        print('None parameters not handled: ellipse not plotted')
        return
    ell_trans_mat = np.zeros((3, 3))
    ell_trans_mat[:2, :2] = np.linalg.cholesky(cov)
    ell_trans_mat[:2, 2] = mean
    ell_trans_mat[2, 2] = 1

    ell = Ellipse((0.0, 0.0),
                  2.0 * n_sigma,
                  2.0 * n_sigma,
                  edgecolor=edgecolor,
                  facecolor=facecolor,
                  **kwargs)
    trans = Affine2D(ell_trans_mat)
    ell.set_transform(trans + ax.transData)
    return ax.add_patch(ell)
示例#25
0
 def alpha_label(
     axes_: Axes,
     xy_pt1_B: np.ndarray,
     xy_pt2_B: np.ndarray,
     color_: str = red_,
 ) -> None:
     label_xy = [0.55, 0.75]
     axes_.text(
         *label_xy,
         r"$-\alpha$",
         color=color_,
         fontsize=20,
         rotation=0,
         transform=axes_.transAxes,
         horizontalalignment="center",
         verticalalignment="center",
     )
     # angle_ref = 0
     angle_B = np.rad2deg(
         np.arctan(
             (xy_pt2_B[1] - xy_pt1_B[1])
             / (xy_pt2_B[0] - xy_pt1_B[0])
         )
     )
     radius = 0.88
     axes_.add_patch(
         Arc(
             xy_pt2_B,
             radius,
             radius,
             color=color_,
             linestyle="--",
             linewidth=2,
             fill=False,
             zorder=2,
             # transform=axes_.transAxes,
             angle=angle_B,
             theta1=0,
             theta2=-angle_B,
         )
     )
     axes_.plot(
         [xy_pt2_B[0], xy_pt2_B[0] + 0.5],
         [xy_pt2_B[1], xy_pt2_B[1]],
         ":",
         color=color_,
     )
示例#26
0
 def psi_label(
     axes_: Axes,
     xy_pt1_B: np.ndarray,
     xy_pt2_B: np.ndarray,
     xy_pt1_C: np.ndarray,
     xy_pt2_C: np.ndarray,
     color_: str = red_,
 ) -> None:
     label_xy = [0.5, 0.53]
     axes_.text(
         *label_xy,
         r"$\psi$",
         color=color_,
         fontsize=20,
         rotation=0,
         transform=axes_.transAxes,
         horizontalalignment="center",
         verticalalignment="center",
     )
     angle_B = np.rad2deg(
         np.arctan(
             (xy_pt2_B[1] - xy_pt1_B[1])
             / (xy_pt2_B[0] - xy_pt1_B[0])
         )
     )
     angle_C = np.rad2deg(
         np.arctan(
             (xy_pt2_C[1] - xy_pt1_C[1])
             / (xy_pt2_C[0] - xy_pt1_C[0])
         )
     )
     radius = 0.95
     axes_.add_patch(
         Arc(
             xy_pt2_B,
             radius,
             radius,
             color=color_,
             linewidth=2,
             fill=False,
             zorder=2,
             # transform=axes_.transAxes,
             angle=angle_B,
             theta1=0,
             theta2=angle_C - angle_B,
         )
     )
示例#27
0
def drawRect(ax: plt.Axes,
             x0: float,
             y0: float,
             x1: float,
             y1: float,
             color=None,
             alpha: float = None,
             edgecolor=None,
             label: str = None,
             profile: dict = None) -> None:
    """
    Draw a rectangle from point (x0, y0) to (x1, y1)

    Args:
        ax: the plot axe
        x0: x coord of the start point
        y0: y coord of the start point
        x1: x coord of the end point
        y1: y coord of the end point
        color: the face color
        edgecolor: the color of the edges
        alpha: alpha value for the rectangle (both facecolor and edgecolor)
        label: if given, a label is plotted at the center of the rectangle
        profile: the profile used, or None for default

    """
    facecolor = _fallback(color, profile, 'facecolor')
    edgecolor = _fallback(edgecolor, profile, 'edgecolor')
    facecolor = _getcolor(facecolor)
    edgecolor = _getcolor(edgecolor)
    alpha = alpha if alpha is not None else _get(profile, 'alpha')
    rect = Rectangle((x0, y0),
                     x1 - x0,
                     y1 - y0,
                     facecolor=facecolor,
                     edgecolor=edgecolor,
                     alpha=alpha)
    ax.add_patch(rect)
    if label is not None:
        drawLabel(ax,
                  x=(x0 + x1) * 0.5,
                  y=(y0 + y1) * 0.5,
                  text=label,
                  profile=profile)
    if _get(profile, 'autoscale'):
        autoscaleAxis(ax)
示例#28
0
文件: boid.py 项目: TheDecks/Studies
    def draw(self, ax: plt.Axes, show_range: bool = False):
        """Draw boid on provided matplotlib axes object.

        :param ax: axes on which the boid should be drawn.
        :param show_range: whether to also show "seeing" range of the boid.
        """
        if show_range:
            arc = ptch.Arc(
                (self.x, self.y),
                width=2 * self.lu_distance,
                height=2 * self.lu_distance,
                angle=math.degrees(self.direction),
                theta1=math.degrees(2 * math.pi - self.lu_angle / 2),
                theta2=math.degrees(self.lu_angle / 2),
                color='black',
                linewidth=1,
                alpha=0.3,
                zorder=5)
            line_1 = plt.Line2D([
                self.x + self.lu_distance *
                math.cos(self.lu_angle / 2 + self.direction), self.x
            ], [
                self.y + self.lu_distance *
                math.sin(self.lu_angle / 2 + self.direction), self.y
            ],
                                color='black',
                                linewidth=1,
                                alpha=0.3,
                                zorder=5)
            line_2 = plt.Line2D([
                self.x + self.lu_distance *
                math.cos(2 * math.pi - self.lu_angle / 2 + self.direction),
                self.x
            ], [
                self.y + self.lu_distance *
                math.sin(2 * math.pi - self.lu_angle / 2 + self.direction),
                self.y
            ],
                                color='black',
                                linewidth=1,
                                alpha=0.3,
                                zorder=5)
            ax.add_line(line_1)
            ax.add_line(line_2)
            ax.add_patch(arc)
        ax.add_patch(self._arrow_representation())
示例#29
0
def add_internal_window_to_subplot(sampled: samples.Samples,
                                   ax: plt.Axes) -> None:
    if ax is None:
        return

    loss_window_radius = sampled.config.data_build.loss_window_radius
    window_radius = sampled.config.data_build.window_radius
    if loss_window_radius == window_radius:
        return
    buffer = int(window_radius - loss_window_radius)
    rect = patches.Rectangle((buffer, buffer),
                             loss_window_radius * 2,
                             loss_window_radius * 2,
                             linewidth=1,
                             edgecolor="red",
                             facecolor="none")
    ax.add_patch(rect)
示例#30
0
文件: plt2.py 项目: Gravifer/pylabyk
def patch_chance_level(level=None,
                       signs=(-1, 1),
                       ax: plt.Axes = None,
                       xy='y',
                       color=(0.7, 0.7, 0.7)):
    if level is None:
        level = np.log(10.)
    if ax is None:
        ax = plt.gca()

    hs = []
    for sign in signs:
        if xy == 'y':
            if ax.yaxis.get_scale() == 'log':
                vmin = 1.
                level1 = level * 10**sign
            else:
                vmin = 0.
                level1 = level * sign

            lim = ax.get_xlim()
            rect = mpl.patches.Rectangle([lim[0], vmin],
                                         lim[1] - lim[0],
                                         level1,
                                         linewidth=0,
                                         fc=color,
                                         zorder=-1)
        elif xy == 'x':
            if ax.xaxis.get_scale() == 'log':
                vmin = 1.
                level1 = level * 10**sign
            else:
                vmin = 0.
                level1 = level * sign

            lim = ax.get_ylim()
            rect = mpl.patches.Rectangle([vmin, lim[0]],
                                         level1,
                                         lim[1] - lim[0],
                                         linewidth=0,
                                         fc=color,
                                         zorder=-1)
        ax.add_patch(rect)
        hs.append(rect)
    return hs
示例#31
0
    def plot2axes(self, axes: plt.Axes=None, edgecolor: str='black', fill: bool=False, plot_peaks: bool=True):
        """Add 2 circles to the axes: one at the maximum and minimum radius of the ROI.

        See Also
        --------
        :meth:`~pylinac.core.profile.CircleProfile.plot2axes` : Further parameter info.
        """
        if axes is None:
            fig, axes = plt.subplots()
            axes.imshow(self.image_array)
        axes.add_patch(mpl_Circle((self.center.x, self.center.y), edgecolor=edgecolor, radius=self.radius*(1+self.width_ratio),
                                  fill=fill))
        axes.add_patch(mpl_Circle((self.center.x, self.center.y), edgecolor=edgecolor, radius=self.radius*(1-self.width_ratio),
                                  fill=fill))
        if plot_peaks:
            x_locs = [peak.x for peak in self.peaks]
            y_locs = [peak.y for peak in self.peaks]
            axes.autoscale(enable=False)
            axes.scatter(x_locs, y_locs, s=20, marker='x', c=edgecolor)
示例#32
0
    def plot2axes(self, axes: plt.Axes, edgecolor: str='black', angle: float=0.0, fill: bool=False,
                  alpha: float=1, facecolor: str='g'):
        """Plot the Rectangle to the axes.

        Parameters
        ----------
        axes : matplotlib.axes.Axes
            An MPL axes to plot to.
        edgecolor : str
            The color of the circle.
        angle : float
            Angle of the rectangle.
        fill : bool
            Whether to fill the rectangle with color or leave hollow.
        """
        axes.add_patch(mpl_Rectangle((self.bl_corner.x, self.bl_corner.y),
                                     width=self.width,
                                     height=self.height,
                                     angle=angle,
                                     edgecolor=edgecolor,
                                     alpha=alpha,
                                     facecolor=facecolor,
                                     fill=fill))
示例#33
0
    def plot2axes(self, axes: plt.Axes=None, edgecolor: str='black', fill: bool=False, plot_peaks: bool=True):
        """Plot the circle to an axes.

        Parameters
        ----------
        axes : matplotlib.Axes, None
            The axes to plot on. If None, will create a new figure of the image array.
        edgecolor : str
            Color of the Circle; must be a valid matplotlib color.
        fill : bool
            Whether to fill the circle. matplotlib keyword.
        plot_peaks : bool
            If True, plots the found peaks as well.
        """
        if axes is None:
            fig, axes = plt.subplots()
            axes.imshow(self.image_array)
        axes.add_patch(
            mpl_Circle((self.center.x, self.center.y), edgecolor=edgecolor, radius=self.radius, fill=fill))
        if plot_peaks:
            x_locs = [peak.x for peak in self.peaks]
            y_locs = [peak.y for peak in self.peaks]
            axes.autoscale(enable=False)
            axes.scatter(x_locs, y_locs, s=40, marker='x', c=edgecolor)