Python matplotlib.patches() Examples

The following are 30 code examples for showing how to use matplotlib.patches(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module matplotlib , or try the search function .

Example 1
Project: kvae   Author: simonkamronn   File: plotting.py    License: MIT License 6 votes vote down vote up
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 
Example 2
Project: LSDMappingTools   Author: LSDtopotools   File: PlottingRaster.py    License: MIT License 6 votes vote down vote up
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) 
Example 3
Project: COCO-Style-Dataset-Generator-GUI   Author: hanskrupakar   File: segment_bbox_only.py    License: Apache License 2.0 6 votes vote down vote up
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 
Example 4
Project: neural-network-animation   Author: miloharper   File: _base.py    License: MIT License 6 votes vote down vote up
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 
Example 5
Project: neural-network-animation   Author: miloharper   File: _base.py    License: MIT License 6 votes vote down vote up
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) 
Example 6
Project: neural-network-animation   Author: miloharper   File: _base.py    License: MIT License 6 votes vote down vote up
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) 
Example 7
Project: neural-network-animation   Author: miloharper   File: test_axes.py    License: MIT License 6 votes vote down vote up
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) 
Example 8
Project: GraphicDesignPatternByPython   Author: Relph1119   File: _base.py    License: MIT License 6 votes vote down vote up
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 
Example 9
Project: GraphicDesignPatternByPython   Author: Relph1119   File: _base.py    License: MIT License 6 votes vote down vote up
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) 
Example 10
Project: GraphicDesignPatternByPython   Author: Relph1119   File: _base.py    License: MIT License 6 votes vote down vote up
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 
Example 11
Project: python3_ios   Author: holzschu   File: _base.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example 12
Project: python3_ios   Author: holzschu   File: _base.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example 13
Project: python3_ios   Author: holzschu   File: test_axes.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example 14
Project: python3_ios   Author: holzschu   File: test_axes.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example 15
Project: python3_ios   Author: holzschu   File: test_axes.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example 16
Project: pytorch-asr   Author: jinserk   File: logger.py    License: GNU General Public License v3.0 6 votes vote down vote up
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) 
Example 17
Project: CNNArt   Author: thomaskuestner   File: canvas.py    License: Apache License 2.0 6 votes vote down vote up
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) 
Example 18
Project: ImageFusion   Author: pfchai   File: _base.py    License: MIT License 6 votes vote down vote up
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 
Example 19
Project: ImageFusion   Author: pfchai   File: _base.py    License: MIT License 6 votes vote down vote up
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) 
Example 20
Project: ImageFusion   Author: pfchai   File: _base.py    License: MIT License 6 votes vote down vote up
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) 
Example 21
Project: spm1d   Author: 0todd0000   File: _plot.py    License: GNU General Public License v3.0 6 votes vote down vote up
def plot_cloud(self, Y, facecolor='0.8', edgecolor='0.8', alpha=0.5, edgelinestyle='-'):
		### create patches:
		y0,y1       = Y
		x,y0,y1     = self.x.tolist(), y0.tolist(), y1.tolist()
		x           = [x[0]]  + x  + [x[-1]]
		y0          = [y0[0]] + y0 + [y0[-1]]
		y1          = [y1[0]] + y1 + [y1[-1]]
		y1.reverse()
		### concatenate:
		x1          = np.copy(x).tolist()
		x1.reverse()
		x,y         = x + x1, y0 + y1
		patches     = PatchCollection(   [  Polygon(  np.array([x,y]).T  )  ], edgecolors=None)
		### plot:
		self.ax.add_collection(patches)
		pyplot.setp(patches, facecolor=facecolor, edgecolor=edgecolor, alpha=alpha, linestyle=edgelinestyle)
		return patches 
Example 22
Project: H3DNet   Author: zaiweizhang   File: box_util.py    License: MIT License 5 votes vote down vote up
def plot_polys(plist,scale=500.0):
        fig, ax = plt.subplots()
        patches = []
        for p in plist:
            poly = Polygon(np.array(p)/scale, True)
            patches.append(poly) 
Example 23
Project: LSDMappingTools   Author: LSDtopotools   File: PlottingRaster.py    License: MIT License 5 votes vote down vote up
def add_arrows_from_points(self, arrow_df, azimuth_header='azimuth', arrow_length=0.1, colour='black', linewidth=1, alpha = 1):
        """
        This function adds arrows at locations and azimuths specified by the
        pandas dataframe.  The X and Y locations should have column headers
        called 'X' and 'Y', the user specifies the column header of the azimuths
        column (default = 'azimuth')

        Args:
            arrow_df: pandas dataframe with the X and Y locations and the azimuths
            azimuth_header (str): the name of the column header with the azimuth locations
            colour: arrow colour, can pass in the name of one of the column headers and arrows will be coloured according to this.

        Author: FJC

        """
        import math
        import matplotlib.patches as patches

        # convert azimuths to radians
        azimuths = list(arrow_df[azimuth_header])
        az_radians = np.radians(azimuths)
        print(az_radians)

        # get points
        X = np.array(arrow_df['X'])
        Y = np.array(arrow_df['Y'])
        dx = np.array([ arrow_length*np.sin(i) for i in az_radians ])
        dy = np.array([ arrow_length*np.cos(i) for i in az_radians ])
        new_X = X - dx/2
        new_Y = Y - dy/2

        print((dx,dy))

        self.ax_list[0].quiver(new_X,new_Y,dx,dy,angles='xy',scale_units='xy',scale=1, width=0.002) 
Example 24
Project: AGFusion   Author: murphycj   File: plot.py    License: MIT License 5 votes vote down vote up
def _draw_exons(self):
        for exon in self.ensembl_transcript.exon_intervals:

            if self.ensembl_transcript.strand == '+':
                start = exon[0] - self.ensembl_transcript.start
                end = exon[1] - self.ensembl_transcript.start
            else:

                # this is so the transcription direction is not plotted
                # in reverse for genes on minus strand

                start = -(exon[1] - self.ensembl_transcript.end)
                end = -(exon[0] - self.ensembl_transcript.end)

            exon_start = (int(start)/float(self.normalize))*0.9 + self.offset
            exon_end = (int(end)/float(self.normalize))*0.9 + self.offset
            exon_center = (exon_end-exon_start)/2. + exon_start

            self.ax.add_patch(
                patches.Rectangle(
                    (
                        exon_start,
                        0.45,
                    ),
                    exon_end-exon_start,
                    0.1,
                    color="black"
                )
            ) 
Example 25
Project: AGFusion   Author: murphycj   File: plot.py    License: MIT License 5 votes vote down vote up
def _draw_main_body(self, name_symbols, name_isoform):
        """
        main protein frame
        """

        self.ax.add_patch(
            patches.Rectangle(
                (self.offset, self.vertical_offset),
                self.protein_frame_length,
                0.1,
                fill=False
            )
        )

        self.ax.text(
            0.5,
            0.95,
            name_symbols,
            horizontalalignment='center',
            fontsize=self.fontsize
        )

        self.ax.text(
            0.5,
            0.88,
            name_isoform,
            horizontalalignment='center',
            fontsize=self.fontsize-3
        ) 
Example 26
Project: Computable   Author: ktraunmueller   File: pyplot.py    License: MIT License 5 votes vote down vote up
def figlegend(handles, labels, loc, **kwargs):
    """
    Place a legend in the figure.

    *labels*
      a sequence of strings

    *handles*
      a sequence of :class:`~matplotlib.lines.Line2D` or
      :class:`~matplotlib.patches.Patch` instances

    *loc*
      can be a string or an integer specifying the legend
      location

    A :class:`matplotlib.legend.Legend` instance is returned.

    Example::

      figlegend( (line1, line2, line3),
                 ('label1', 'label2', 'label3'),
                 'upper right' )

    .. seealso::

       :func:`~matplotlib.pyplot.legend`

    """
    l = gcf().legend(handles, labels, loc, **kwargs)
    draw_if_interactive()
    return l


## Figure and Axes hybrid ## 
Example 27
Project: Ensemble-Bayesian-Optimization   Author: zi-w   File: mondrian.py    License: MIT License 5 votes vote down vote up
def visualize(self):
        if self.leaves is None or self.X.shape[1] != 2:
            print
            'error: x shape is wrong or leaves is none.'

        # visaulize 2d mondrians
        import matplotlib.pyplot as plt
        import matplotlib.patches as patches
        import matplotlib
        font = {'size': 20}
        matplotlib.rc('font', **font)
        mondrian_colors = np.array([[255, 240, 1], [48, 48, 58],
                                    [255, 1, 1], [1, 1, 253], [249, 249, 249]])
        mondrian_colors = mondrian_colors / 255.0
        fig = plt.figure()
        ax = fig.add_subplot(111, aspect='equal')
        print('number of leaves = {}'.format(len(self.leaves)))
        for node in self.leaves:
            xy = node.x_range[0]
            xylen = node.x_range[1] - node.x_range[0]
            c = mondrian_colors[4]
            p = patches.Rectangle(
                xy, xylen[0], xylen[1],
                facecolor=c,
                linewidth=1,
                edgecolor='k'
            )
            ax.add_patch(p)
        for x in self.X:
            c = '#fdbf6f'
            p = patches.Circle(
                x, 0.01,
                facecolor=c,
                linewidth=0
            )
            ax.add_patch(p)
        return ax, fig 
Example 28
Project: matplotlib-4-abaqus   Author: Solid-Mechanics   File: pyplot.py    License: MIT License 5 votes vote down vote up
def figlegend(handles, labels, loc, **kwargs):
    """
    Place a legend in the figure.

    *labels*
      a sequence of strings

    *handles*
      a sequence of :class:`~matplotlib.lines.Line2D` or
      :class:`~matplotlib.patches.Patch` instances

    *loc*
      can be a string or an integer specifying the legend
      location

    A :class:`matplotlib.legend.Legend` instance is returned.

    Example::

      figlegend( (line1, line2, line3),
                 ('label1', 'label2', 'label3'),
                 'upper right' )

    .. seealso::

       :func:`~matplotlib.pyplot.legend`

    """
    l = gcf().legend(handles, labels, loc, **kwargs)
    draw_if_interactive()
    return l


## Figure and Axes hybrid ## 
Example 29
Project: HereIsWally   Author: tadejmagajna   File: find_wally_pretty.py    License: MIT License 5 votes vote down vote up
def draw_box(box, image_np):
    #expand the box by 50%
    box += np.array([-(box[2] - box[0])/2, -(box[3] - box[1])/2, (box[2] - box[0])/2, (box[3] - box[1])/2]) 

    fig = plt.figure()
    ax = plt.Axes(fig, [0., 0., 1., 1.])
    fig.add_axes(ax)

    #draw blurred boxes around box
    ax.add_patch(patches.Rectangle((0,0),box[1]*image_np.shape[1], image_np.shape[0],linewidth=0,edgecolor='none',facecolor='w',alpha=0.8))
    ax.add_patch(patches.Rectangle((box[3]*image_np.shape[1],0),image_np.shape[1], image_np.shape[0],linewidth=0,edgecolor='none',facecolor='w',alpha=0.8))
    ax.add_patch(patches.Rectangle((box[1]*image_np.shape[1],0),(box[3]-box[1])*image_np.shape[1], box[0]*image_np.shape[0],linewidth=0,edgecolor='none',facecolor='w',alpha=0.8))
    ax.add_patch(patches.Rectangle((box[1]*image_np.shape[1],box[2]*image_np.shape[0]),(box[3]-box[1])*image_np.shape[1], image_np.shape[0],linewidth=0,edgecolor='none',facecolor='w',alpha=0.8))

    return fig, ax 
Example 30
Project: neural-network-animation   Author: miloharper   File: _base.py    License: MIT License 5 votes vote down vote up
def __setstate__(self, state):
        self.__dict__ = state
        # put the _remove_method back on all artists contained within the axes
        for container_name in ['lines', 'collections', 'tables', 'patches',
                               'texts', 'images']:
            container = getattr(self, container_name)
            for artist in container:
                artist._remove_method = container.remove