Python matplotlib.pyplot 模块,Polygon() 实例源码

我们从Python开源项目中,提取了以下22个代码示例,用于说明如何使用matplotlib.pyplot.Polygon()

项目:OpenTDA    作者:outlace    | 项目源码 | 文件源码
def drawComplex(origData, ripsComplex, axes=[-6,8,-6,6]):
  plt.clf()
  plt.axis(axes)
  plt.scatter(origData[:,0],origData[:,1]) #plotting just for clarity
  for i, txt in enumerate(origData):
      plt.annotate(i, (origData[i][0]+0.05, origData[i][1])) #add labels

  #add lines for edges
  for edge in [e for e in ripsComplex if len(e)==2]:
      #print(edge)
      pt1,pt2 = [origData[pt] for pt in [n for n in edge]]
      #plt.gca().add_line(plt.Line2D(pt1,pt2))
      line = plt.Polygon([pt1,pt2], closed=None, fill=None, edgecolor='r')
      plt.gca().add_line(line)

  #add triangles
  for triangle in [t for t in ripsComplex if len(t)==3]:
      pt1,pt2,pt3 = [origData[pt] for pt in [n for n in triangle]]
      line = plt.Polygon([pt1,pt2,pt3], closed=False, color="blue",alpha=0.3, fill=True, edgecolor=None)
      plt.gca().add_line(line)
  plt.show()
项目:OpenTDA    作者:outlace    | 项目源码 | 文件源码
def drawComplex(data, ph, axes=[-6, 8, -6, 6]):
    plt.clf()
    plt.axis(axes)  # axes = [x1, x2, y1, y2]
    plt.scatter(data[:, 0], data[:, 1])  # plotting just for clarity
    for i, txt in enumerate(data):
        plt.annotate(i, (data[i][0] + 0.05, data[i][1]))  # add labels

    # add lines for edges
    for edge in [e for e in ph.ripsComplex if len(e) == 2]:
        # print(edge)
        pt1, pt2 = [data[pt] for pt in [n for n in edge]]
        # plt.gca().add_line(plt.Line2D(pt1,pt2))
        line = plt.Polygon([pt1, pt2], closed=None, fill=None, edgecolor='r')
        plt.gca().add_line(line)

    # add triangles
    for triangle in [t for t in ph.ripsComplex if len(t) == 3]:
        pt1, pt2, pt3 = [data[pt] for pt in [n for n in triangle]]
        line = plt.Polygon([pt1, pt2, pt3], closed=False,
                           color="blue", alpha=0.3, fill=True, edgecolor=None)
        plt.gca().add_line(line)
    plt.show()
项目:OpenTDA    作者:outlace    | 项目源码 | 文件源码
def drawComplex(origData, ripsComplex, axes=[-6,8,-6,6]):
  plt.clf()
  plt.axis(axes)
  plt.scatter(origData[:,0],origData[:,1]) #plotting just for clarity
  for i, txt in enumerate(origData):
      plt.annotate(i, (origData[i][0]+0.05, origData[i][1])) #add labels

  #add lines for edges
  for edge in [e for e in ripsComplex if len(e)==2]:
      #print(edge)
      pt1,pt2 = [origData[pt] for pt in [n for n in edge]]
      #plt.gca().add_line(plt.Line2D(pt1,pt2))
      line = plt.Polygon([pt1,pt2], closed=None, fill=None, edgecolor='r')
      plt.gca().add_line(line)

  #add triangles
  for triangle in [t for t in ripsComplex if len(t)==3]:
      pt1,pt2,pt3 = [origData[pt] for pt in [n for n in triangle]]
      line = plt.Polygon([pt1,pt2,pt3], closed=False, color="blue",alpha=0.3, fill=True, edgecolor=None)
      plt.gca().add_line(line)
  plt.show()
项目:geonum    作者:jgliss    | 项目源码 | 文件源码
def add_polygon_2d(self, points=[], poly_id="undefined", ax=None, **kwargs):
        """Add a polygon specified by list of input points

        :param list points: list with :class:`GeoPoint` objects
        :param str poly_id: string ID of this object (e.g. for 
            deletion, default: "undefined")
        """
        if ax is None:
            ax = self.ax
        if not "label" in kwargs:
            kwargs["label"] = poly_id
        coords=[]
        for p in points:
            try:
                coords.append(self(p.longitude, p.latitude))
            except Exception as e:
                print "Failed to add one point to poly: " + repr(e)
        polygon = Polygon(coords, **kwargs)
        ax.add_patch(polygon)
项目:discretize    作者:simpeg    | 项目源码 | 文件源码
def plotImage(
        self, I, ax=None, showIt=False, grid=False, clim=None
    ):
        if self.dim == 3:
            raise NotImplementedError('This is not yet done!')

        import matplotlib.pyplot as plt
        import matplotlib
        from mpl_toolkits.mplot3d import Axes3D
        import matplotlib.colors as colors
        import matplotlib.cm as cmx

        if ax is None:
            ax = plt.subplot(111)

        jet = cm = plt.get_cmap('jet')
        cNorm  = colors.Normalize(
            vmin=I.min() if clim is None else clim[0],
            vmax=I.max() if clim is None else clim[1])

        scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)
        # ax.set_xlim((self.x0[0], self.h[0].sum()))
        # ax.set_ylim((self.x0[1], self.h[1].sum()))

        Nx = self.r(self.gridN[:, 0], 'N', 'N', 'M')
        Ny = self.r(self.gridN[:, 1], 'N', 'N', 'M')
        cell = self.r(I, 'CC', 'CC', 'M')

        for ii in range(self.nCx):
            for jj in range(self.nCy):
                I = [ii, ii+1, ii+1, ii]
                J = [jj, jj, jj+1, jj+1]
                ax.add_patch(plt.Polygon(np.c_[Nx[I, J], Ny[I, J]], facecolor=scalarMap.to_rgba(cell[ii, jj]), edgecolor='k' if grid else 'none'))

        scalarMap._A = []  # http://stackoverflow.com/questions/8342549/matplotlib-add-colorbar-to-a-sequence-of-line-plots
        ax.set_xlabel('x')
        ax.set_ylabel('y')
        if showIt:
            plt.show()
        return [scalarMap]
项目:xdesign    作者:tomography    | 项目源码 | 文件源码
def contains(self, other):
        """Return whether the Circle contains the other.

        Return one boolean for all geometric entities. Return an array of
        boolean for array input.
        """
        if isinstance(other, Point):
            x = other._x
        elif isinstance(other, np.ndarray):
            x = other
        elif isinstance(other, Circle):
            return (other.center.distance(self.center) + other.radius
                    <= self.radius)
        elif isinstance(other, Polygon):
            x = _points_to_array(other.vertices)
            return np.all(self.contains(x))
        elif isinstance(other, Mesh):
            for face in other.faces:
                if not self.contains(face):
                    return False
            return True
        else:
            raise NotImplementedError("Circle.contains() not implemented for" +
                                      " {}".format(type(other)))

        return np.sum((x - self.center._x)**2, axis=1) <= self.radius**2
项目:xdesign    作者:tomography    | 项目源码 | 文件源码
def __init__(self, vertices):
        for v in vertices:
            if not isinstance(v, Point):
                raise TypeError("vertices must be of type Point.")
        super(Polygon, self).__init__()
        self.vertices = vertices
        self._dim = vertices[0].dim
项目:xdesign    作者:tomography    | 项目源码 | 文件源码
def __str__(self):
        return "{}({})".format(type(self).__name__, str(self.numpy))
    # return "Polygon(%s" % ', '.join([str(n) for n in self.vertices]) + ")"
项目:xdesign    作者:tomography    | 项目源码 | 文件源码
def area(self):
        """Returns the area of the Polygon."""
        raise NotImplementedError
项目:xdesign    作者:tomography    | 项目源码 | 文件源码
def perimeter(self):
        """Return the perimeter of the Polygon."""
        perimeter = 0
        verts = self.vertices
        points = verts + [verts[0]]
        for m in range(self.numverts):
            perimeter += points[m].distance(points[m + 1])
        return perimeter
项目:xdesign    作者:tomography    | 项目源码 | 文件源码
def patch(self):
        """Returns a matplotlib patch."""
        return plt.Polygon(self.numpy)
项目:xdesign    作者:tomography    | 项目源码 | 文件源码
def rotate(self, theta, point=None, axis=None):
        """Rotates the Polygon around an axis which passes through a point by
        theta radians."""
        for v in self.vertices:
            v.rotate(theta, point, axis)

        if 'half_space' in self.__dict__:
            if point is None:
                d = 0
            else:
                d = point._x
            self.half_space = self.half_space.translation(-d)
            self.half_space = self.half_space.rotation(0, 1, theta)
            self.half_space = self.half_space.translation(d)
项目:xdesign    作者:tomography    | 项目源码 | 文件源码
def edges(self):
        """Return a list of lines connecting the points of the Polygon."""
        edges = []

        for i in range(self.numverts):
            edges.append(Line(self.vertices[i],
                              self.vertices[(i+1) % self.numverts]))

        return edges
项目:xdesign    作者:tomography    | 项目源码 | 文件源码
def contains(self, other):
        """Return whether this Polygon contains the other."""

        border = Path(self.numpy)

        if isinstance(other, Point):
            x = other._x
        elif isinstance(other, np.ndarray):
            x = other
        elif isinstance(other, Polygon):
            x = _points_to_array(other.vertices)
            return np.all(border.contains_points(x, radius=1e-32))
        elif isinstance(other, Circle):
            if self.contains(other.center):
                for edge in self.edges:
                    if other.center.distance(edge) < other.radius:
                        return False
                return True
            return False
        elif isinstance(other, Mesh):
            for face in other.faces:
                if not self.contains(face):
                    return False
            return True
        else:
            raise NotImplementedError("Polygon.contains() not implemented " +
                                      "for this class.")

        border = Path(self.numpy)
        return border.contains_points(np.atleast_2d(x), radius=1e-32)
项目:xdesign    作者:tomography    | 项目源码 | 文件源码
def append(self, t):
        """Add a triangle to the mesh."""
        assert(isinstance(t, Polygon))
        self.population += 1
        # self.center = ((self.center * self.area + t.center * t.area) /
        #                (self.area + t.area))
        self.area += t.area
        for v in t.vertices:
            self.radius = max(self.radius, self.center.distance(v))
        self.faces.append(t)
项目:lomap    作者:wasserfeder    | 项目源码 | 文件源码
def define_local(self):
        """Defines polygons for locally sensed requests
        """
        local = self.env.local_reqs
        self.local_polygons = dict()
        for cell in local.iterkeys():
            color = local[cell]['color']
            vertices = self.get_vertices_of_cell(cell)
            self.local_polygons[cell] = plt.Polygon(vertices, facecolor=color, edgecolor=color, zorder=0)
项目:chainer-spatial-transformer-networks    作者:hvy    | 项目源码 | 文件源码
def __call__(self, trainer):
        x = self.x
        dpi = self.dpi
        updater = trainer.updater

        filename = os.path.join(trainer.out, '{0:08d}.png'.format(
                                updater.iteration))

        # Inference to update model internal grid
        x = updater.converter(x, updater.device)
        model = updater.get_optimizer('main').target.predictor
        model(x)

        # Get grids from previous inference
        grid = model.st.grid.data
        if isinstance(grid, cuda.ndarray):
            grid = cuda.to_cpu(grid)
        if isinstance(x, cuda.ndarray):
            x = cuda.to_cpu(x)

        n, c, w, h = x.shape
        x_plots = math.ceil(math.sqrt(n))
        y_plots = x_plots if n % x_plots == 0 else x_plots - 1
        plt.figure(figsize=(w*x_plots/dpi, h*y_plots/dpi), dpi=dpi)

        for i, im in enumerate(x):
            plt.subplot(y_plots, x_plots, i+1)

            if c == 1:
                plt.imshow(im[0])
            else:
                plt.imshow(im.transpose((1, 2, 0)))

            plt.axis('off')
            plt.gca().set_xticks([])
            plt.gca().set_yticks([])
            plt.gray()

            # Get the 4 corners of the transformation grid to draw a box
            g = grid[i]
            vs = np.empty((4, 2), dtype=np.float32)
            vs[0] = g[:, 0, 0]
            vs[1] = g[:, 0, w-1]
            vs[2] = g[:, h-1, w-1]
            vs[3] = g[:, h-1, 0]
            vs += 1  # [-1, 1] -> [0, 2]
            vs /= 2
            vs[:, 0] *= h
            vs[:, 1] *= w

            bbox = plt.Polygon(vs, True, color='r', fill=False, linewidth=0.8,
                               alpha=0.8)
            plt.gca().add_patch(bbox)
            bbox.set_clip_on(False)  # Allow drawing outside axes

            plt.subplots_adjust(left=None, bottom=None, right=None, top=None,
                                wspace=0.2, hspace=0.2)

        plt.savefig(filename, dpi=dpi*2, facecolor='black')
        plt.clf()
        plt.close()
项目:em_examples    作者:geoscixyz    | 项目源码 | 文件源码
def plotProfileTxRxSphere(Ax,xtx,ztx,x0,z0,a,xrx,zrx,X,Z,orient):

    FS = 22

    phi = np.linspace(0,2*np.pi,41)
    psi = np.linspace(0,np.pi,21)

    if orient == 'x':
        Xtx = xtx + 0.5*np.cos(phi)
        Ztx = ztx + 2*np.sin(phi)
        Xrx = xrx + 0.5*np.cos(phi)
        Zrx = zrx + 2*np.sin(phi)
    elif orient == 'z':
        Xtx = xtx + 2*np.cos(phi)
        Ztx = ztx + 0.5*np.sin(phi)
        Xrx = xrx + 2*np.cos(phi)
        Zrx = zrx + 0.5*np.sin(phi)

    # Xs = x0 + a*np.cos(psi)
    # Zs1 = z0 + a*np.sin(psi)
    # Zs2 = z0 - a*np.sin(psi)

    XS = x0 + a*np.cos(phi)
    ZS = z0 + a*np.sin(phi)

    Ax.fill_between(np.array([np.min(X),np.max(X)]),np.array([0.,0.]),np.array([np.max(Z),np.max(Z)]),facecolor=(0.9,0.9,0.9))
    Ax.fill_between(np.array([np.min(X),np.max(X)]),np.array([0.,0.]),np.array([np.min(Z),np.min(Z)]),facecolor=(0.6,0.6,0.6),linewidth=2)
    # Ax.fill_between(Xs,Zs1,Zs2,facecolor=(0.4,0.4,0.4),linewidth=4)

    polyObj = plt.Polygon(np.c_[XS,ZS],closed=True,facecolor=((0.4,0.4,0.4)),edgecolor='k',linewidth=2)
    Ax.add_patch(polyObj)

    Ax.plot(Xtx,Ztx,'k',linewidth=4)
    Ax.plot(Xrx,Zrx,'k',linewidth=4)
    # Ax.plot(x0+a*np.cos(phi),z0+a*np.sin(phi),'k',linewidth=2)

    Ax.set_xbound(np.min(X),np.max(X))
    Ax.set_ybound(np.min(Z),np.max(Z))

    Ax.text(xtx-4,ztx+2,'$\mathbf{Tx}$',fontsize=FS)
    Ax.text(xrx,zrx+2,'$\mathbf{Rx}$',fontsize=FS)

    return Ax
项目:em_examples    作者:geoscixyz    | 项目源码 | 文件源码
def fcn_FDEM_Widget(I,a1,a2,xRx,zRx,azm,logR,logL,logf):

    R = 10**logR
    L = 10**logL
    f = 10**logf

    FS = 20

    xmin, xmax, dx, zmin, zmax, dz = -20., 20., 0.5, -20., 20., 0.5
    X,Z = np.mgrid[xmin:xmax+dx:dx, zmin:zmax+dz:dz]
    X = np.transpose(X)
    Z = np.transpose(Z)

    Obj = IndEx(I,a1,a2,xRx,zRx,azm,R,L)
    t_range = (4/f)*np.linspace(0,1,num=100)

    Obj.calc_PrimaryLoop()  # Calculate primary field at loop center
    Bpx,Bpz,Babs = Obj.calc_PrimaryRegion(X,Z)  # Calculates regional primary field
    EMF,Isf = Obj.calc_IndCurrent_FD_spectrum()
    Ire,Iim,Is,phi = Obj.calc_IndCurrent_cos_range(f,t_range)

    fig1 = plt.figure(figsize=(13,13))
    Ax11 = fig1.add_axes([0,0.62,0.46,0.37])
    Ax12 = fig1.add_axes([0.6,0.63,0.40,0.37])
    Ax21 = fig1.add_axes([0.1,0.31,0.8,0.25])
    Ax22 = fig1.add_axes([0.1,0,0.8,0.25])

    Ax11,Cplot = Obj.plot_PrimaryRegion(X,Z,Bpx,Bpz,Babs,Ax11)
    polyArray = np.array([[-20,10],[4,10],[4,20],[-20,20]])
    polyObj = plt.Polygon(polyArray,facecolor=((1,1,1)),edgecolor='k')
    Ax11.add_patch(polyObj)
    Ax12 = Obj.plot_InducedCurrent_FD(Ax12,Isf,f)
    Ax21,Ax21b,Ax22 = Obj.plot_InducedCurrent_cos(Ax21,Ax22,Ire,Iim,Is,phi,f,t_range)

    Babs_str = '{:.2e}'.format(1e9*Obj.Bpabs)
    Bn_str   = '{:.2e}'.format(1e9*Obj.Bpn)
    A_str    = '{:.2f}'.format(Obj.Area)

    Ax11.text(-19,17,'$\mathbf{|B_p|}$ = '+Babs_str+' nT',fontsize=FS,color='k')
    Ax11.text(-19,14,'$\mathbf{|B_n|}$ = '+Bn_str+' nT',fontsize=FS,color='k')
    Ax11.text(-19,11,'Area = '+A_str+' m$^2$',fontsize=FS,color='k')

    #f_str    = '{:.2e}'.format(f)
    #EMF_str  = '{:.2e}j'.format(EMFi.imag)
    #Ax12.text(-2.9,-1.0,'f = '+f_str+' Hz',fontsize=FS)
    #Ax12.text(-2.9,-1.4,'EMF = '+EMF_str+' V',fontsize=FS)

    plt.show(fig1)
项目:em_examples    作者:geoscixyz    | 项目源码 | 文件源码
def fcn_TDEM_Widget(I,a1,a2,xRx,zRx,azm,logR,logL,logt):

    R = 10**logR
    L = 10**logL
    t = 10**logt

    FS = 20

    xmin, xmax, dx, zmin, zmax, dz = -20., 20., 0.5, -20., 20., 0.5
    X,Z = np.mgrid[xmin:xmax+dx:dx, zmin:zmax+dz:dz]
    X = np.transpose(X)
    Z = np.transpose(Z)

    Obj = IndEx(I,a1,a2,xRx,zRx,azm,R,L)

    Obj.calc_PrimaryLoop()
    Bpx,Bpz,Babs = Obj.calc_PrimaryRegion(X,Z)
    V,Is = Obj.calc_IndCurrent_TD_offtime()
    EMFi,Isi = Obj.calc_IndCurrent_TD_i(t)

    fig1 = plt.figure(figsize=(13,5.8))
    Ax11 = fig1.add_axes([0,0,0.48,0.89])
    Ax12 = fig1.add_axes([0.61,0,0.40,0.89])

    Ax11,Cplot = Obj.plot_PrimaryRegion(X,Z,Bpx,Bpz,Babs,Ax11)
    polyArray = np.array([[-20,10],[4,10],[4,20],[-20,20]])
    polyObj = plt.Polygon(polyArray,facecolor=((1,1,1)),edgecolor='k')
    Ax11.add_patch(polyObj)
    Ax12 = Obj.plot_InducedCurrent_TD(Ax12,Is,t,EMFi,Isi)

    Babs_str = '{:.2e}'.format(1e9*Obj.Bpabs)
    Bn_str   = '{:.2e}'.format(1e9*Obj.Bpn)
    A_str    = '{:.2f}'.format(Obj.Area)

    Ax11.text(-19,17,'$\mathbf{|B_p|}$ = '+Babs_str+' nT',fontsize=FS,color='k')
    Ax11.text(-19,14,'$\mathbf{|B_n|}$ = '+Bn_str+' nT',fontsize=FS,color='k')
    Ax11.text(-19,11,'Area = '+A_str+' m$^2$',fontsize=FS,color='k')

    plt.show(fig1)


############################################
#   DEFINE CLASS
############################################
项目:sentisignal    作者:jonathanmanfield    | 项目源码 | 文件源码
def _radar_factory(num_vars):
    theta = 2*np.pi * np.linspace(0, 1-1./num_vars, num_vars)
    theta += np.pi/2

    def unit_poly_verts(theta):
        x0, y0, r = [0.5] * 3
        verts = [(r*np.cos(t) + x0, r*np.sin(t) + y0) for t in theta]
        return verts

    class RadarAxes(PolarAxes):
        name = 'radar'
        RESOLUTION = 1

        def fill(self, *args, **kwargs):
            closed = kwargs.pop('closed', True)
            return super(RadarAxes, self).fill(closed=closed, *args, **kwargs)

        def plot(self, *args, **kwargs):
            lines = super(RadarAxes, self).plot(*args, **kwargs)
            for line in lines:
                self._close_line(line)

        def _close_line(self, line):
            x, y = line.get_data()
            if x[0] != x[-1]:
                x = np.concatenate((x, [x[0]]))
                y = np.concatenate((y, [y[0]]))
                line.set_data(x, y)

        def set_varlabels(self, labels):
            self.set_thetagrids(theta * 180/np.pi, labels)

        def _gen_axes_patch(self):
            verts = unit_poly_verts(theta)
            return plt.Polygon(verts, closed=True, edgecolor='k')

        def _gen_axes_spines(self):
            spine_type = 'circle'
            verts = unit_poly_verts(theta)
            verts.append(verts[0])
            path = Path(verts)
            spine = Spine(self, spine_type, path)
            spine.set_transform(self.transAxes)
            return {'polar': spine}

    register_projection(RadarAxes)
    return theta
项目:FRCNN_git    作者:runa91    | 项目源码 | 文件源码
def vis_detections(image_name, im, class_name, dets, ax, angles, thresh=0.5):
    """Draw detected bounding boxes."""
    inds = np.where(dets[:, -1] >= thresh)[0]
    if len(inds) == 0:
        return

    for i in inds:
        bbox = dets[i, :4]
        score = dets[i, -1]
        angle = angles[i,:]

        c_orig = np.zeros((4, 2))
        c_orig[0, :] = [bbox[2], bbox[1]]
        c_orig[1, :] = [bbox[2], bbox[3]]
        c_orig[2, :] = [bbox[0], bbox[3]]
        c_orig[3, :] = [bbox[0], bbox[1]] 

        angle = - angle     # that's what I need to do in order to get correct results
        print(angle)
        sin_a = np.sin(angle)
        cos_a = np.cos(angle)

        roi_mid_w = (bbox[2] + bbox[0])/2
        roi_mid_h = (bbox[3] + bbox[1])/2

        # corner positions for the rotated rectangle
        c_rot = np.zeros((4, 2))

        for ind in range(4):
            w = c_orig[ind,0]
            h = c_orig[ind,1]
            w_from_mid = w - roi_mid_w;
            h_from_mid = h - roi_mid_h;
            w_from_mid_rot = cos_a*w_from_mid - sin_a*h_from_mid
            h_from_mid_rot = sin_a*w_from_mid + cos_a*h_from_mid
            c_rot[ind, 0] = w_from_mid_rot + roi_mid_w
            c_rot[ind, 1] = h_from_mid_rot + roi_mid_h

        ax.add_patch(
            plt.Polygon(c_rot, True, alpha=0.4,edgecolor='red', linewidth=2)
        )

        """ax.text((bbox[0]+bbox[2])/2, (bbox[1]+bbox[3])/2-10,     #bbox[0], bbox[1] - 2
                '{:s} {:.3f}'.format(class_name, score),
                bbox=dict(facecolor='blue', alpha=0.5),
                fontsize=14, color='white')"""
        """ax.text((bbox[0]+bbox[2])/2 - 20, (bbox[1]+bbox[3])/2-2,     #bbox[0], bbox[1] - 2
                '{:.3f}'.format(score),
                bbox=dict(facecolor='blue', alpha=0.1),
                fontsize=18, color='white')"""

    ax.set_title(('image{}:    {} detections with '
                  'p({} | box) >= {:.3f}').format(image_name, class_name, class_name,
                                                  thresh),
                  fontsize=14)
    plt.axis('off')
    plt.tight_layout()
    plt.draw()