当前位置: 首页>>代码示例>>Python>>正文


Python Polygon.get_path方法代码示例

本文整理汇总了Python中matplotlib.patches.Polygon.get_path方法的典型用法代码示例。如果您正苦于以下问题:Python Polygon.get_path方法的具体用法?Python Polygon.get_path怎么用?Python Polygon.get_path使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在matplotlib.patches.Polygon的用法示例。


在下文中一共展示了Polygon.get_path方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: getCatalog

# 需要导入模块: from matplotlib.patches import Polygon [as 别名]
# 或者: from matplotlib.patches.Polygon import get_path [as 别名]
def getCatalog(size=10000, surveyname=None):
    # dummy catalog: uniform on sphere
    # Marsaglia (1972)
    xyz = np.random.normal(size=(size, 3))
    r = np.sqrt((xyz**2).sum(axis=1))
    dec = np.arccos(xyz[:,2]/r) / skm.DEG2RAD - 90
    ra = - np.arctan2(xyz[:,0], xyz[:,1]) / skm.DEG2RAD

    if surveyname is not None:
        from matplotlib.patches import Polygon
        # construct survey polygon
        ra_fp, dec_fp = skm.survey_register[surveyname].getFootprint()
        poly = Polygon(np.dstack((ra_fp,dec_fp))[0], closed=True)
        inside = [poly.get_path().contains_point(Point(ra_,dec_)) for (ra_,dec_) in zip(ra,dec)]
        ra = ra[inside]
        dec = dec[inside]

    return ra, dec
开发者ID:pmelchior,项目名称:skymapper,代码行数:20,代码来源:example1.py

示例2: overlapping_bricks

# 需要导入模块: from matplotlib.patches import Polygon [as 别名]
# 或者: from matplotlib.patches.Polygon import get_path [as 别名]
    def overlapping_bricks(self, candidates, map_petals=False):
        """Convert a list of potentially overlapping bricks into actual overlaps.

        Parameters
        ----------
        candidates : :class:`list`
            A list of candidate bricks.
        map_petals : bool, optional
            If ``True`` a map of petal number to a list of overlapping bricks
            is returned.

        Returns
        -------
        :class:`list`
            A list of Polygon objects.
        """
        petals = self.petals()
        petal2brick = dict()
        bricks = list()
        for b in candidates:
            b_ra1, b_ra2 = self.brick_offset(b)
            brick_corners = np.array([[b_ra1, b.dec1],
                                      [b_ra2, b.dec1],
                                      [b_ra2, b.dec2],
                                      [b_ra1, b.dec2]])
            brick = Polygon(brick_corners, closed=True, facecolor='r')
            for i, p in enumerate(petals):
                if brick.get_path().intersects_path(p.get_path()):
                    brick.set_facecolor('g')
                    if i in petal2brick:
                        petal2brick[i].append(b.id)
                    else:
                        petal2brick[i] = [b.id]
            bricks.append(brick)
        if map_petals:
            return petal2brick
        return bricks
开发者ID:rstaten,项目名称:desispec,代码行数:39,代码来源:database.py

示例3: MaskDrawer

# 需要导入模块: from matplotlib.patches import Polygon [as 别名]
# 或者: from matplotlib.patches.Polygon import get_path [as 别名]

#.........这里部分代码省略.........

    def get_ind_under_point(self, event):
        'get the index of the vertex under point if within epsilon tolerance'

        # display coords
        xy = np.asarray(self.poly.xy)
        xyt = self.poly.get_transform().transform(xy)
        xt, yt = xyt[:, 0], xyt[:, 1]
        d = np.sqrt((xt-event.x)**2 + (yt-event.y)**2)
        indseq = np.nonzero(np.equal(d, np.amin(d)))[0]
        ind = indseq[0]

        if d[ind]>=self.epsilon:
            ind = None

        return ind

    def button_press_callback(self, event):
        'whenever a mouse button is pressed'
        if not self.showverts: return
        if event.inaxes==None: return
        if event.button != 1: return
        self._ind = self.get_ind_under_point(event)

    def button_release_callback(self, event):
        'whenever a mouse button is released'
        if not self.showverts: return
        if event.button != 1: return
        self._ind = None

    def key_press_callback(self, event):
        'whenever a key is pressed'
        if not event.inaxes: return
        if event.key=='t':
            self.showverts = not self.showverts
            self.line.set_visible(self.showverts)
            if not self.showverts: self._ind = None
        elif event.key=='d':
            ind = self.get_ind_under_point(event)
            if ind is not None:
                self.poly.xy = [tup for i,tup in enumerate(self.poly.xy) if i!=ind]
                self.line.set_data(zip(*self.poly.xy))
        elif event.key=='i':
            xys = self.poly.get_transform().transform(self.poly.xy)
            p = event.x, event.y # display coords
            for i in range(len(xys)-1):
                s0 = xys[i]
                s1 = xys[i+1]
                d = dist_point_to_segment(p, s0, s1)
                if d<=self.epsilon:
                    self.poly.xy = np.array(
                        list(self.poly.xy[:i]) +
                        [(event.xdata, event.ydata)] +
                        list(self.poly.xy[i:]))
                    self.line.set_data(zip(*self.poly.xy))
                    break
                    
        elif event.key=='n':
            """ Flips the region inside out of the polygon to be masked """
            print('Inverting the mask region')
            self.maskinvert = not self.maskinvert


        elif event.key=='c':
            """ Confirm the drawn polynomial shape and add update the mask """
            self.UpdateMask()
            #Update the imshowed image with new mask
            self.imgplot.set_data(np.ma.filled(np.ma.array(self.img,mask=self.Mask,fill_value=np.nan)))
            self.imgplot.figure.canvas.draw()

        self.canvas.draw()

    def UpdateMask(self):
        """ Updates the maks array with points insied the polygon """
        print('Updating the original Mask..')
        Path = self.poly.get_path()
        h, w = self.Mask.shape
        y, x = np.mgrid[:h,:w]
        XYpoints = np.transpose((x.ravel(), y.ravel()))
        NewMask = Path.contains_points(XYpoints)
        if self.maskinvert :
            NewMask = ~NewMask
        # Combine the two mask by taing an elemet wise or
        self.Mask = self.Mask | NewMask.reshape((h,w))

    def motion_notify_callback(self, event):
        'on mouse movement'
        if not self.showverts: return
        if self._ind is None: return
        if event.inaxes is None: return
        if event.button != 1: return
        x,y = event.xdata, event.ydata

        self.poly.xy[self._ind] = x,y
        self.line.set_data(zip(*self.poly.xy))

        self.canvas.restore_region(self.background)
        self.ax.draw_artist(self.poly)
        self.ax.draw_artist(self.line)
        self.canvas.blit(self.ax.bbox)
开发者ID:indiajoe,项目名称:HandyTools4Astronomers,代码行数:104,代码来源:DrawMask.py

示例4: get_polygon

# 需要导入模块: from matplotlib.patches import Polygon [as 别名]
# 或者: from matplotlib.patches.Polygon import get_path [as 别名]
def get_polygon(data, no_of_vert=4, xlabel=None, xticks=None, ylabel=None, yticks=None, fs=25):
    """
    Interactive function to pick a polygon out of a figure and receive the vertices of it.
    :param data:
    :type:
    
    :param no_of_vert: number of vertices, default 4, 
    :type no_of_vert: int
    """
    from sipy.util.polygon_interactor import PolygonInteractor
    from matplotlib.patches import Polygon
    
    no_of_vert = int(no_of_vert)
    # Define shape of polygon.
    try:
        x, y = xticks.max(), yticks.max() 
        xmin= -x/10.
        xmax= x/10.
        ymin= y - 3.*y/2.
        ymax= y - 3.*y/4.

    except AttributeError:
        y,x = data.shape
        xmin= -x/10.
        xmax= x/10.
        ymin= y - 3.*y/2.
        ymax= y - 3.*y/4.
        
    xs = []
    for i in range(no_of_vert):
        if i >= no_of_vert/2:
            xs.append(xmax)
        else:
            xs.append(xmin)

    ys = np.linspace(ymin, ymax, no_of_vert/2)
    ys = np.append(ys,ys[::-1]).tolist()

    poly = Polygon(list(zip(xs, ys)), animated=True, closed=False, fill=False)
    
    # Add polygon to figure.
    fig, ax = plt.subplots()
    ax.add_patch(poly)
    p = PolygonInteractor(ax, poly)
    plt.title("Pick polygon, close figure to save vertices")
    plt.xlabel(xlabel, fontsize=fs)
    plt.ylabel(ylabel, fontsize=fs)

    try:
        im = ax.imshow(abs(data), aspect='auto', extent=(xticks.min(), xticks.max(), 0, yticks.max()), interpolation='none')
    except AttributeError:
        im = ax.imshow(abs(data), aspect='auto', interpolation='none')

    cbar = fig.colorbar(im)
    cbar.ax.tick_params(labelsize=fs)
    cbar.ax.set_ylabel('R', fontsize=fs)
    mpl.rcParams['xtick.labelsize'] = fs
    mpl.rcParams['ytick.labelsize'] = fs
    ax.tick_params(axis='both', which='major', labelsize=fs)


    plt.show()      
    print("Calculate area inside chosen polygon\n")
    try:
        vertices = (poly.get_path().vertices)
        vert_tmp = []
        xticks.sort()
        yticks.sort()
        for fkvertex in vertices:
            vert_tmp.append([np.abs(xticks-fkvertex[0]).argmin(), np.abs(yticks[::-1]-fkvertex[1]).argmin()])
        vertices = np.array(vert_tmp)   
        
    except AttributeError:
        vertices = (poly.get_path().vertices).astype('int')

    indicies = convert_polygon_to_flat_index(data, vertices)
    return indicies
开发者ID:s-schneider,项目名称:FK-Toolbox,代码行数:79,代码来源:picker.py

示例5: Map

# 需要导入模块: from matplotlib.patches import Polygon [as 别名]
# 或者: from matplotlib.patches.Polygon import get_path [as 别名]

#.........这里部分代码省略.........
        return artist

    def _setEdge(self, **kwargs):
        self._dec_range = np.linspace(-90, 90, self._resolution)
        self._ra_range = np.linspace(-180, 180, self._resolution) + self.proj.ra_0

        # styling: frame needs to be on top of everything, must be transparent
        facecolor = 'None'
        zorder = 1000
        lw = kwargs.pop('lw', 0.7)
        edgecolor = kwargs.pop('edgecolor', 'k')
        # if there is facecolor: clone the polygon and put it in as bottom layer
        facecolor_ = kwargs.pop('facecolor', '#dddddd')

        # polygon of the map edge: top, left, bottom, right
        # don't draw poles if that's a single point
        lines = [self._getMeridian(self.proj.ra_0 + 180, reverse=True), self._getMeridian(self.proj.ra_0 - 180)]
        if not self.proj.poleIsPoint[-90]:
            lines.insert(1, self._getParallel(-90, reverse=True))
        if not self.proj.poleIsPoint[90]:
            lines.insert(0, self._getParallel(90))
        xy = np.concatenate(lines, axis=1).T
        self._edge = Polygon(xy, closed=True, edgecolor=edgecolor, facecolor=facecolor, lw=lw, zorder=zorder,gid="edge", **kwargs)
        self.ax.add_patch(self._edge)

        if facecolor_ is not None:
            zorder = -1000
            edgecolor = 'None'
            poly = Polygon(xy, closed=True, edgecolor=edgecolor, facecolor=facecolor_, zorder=zorder, gid="edge-background")
            self.ax.add_patch(poly)

    def contains(self, x, y):
        xy = np.dstack((x,y)).reshape(-1,2)
        return self._edge.get_path().contains_points(xy).reshape(x.shape)

    def xlim(self, left=None, right=None, **kw):
        """Get/set the map limits in x-direction"""
        if left is None and right is None:
            return (self._edge.xy[:, 0].min(), self._edge.xy[:, 0].max())
        else:
            self.ax.set_xlim(left=left, right=right, **kw)
            self._resetFrame()

    def ylim(self, bottom=None, top=None, **kw):
        """Get/set the map limits in x-direction"""
        if bottom is None and top is None:
            return (self._edge.xy[:, 1].min(), self._edge.xy[:, 1].max())
        else:
            self.ax.set_ylim(bottom=bottom, top=top, **kw)
            self._resetFrame()

    def grid(self, sep=30, parallel_fmt=degPMFormatter, meridian_fmt=deg360Formatter, dec_min=-90, dec_max=90, ra_min=-180, ra_max=180, **kwargs):
        """Set map grid / graticules

        Args:
            sep: distance between graticules in deg
            parallel_fmt: formatter for parallel labels
            meridian_fmt: formatter for meridian labels
            dec_min: minimum declination for graticules
            dec_max: maximum declination for graticules
            ra_min: minimum declination for graticules (for which reference RA=0)
            ra_max: maximum declination for graticules (for which reference RA=0)
            **kwargs: styling of `matplotlib.lines.Line2D` for the graticules
        """
        self._config['grid'] = _parseArgs(locals())
        self._dec_range = np.linspace(dec_min, dec_max, self._resolution)
开发者ID:pmelchior,项目名称:skymapper,代码行数:70,代码来源:map.py


注:本文中的matplotlib.patches.Polygon.get_path方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。