當前位置: 首頁>>代碼示例>>Python>>正文


Python matplotlib.patches方法代碼示例

本文整理匯總了Python中matplotlib.patches方法的典型用法代碼示例。如果您正苦於以下問題:Python matplotlib.patches方法的具體用法?Python matplotlib.patches怎麽用?Python matplotlib.patches使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在matplotlib的用法示例。


在下文中一共展示了matplotlib.patches方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: construct_ball_trajectory

# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import patches [as 別名]
def construct_ball_trajectory(var, r=1., cmap='Blues', start_color=0.4, shape='c'):
    # https://matplotlib.org/examples/color/colormaps_reference.html
    patches = []
    for pos in var:
        if shape == 'c':
            patches.append(mpatches.Circle(pos, r))
        elif shape == 'r':
            patches.append(mpatches.RegularPolygon(pos, 4, r))
        elif shape == 's':
            patches.append(mpatches.RegularPolygon(pos, 6, r))

    colors = np.linspace(start_color, .9, len(patches))
    collection = PatchCollection(patches, cmap=cm.get_cmap(cmap), alpha=1.)
    collection.set_array(np.array(colors))
    collection.set_clim(0, 1)
    return collection 
開發者ID:simonkamronn,項目名稱:kvae,代碼行數:18,代碼來源:plotting.py

示例2: plot_filled_polygons

# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import patches [as 別名]
def plot_filled_polygons(self,polygons, facecolour='green', edgecolour='black', linewidth=1, alpha=0.5):
        """
        This function plots a series of shapely polygons but fills them in

        Args:
            ax_list: list of axes
            polygons: list of shapely polygons

        Author: FJC
        """
        from shapely.geometry import Polygon
        from descartes import PolygonPatch
        from matplotlib.collections import PatchCollection

        print('Plotting the polygons...')

        #patches = []
        for key, poly in polygons.items():
            this_patch = PolygonPatch(poly, fc=facecolour, ec=edgecolour, alpha=alpha)
            self.ax_list[0].add_patch(this_patch) 
開發者ID:LSDtopotools,項目名稱:LSDMappingTools,代碼行數:22,代碼來源:PlottingRaster.py

示例3: read_JSON_file

# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import patches [as 別名]
def read_JSON_file(f):
    
    with open(f, 'r') as g:
        d = json.loads(g.read())
    
    img_paths = [x['file_name'] for x in d['images']]
    
    rects = [{'bbox': x['segmentation'][0], 'class': x['category_id'], 'image_id': x['image_id']} for x in d['annotations']]
    
    annotations = defaultdict(list)
    
    for rect in rects:
        r = rect['bbox']
        x0, y0 = min(r[0], r[2], r[4], r[6]), min(r[1], r[3], r[5], r[7])
        x1, y1 = max(r[0], r[2], r[4], r[6]), max(r[1], r[3], r[5], r[7])
        
        r = patches.Rectangle((x0,y0),x1-x0,y1-y0,linewidth=1,edgecolor='g',facecolor='g', alpha=0.4)        
        
        annotations[img_paths[rect['image_id']]].append({'bbox': r, 'cls': d['classes'][rect['class']-1]})
        
    return d['classes'], img_paths, annotations 
開發者ID:hanskrupakar,項目名稱:COCO-Style-Dataset-Generator-GUI,代碼行數:23,代碼來源:segment_bbox_only.py

示例4: add_patch

# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import patches [as 別名]
def add_patch(self, p):
        """
        Add a :class:`~matplotlib.patches.Patch` *p* to the list of
        axes patches; the clipbox will be set to the Axes clipping
        box.  If the transform is not set, it will be set to
        :attr:`transData`.

        Returns the patch.
        """

        self._set_artist_props(p)
        if p.get_clip_path() is None:
            p.set_clip_path(self.patch)
        self._update_patch_limits(p)
        self.patches.append(p)
        p._remove_method = lambda h: self.patches.remove(h)
        return p 
開發者ID:miloharper,項目名稱:neural-network-animation,代碼行數:19,代碼來源:_base.py

示例5: _update_patch_limits

# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import patches [as 別名]
def _update_patch_limits(self, patch):
        """update the data limits for patch *p*"""
        # hist can add zero height Rectangles, which is useful to keep
        # the bins, counts and patches lined up, but it throws off log
        # scaling.  We'll ignore rects with zero height or width in
        # the auto-scaling

        # cannot check for '==0' since unitized data may not compare to zero
        # issue #2150 - we update the limits if patch has non zero width
        # or height.
        if (isinstance(patch, mpatches.Rectangle) and
                ((not patch.get_width()) and (not patch.get_height()))):
            return
        vertices = patch.get_path().vertices
        if vertices.size > 0:
            xys = patch.get_patch_transform().transform(vertices)
            if patch.get_data_transform() != self.transData:
                patch_to_data = (patch.get_data_transform() -
                                    self.transData)
                xys = patch_to_data.transform(xys)

            updatex, updatey = patch.get_transform().\
                contains_branch_seperately(self.transData)
            self.update_datalim(xys, updatex=updatex,
                                updatey=updatey) 
開發者ID:miloharper,項目名稱:neural-network-animation,代碼行數:27,代碼來源:_base.py

示例6: relim

# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import patches [as 別名]
def relim(self, visible_only=False):
        """
        Recompute the data limits based on current artists. If you want to
        exclude invisible artists from the calculation, set
        ``visible_only=True``

        At present, :class:`~matplotlib.collections.Collection`
        instances are not supported.
        """
        # Collections are deliberately not supported (yet); see
        # the TODO note in artists.py.
        self.dataLim.ignore(True)
        self.dataLim.set_points(mtransforms.Bbox.null().get_points())
        self.ignore_existing_data_limits = True

        for line in self.lines:
            if not visible_only or line.get_visible():
                self._update_line_limits(line)

        for p in self.patches:
            if not visible_only or p.get_visible():
                self._update_patch_limits(p) 
開發者ID:miloharper,項目名稱:neural-network-animation,代碼行數:24,代碼來源:_base.py

示例7: test_arc_ellipse

# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import patches [as 別名]
def test_arc_ellipse():
    from matplotlib import patches
    xcenter, ycenter = 0.38, 0.52
    width, height = 1e-1, 3e-1
    angle = -30

    theta = np.arange(0.0, 360.0, 1.0)*np.pi/180.0
    x = width/2. * np.cos(theta)
    y = height/2. * np.sin(theta)

    rtheta = angle*np.pi/180.
    R = np.array([
        [np.cos(rtheta),  -np.sin(rtheta)],
        [np.sin(rtheta), np.cos(rtheta)],
        ])

    x, y = np.dot(R, np.array([x, y]))
    x += xcenter
    y += ycenter

    fig = plt.figure()
    ax = fig.add_subplot(211, aspect='auto')
    ax.fill(x, y, alpha=0.2, facecolor='yellow', edgecolor='yellow', linewidth=1, zorder=1)

    e1 = patches.Arc((xcenter, ycenter), width, height,
                     angle=angle, linewidth=2, fill=False, zorder=2)

    ax.add_patch(e1)

    ax = fig.add_subplot(212, aspect='equal')
    ax.fill(x, y, alpha=0.2, facecolor='green', edgecolor='green', zorder=1)
    e2 = patches.Arc((xcenter, ycenter), width, height,
                     angle=angle, linewidth=2, fill=False, zorder=2)

    ax.add_patch(e2) 
開發者ID:miloharper,項目名稱:neural-network-animation,代碼行數:37,代碼來源:test_axes.py

示例8: add_patch

# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import patches [as 別名]
def add_patch(self, p):
        """
        Add a :class:`~matplotlib.patches.Patch` *p* to the list of
        axes patches; the clipbox will be set to the Axes clipping
        box.  If the transform is not set, it will be set to
        :attr:`transData`.

        Returns the patch.
        """

        self._set_artist_props(p)
        if p.get_clip_path() is None:
            p.set_clip_path(self.patch)
        self._update_patch_limits(p)
        self.patches.append(p)
        p._remove_method = self.patches.remove
        return p 
開發者ID:Relph1119,項目名稱:GraphicDesignPatternByPython,代碼行數:19,代碼來源:_base.py

示例9: _update_patch_limits

# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import patches [as 別名]
def _update_patch_limits(self, patch):
        """update the data limits for patch *p*"""
        # hist can add zero height Rectangles, which is useful to keep
        # the bins, counts and patches lined up, but it throws off log
        # scaling.  We'll ignore rects with zero height or width in
        # the auto-scaling

        # cannot check for '==0' since unitized data may not compare to zero
        # issue #2150 - we update the limits if patch has non zero width
        # or height.
        if (isinstance(patch, mpatches.Rectangle) and
                ((not patch.get_width()) and (not patch.get_height()))):
            return
        vertices = patch.get_path().vertices
        if vertices.size > 0:
            xys = patch.get_patch_transform().transform(vertices)
            if patch.get_data_transform() != self.transData:
                patch_to_data = (patch.get_data_transform() -
                                 self.transData)
                xys = patch_to_data.transform(xys)

            updatex, updatey = patch.get_transform().\
                contains_branch_seperately(self.transData)
            self.update_datalim(xys, updatex=updatex,
                                updatey=updatey) 
開發者ID:Relph1119,項目名稱:GraphicDesignPatternByPython,代碼行數:27,代碼來源:_base.py

示例10: get_children

# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import patches [as 別名]
def get_children(self):
        """return a list of child artists"""
        children = []
        children.extend(self.collections)
        children.extend(self.patches)
        children.extend(self.lines)
        children.extend(self.texts)
        children.extend(self.artists)
        children.extend(self.spines.values())
        children.append(self.xaxis)
        children.append(self.yaxis)
        children.append(self.title)
        children.append(self._left_title)
        children.append(self._right_title)
        children.extend(self.tables)
        children.extend(self.images)
        children.extend(self.child_axes)

        if self.legend_ is not None:
            children.append(self.legend_)
        children.append(self.patch)

        return children 
開發者ID:Relph1119,項目名稱:GraphicDesignPatternByPython,代碼行數:25,代碼來源:_base.py

示例11: test_arc_angles

# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import patches [as 別名]
def test_arc_angles():
    from matplotlib import patches
    # Ellipse parameters
    w = 2
    h = 1
    centre = (0.2, 0.5)
    scale = 2

    fig, axs = plt.subplots(3, 3)
    for i, ax in enumerate(axs.flat):
        theta2 = i * 360 / 9
        theta1 = theta2 - 45

        ax.add_patch(patches.Ellipse(centre, w, h, alpha=0.3))
        ax.add_patch(patches.Arc(centre, w, h, theta1=theta1, theta2=theta2))
        # Straight lines intersecting start and end of arc
        ax.plot([scale * np.cos(np.deg2rad(theta1)) + centre[0],
                 centre[0],
                 scale * np.cos(np.deg2rad(theta2)) + centre[0]],
                [scale * np.sin(np.deg2rad(theta1)) + centre[1],
                 centre[1],
                 scale * np.sin(np.deg2rad(theta2)) + centre[1]])

        ax.set_xlim(-scale, scale)
        ax.set_ylim(-scale, scale)

        # This looks the same, but it triggers a different code path when it
        # gets large enough.
        w *= 10
        h *= 10
        centre = (centre[0] * 10, centre[1] * 10)
        scale *= 10 
開發者ID:holzschu,項目名稱:python3_ios,代碼行數:34,代碼來源:test_axes.py

示例12: test_arc_ellipse

# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import patches [as 別名]
def test_arc_ellipse():
    from matplotlib import patches
    xcenter, ycenter = 0.38, 0.52
    width, height = 1e-1, 3e-1
    angle = -30

    theta = np.deg2rad(np.arange(360))
    x = width / 2. * np.cos(theta)
    y = height / 2. * np.sin(theta)

    rtheta = np.deg2rad(angle)
    R = np.array([
        [np.cos(rtheta), -np.sin(rtheta)],
        [np.sin(rtheta), np.cos(rtheta)]])

    x, y = np.dot(R, np.array([x, y]))
    x += xcenter
    y += ycenter

    fig = plt.figure()
    ax = fig.add_subplot(211, aspect='auto')
    ax.fill(x, y, alpha=0.2, facecolor='yellow', edgecolor='yellow',
            linewidth=1, zorder=1)

    e1 = patches.Arc((xcenter, ycenter), width, height,
                     angle=angle, linewidth=2, fill=False, zorder=2)

    ax.add_patch(e1)

    ax = fig.add_subplot(212, aspect='equal')
    ax.fill(x, y, alpha=0.2, facecolor='green', edgecolor='green', zorder=1)
    e2 = patches.Arc((xcenter, ycenter), width, height,
                     angle=angle, linewidth=2, fill=False, zorder=2)

    ax.add_patch(e2) 
開發者ID:holzschu,項目名稱:python3_ios,代碼行數:37,代碼來源:test_axes.py

示例13: test_hist_step_filled

# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import patches [as 別名]
def test_hist_step_filled():
    np.random.seed(0)
    x = np.random.randn(1000, 3)
    n_bins = 10

    kwargs = [{'fill': True}, {'fill': False}, {'fill': None}, {}]*2
    types = ['step']*4+['stepfilled']*4
    fig, axes = plt.subplots(nrows=2, ncols=4)
    axes = axes.flatten()

    for kg, _type, ax in zip(kwargs, types, axes):
        ax.hist(x, n_bins, histtype=_type, stacked=True, **kg)
        ax.set_title('%s/%s' % (kg, _type))
        ax.set_ylim(bottom=-50)

    patches = axes[0].patches
    assert all(p.get_facecolor() == p.get_edgecolor() for p in patches) 
開發者ID:holzschu,項目名稱:python3_ios,代碼行數:19,代碼來源:test_axes.py

示例14: add_heatmap

# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import patches [as 別名]
def add_heatmap(self, title, x, tensor, drawbox=None):
        assert tensor.dim() == 3

        def plot_heatmap(ax, tensor, drawbox=None):
            ax.imshow(tensor.detach().cpu().numpy())
            ax.invert_yaxis()
            ax.label_outer()
            if drawbox is not None:
                rect = patches.Rectangle((0, 0), *drawbox.tolist(), linewidth=1, edgecolor='b', facecolor='none')
                ax.add_patch(rect)

        if tensor.size(0) == 1:
            fig, ax = plt.subplots()
            plot_heatmap(ax, tensor[0], drawbox)
        else:
            fig, axs = plt.subplots(tensor.size(0), sharex=True)
            for i, ax in enumerate(axs):
                plot_heatmap(ax, tensor[i], drawbox)
            fig.subplots_adjust(hspace=2)

        fig.patch.set_color('white')
        fig.tight_layout()
        self.writer.add_figure(title, fig, x) 
開發者ID:jinserk,項目名稱:pytorch-asr,代碼行數:25,代碼來源:logger.py

示例15: lasso_onselect

# 需要導入模塊: import matplotlib [as 別名]
# 或者: from matplotlib import patches [as 別名]
def lasso_onselect(self, verts):
        self.pathlasso = path.Path(verts)
        patch = patches.PathPatch(self.pathlasso, fill=True, alpha=.2, edgecolor=None)
        self.ax1.add_patch(patch)
        self.figure.canvas.draw()
        if self.mode == 1 or self.mode == 4 or self.mode == 7:
            onslice = 'Z %s' % (self.ind + 1)
        elif self.mode == 2 or self.mode == 5 or self.mode == 8:
            onslice = 'X %s' % (self.ind + 1)
        elif self.mode == 3 or self.mode == 6 or self.mode == 9:
            onslice = 'Y %s' % (self.ind + 1)
        self.df = pandas.read_csv('Markings/marking_records.csv')
        df_size = pandas.DataFrame.count(self.df)
        df_rows = df_size['artist']
        self.df.loc[df_rows, 'artist'] = patch
        plist = np.ndarray.tolist(self.pathlasso.vertices)
        plist = ', '.join(str(x) for x in plist)
        self.df.loc[df_rows, 'labelshape'] = 'lasso'
        self.df.loc[df_rows, 'slice'] = onslice
        self.df.loc[df_rows, 'path'] = plist
        self.df.loc[df_rows, 'status'] = 0
        self.df.to_csv('Markings/marking_records.csv', index=False) 
開發者ID:thomaskuestner,項目名稱:CNNArt,代碼行數:24,代碼來源:canvas.py


注:本文中的matplotlib.patches方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。