Python matplotlib.pyplot.Polygon() Examples

The following are 16 code examples of matplotlib.pyplot.Polygon(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib.pyplot , or try the search function .
Example #1
Source File: SimplicialComplex.py    From OpenTDA with Apache License 2.0 8 votes vote down vote up
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() 
Example #2
Source File: FilteredSimplicialComplex.py    From OpenTDA with Apache License 2.0 8 votes vote down vote up
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() 
Example #3
Source File: plotting.py    From OpenTDA with Apache License 2.0 6 votes vote down vote up
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() 
Example #4
Source File: paper_synthetic2.py    From defragTrees with MIT License 6 votes vote down vote up
def plotTZ(filename=None):
    t = np.linspace(0, 1, 101)
    z = 0.25 + 0.5 / (1 + np.exp(- 20 * (t - 0.5))) + 0.05 * np.cos(t * 2 * np.pi)
    cmap = cm.get_cmap('cool')
    fig, (ax1, ax2) = plt.subplots(1, 2, gridspec_kw = {'width_ratios':[19, 1]})
    poly1 = [[0, 0]]
    poly1.extend([[t[i], z[i]] for i in range(t.size)])
    poly1.extend([[1, 0], [0, 0]])
    poly2 = [[0, 1]]
    poly2.extend([[t[i], z[i]] for i in range(t.size)])
    poly2.extend([[1, 1], [0, 1]])
    poly1 = plt.Polygon(poly1,fc=cmap(0.0))
    poly2 = plt.Polygon(poly2,fc=cmap(1.0))
    ax1.add_patch(poly1)
    ax1.add_patch(poly2)
    ax1.set_xlabel('x1', size=22)
    ax1.set_ylabel('x2', size=22)
    ax1.set_title('True Data', size=28)
    colorbar.ColorbarBase(ax2, cmap=cmap, format='%.1f')
    ax2.set_ylabel('Output y', size=22)
    plt.show()
    if not filename is None:
        plt.savefig(filename, format="pdf", bbox_inches="tight")
        plt.close() 
Example #5
Source File: ssd_utils.py    From aiexamples with Apache License 2.0 6 votes vote down vote up
def plot_assignement(self, map_idx):
        ax = plt.gca()
        im = plt.gci()
        img_h, img_w = image_size = im.get_size()
        
        # ground truth
        boxes = self.gt_boxes
        boxes_x = (boxes[:,0] + boxes[:,2]) / 2. * img_h
        boxes_y = (boxes[:,1] + boxes[:,3]) / 2. * img_w
        for box in boxes:
            xy_rec = to_rec(box[:4], image_size)
            ax.add_patch(plt.Polygon(xy_rec, fill=False, edgecolor='b', linewidth=2))
        plt.plot(boxes_x, boxes_y, 'bo',  markersize=6)
        
        # prior boxes
        for idx, box_idx in self.match_indices.items():
            if idx >= self.map_offsets[map_idx] and idx < self.map_offsets[map_idx+1]:
                x, y = self.priors_xy[idx]
                w, h = self.priors_wh[idx]
                plt.plot(x, y, 'ro',  markersize=4)
                plt.plot([x, boxes_x[box_idx]], [y, boxes_y[box_idx]], '-r', linewidth=1)
                ax.add_patch(plt.Rectangle((x-w/2, y-h/2), w+1, h+1, 
                        fill=False, edgecolor='y', linewidth=2)) 
Example #6
Source File: ssd_viz.py    From aiexamples with Apache License 2.0 6 votes vote down vote up
def plot_box(box, box_format='xywh', color='r', linewidth=1, normalized=False, vertices=False):
    if box_format == 'xywh': # opencv
        xmin, ymin, w, h = box
        xmax, ymax = xmin + w, ymin + h
    elif box_format == 'xyxy':
        xmin, ymin, xmax, ymax = box
    if box_format == 'polygon':
        xy_rec = np.reshape(box, (-1, 2))
    else:
        xy_rec = np.array([[xmin, ymin], [xmax, ymin], [xmax, ymax], [xmin, ymax]])
    if normalized:
        im = plt.gci()
        xy_rec = xy_rec * np.tile(im.get_size(), (4,1))
    ax = plt.gca()
    ax.add_patch(plt.Polygon(xy_rec, fill=False, edgecolor=color, linewidth=linewidth))
    if vertices:
        c = 'rgby'
        for i in range(4):
            plt.plot(xy_rec[i,0],xy_rec[i,1], c[i], marker='o', markersize=4) 
Example #7
Source File: evaluation.py    From EAST with MIT License 6 votes vote down vote up
def polygon_iou(list1, list2):
    """
    Intersection over union between two shapely polygons.
    """
    polygon_points1 = np.array(list1).reshape(4, 2)
    poly1 = Polygon(polygon_points1).convex_hull
    polygon_points2 = np.array(list2).reshape(4, 2)
    poly2 = Polygon(polygon_points2).convex_hull
    union_poly = np.concatenate((polygon_points1, polygon_points2))
    if not poly1.intersects(poly2):  # this test is fast and can accelerate calculation
        iou = 0
    else:
        try:
            inter_area = poly1.intersection(poly2).area
            # union_area = poly1.area + poly2.area - inter_area
            union_area = MultiPoint(union_poly).convex_hull.area
            if union_area == 0:
                return 0
            iou = float(inter_area) / union_area
        except shapely.geos.TopologicalError:
            print('shapely.geos.TopologicalError occured, iou set to 0')
            iou = 0
    return iou 
Example #8
Source File: mpl.py    From anaStruct with GNU General Public License v3.0 6 votes vote down vote up
def plot_result(
        self,
        axis_values,
        force_1=None,
        force_2=None,
        digits=2,
        node_results=True,
        fill_polygon=True,
        color=0
    ):
        if fill_polygon:
            rec = plt.Polygon(
                np.vstack(axis_values).T, color="C{}".format(color), alpha=0.3
            )
            self.one_fig.add_patch(rec)
        # plot force
        x_val = axis_values[0]
        y_val = axis_values[1]

        self.one_fig.plot(x_val, y_val, color="C{}".format(color))

        if node_results:
            self._add_node_values(x_val, y_val, force_1, force_2, digits) 
Example #9
Source File: edgenode.py    From viznet with MIT License 5 votes vote down vote up
def mass_center(self):
        '''mass center of a node'''
        shape = self.brush.style[1]
        if isinstance(self.obj, (plt.Polygon, patches.PathPatch)):
            pos = self._clean_path.mean(axis=0)
        else:
            pos = self.position
        return Pin(pos) 
Example #10
Source File: edgenode.py    From viznet with MIT License 5 votes vote down vote up
def height(self):
        shape = self.brush.style[1]
        if isinstance(self.obj, plt.Circle):
            return self.obj.radius * 2
        elif isinstance(self.obj, plt.Rectangle):
            return self.obj.get_height()
        elif isinstance(self.obj, patches.FancyBboxPatch):
            return self.obj.get_height() + 2*self.obj.get_boxstyle().pad
        elif isinstance(self.obj, (plt.Polygon, patches.PathPatch)):
            y = self.path[:,1]
            return y.max() - y.min()
        else:
            raise 
Example #11
Source File: edgenode.py    From viznet with MIT License 5 votes vote down vote up
def width(self):
        shape = self.brush.style[1]
        if isinstance(self.obj, plt.Circle):
            return self.obj.radius * 2
        elif isinstance(self.obj, plt.Rectangle):
            return self.obj.get_width()
        elif isinstance(self.obj, patches.FancyBboxPatch):
            return self.obj.get_width() + 2*self.obj.get_boxstyle().pad
        elif isinstance(self.obj, (plt.Polygon, patches.PathPatch)):
            x = self.path[:,0]
            return x.max() - x.min()
        else:
            raise 
Example #12
Source File: ssd_utils.py    From aiexamples with Apache License 2.0 5 votes vote down vote up
def plot_results(self, results=None, classes=None, show_labels=True, gt_data=None, confidence_threshold=None):
        if results is None:
            results = self.results
        if confidence_threshold is not None:
            mask = results[:, 4] > confidence_threshold
            results = results[mask]
        if classes is not None:
            colors = plt.cm.hsv(np.linspace(0, 1, len(classes)+1)).tolist()
        ax = plt.gca()
        im = plt.gci()
        image_size = im.get_size()
        
        # draw ground truth
        if gt_data is not None:
            for box in gt_data:
                label = np.nonzero(box[4:])[0][0]+1
                color = 'g' if classes == None else colors[label]
                xy_rec = to_rec(box[:4], image_size)
                ax.add_patch(plt.Polygon(xy_rec, fill=True, color=color, linewidth=1, alpha=0.3))
        
        # draw prediction
        for r in results:
            label = int(r[5])
            confidence = r[4]
            color = 'r' if classes == None else colors[label]
            xy_rec = to_rec(r[:4], image_size)
            ax.add_patch(plt.Polygon(xy_rec, fill=False, edgecolor=color, linewidth=2))
            if show_labels:
                label_name = label if classes == None else classes[label]
                xmin, ymin = xy_rec[0]
                display_txt = '%0.2f, %s' % (confidence, label_name)        
                ax.text(xmin, ymin, display_txt, bbox={'facecolor':color, 'alpha':0.5}) 
Example #13
Source File: ssd_data.py    From aiexamples with Apache License 2.0 5 votes vote down vote up
def plot_gt(self, boxes, show_labels=True):
        # if parameter is sample index
        if type(boxes) in [int]:
            boxes = self.data[boxes]
        
        ax = plt.gca()
        im = plt.gci()
        w, h = im.get_size()
        
        for box in boxes:
            class_idx = int(box[-1])
            color = self.colors[class_idx]
            is_polygon = len(box)-1 > 4
            if is_polygon:
                xy = box[:-1].reshape((-1,2))
            else:
                xmin, ymin, xmax, ymax = box[:4]
                xy = np.array([[xmin, ymin], [xmax, ymin], [xmax, ymax], [xmin, ymax]])
            xy = xy * [h, w]
            ax.add_patch(plt.Polygon(xy, fill=False, edgecolor=color, linewidth=1))
            if show_labels:
                label_name = self.classes[class_idx]
                if is_polygon:
                    angle = np.arctan((xy[1,0]-xy[0,0])/(xy[1,1]-xy[0,1]+eps))
                    if angle < 0:
                        angle += np.pi
                    angle = angle/np.pi*180-90
                else:
                    angle = 0                
                ax.text(xy[0,0], xy[0,1], label_name, bbox={'facecolor':color, 'alpha':0.5}, rotation=angle) 
Example #14
Source File: evaluation.py    From EAST with MIT License 5 votes vote down vote up
def polygon_from_list(line):
    """
    Create a shapely polygon object from gt or dt line.
    """
    # polygon_points = [float(o) for o in line.split(',')[:8]]
    polygon_points = np.array(line).reshape(4, 2)
    polygon = Polygon(polygon_points).convex_hull
    return polygon 
Example #15
Source File: evaluation.py    From EAST with MIT License 5 votes vote down vote up
def visulization(img_dir, bbox_dir, visu_dir):
    for root, dirs, files in os.walk(img_dir):
        for file in files:
            # print(file)
            # if file!='img_75.jpg':
            #   continue
            print(file)
            image_name = file
            img_path = os.path.join(img_dir, image_name)
            img = cv2.imread(img_path)
            plt.clf()
            plt.imshow(img)
            currentAxis = plt.gca()
            bbox_name = 'res_' + file[0:len(file) - 3] + 'txt'
            bbox_path = os.path.join(bbox_dir, bbox_name)
            if os.path.isfile(bbox_path):
                with open(bbox_path, 'r') as f:
                    count = 1
                    for line in f.readlines():
                        line = line.strip()
                        x1 = line.split(',')[0]
                        y1 = line.split(',')[1]
                        x2 = line.split(',')[2]
                        y2 = line.split(',')[3]
                        x3 = line.split(',')[4]
                        y3 = line.split(',')[5]
                        x4 = line.split(',')[6]
                        y4 = line.split(',')[7]
                        rbox = np.array([[x1, y1], [x2, y2], [x3, y3], [x4, y4]])
                        color_rbox = 'r'
                        currentAxis.add_patch(plt.Polygon(rbox, fill=False, edgecolor=color_rbox, linewidth=1))
                        # currentAxis.text(int(x1), int(y1), str(count), bbox={'facecolor':'white', 'alpha':0.5})
                        count = count + 1

                plt.axis('off')
                plt.savefig(visu_dir + image_name, dpi=300) 
Example #16
Source File: mpl.py    From anaStruct with GNU General Public License v3.0 4 votes vote down vote up
def __roll_support_patch(self, max_val):
        """
        :param max_val: max scale of the plot
        """
        radius = PATCH_SIZE * max_val
        count = 0
        for node in self.system.supports_roll:
            direction = self.system.supports_roll_direction[count]
            x1 = np.cos(np.pi) * radius + node.vertex.x + radius
            z1 = np.sin(np.pi) * radius + node.vertex.y
            x2 = np.cos(np.radians(90)) * radius + node.vertex.x + radius
            z2 = np.sin(np.radians(90)) * radius + node.vertex.y
            x3 = np.cos(np.radians(270)) * radius + node.vertex.x + radius
            z3 = np.sin(np.radians(270)) * radius + node.vertex.y

            triangle = np.array([[x1, z1], [x2, z2], [x3, z3]])

            if node.id in self.system.inclined_roll:
                angle = self.system.inclined_roll[node.id]
                triangle = rotate_xy(triangle, angle + np.pi * 0.5)
                support_patch = plt.Polygon(triangle, color="r", zorder=9)
                self.one_fig.add_patch(support_patch)
                self.one_fig.plot(
                    triangle[1:, 0] - 0.5 * radius * np.sin(angle),
                    triangle[1:, 1] - 0.5 * radius * np.cos(angle),
                    color="r",
                )

            elif direction == 2:  # horizontal roll
                support_patch = mpatches.RegularPolygon(
                    (node.vertex.x, node.vertex.y - radius),
                    numVertices=3,
                    radius=radius,
                    color="r",
                    zorder=9,
                )
                self.one_fig.add_patch(support_patch)
                y = -node.vertex.z - 2 * radius
                self.one_fig.plot(
                    [node.vertex.x - radius, node.vertex.x + radius], [y, y], color="r"
                )
            elif direction == 1:  # vertical roll
                # translate the support to the node

                support_patch = mpatches.Polygon(triangle, color="r", zorder=9)
                self.one_fig.add_patch(support_patch)

                y = node.vertex.y - radius
                self.one_fig.plot(
                    [node.vertex.x + radius * 1.5, node.vertex.x + radius * 1.5],
                    [y, y + 2 * radius],
                    color="r",
                )
            count += 1