Python matplotlib 模块,patches() 实例源码

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

项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def redraw_overplot_on_image(self, *args):
        if self.star_center_patch is not None:
            self.ztv_frame.primary_image_panel.axes.patches.remove(self.star_center_patch)
        if self.star_aperture_patch is not None:
            self.ztv_frame.primary_image_panel.axes.patches.remove(self.star_aperture_patch)
        if self.sky_aperture_patch is not None:
            self.ztv_frame.primary_image_panel.axes.patches.remove(self.sky_aperture_patch)
        self.star_center_patch = Circle([self.xcentroid, self.ycentroid], 0.125, color=self.aprad_color)
        self.ztv_frame.primary_image_panel.axes.add_patch(self.star_center_patch)
        self.star_aperture_patch = Circle([self.xcentroid, self.ycentroid], self.aprad, color=self.aprad_color, alpha=self.alpha)
        self.ztv_frame.primary_image_panel.axes.add_patch(self.star_aperture_patch)
        self.sky_aperture_patch = Wedge([self.xcentroid, self.ycentroid], self.skyradout, 0., 360., 
                                        width=self.skyradout - self.skyradin, color=self.skyrad_color, alpha=self.alpha)
        self.ztv_frame.primary_image_panel.axes.add_patch(self.sky_aperture_patch)
        self.ztv_frame.primary_image_panel.figure.canvas.draw()
        self.hideshow_button.SetLabel(u"Hide")
项目:pauvre    作者:conchoecia    | 项目源码 | 文件源码
def plotArc(start_angle, stop_angle, radius, width, **kwargs):
    """ write a docstring for this function"""
    numsegments = 100
    theta = np.radians(np.linspace(start_angle+90, stop_angle+90, numsegments))
    centerx = 0
    centery = 0
    x1 = -np.cos(theta) * (radius)
    y1 = np.sin(theta) * (radius)
    stack1 = np.column_stack([x1, y1])
    x2 = -np.cos(theta) * (radius + width)
    y2 = np.sin(theta) *  (radius + width)
    stack2 = np.column_stack([np.flip(x2, axis=0), np.flip(y2,axis=0)])
    #add the first values from the first set to close the polygon
    np.append(stack2, [[x1[0],y1[0]]], axis=0)
    arcArray = np.concatenate((stack1,stack2), axis=0)
    return patches.Polygon(arcArray, True, **kwargs), ((x1, y1), (x2, y2))
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def redraw_overplot_on_image(self, msg=None):
        if self.primary_image_patch is not None:
            self.ztv_frame.primary_image_panel.axes.patches.remove(self.primary_image_patch)
        if self.start_pt == self.end_pt:
            path = Path([self.start_pt, self.start_pt + (0.5, 0.),
                         self.start_pt, self.start_pt + (-0.5, 0.), 
                         self.start_pt, self.start_pt + (0., 0.5), 
                         self.start_pt, self.start_pt + (0., -0.5), self.start_pt], 
                        [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, 
                         Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO])
        else:
            path = Path([self.start_pt, self.end_pt], [Path.MOVETO, Path.LINETO])
        self.primary_image_patch = PathPatch(path, color='magenta', lw=1)
        self.ztv_frame.primary_image_panel.axes.add_patch(self.primary_image_patch)
        self.ztv_frame.primary_image_panel.figure.canvas.draw()
        self.hideshow_button.SetLabel(u"Hide")
项目:FoundryDataBrowser    作者:ScopeFoundry    | 项目源码 | 文件源码
def draw_roi(x1, y1, x2, y2, **draw_params):
    codes = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY]

    ax = plt.gca()

    # Form a path
    verts = [(x1, y1),
             (x1, y2),
             (x2, y2),
             (x2, y1),
             (0, 0)]
    path = Path(verts, codes)

    # Draw the BG region on the image
    patch = patches.PathPatch(path, **draw_params)
    ax.add_patch(patch)
项目:SamuROI    作者:samuroi    | 项目源码 | 文件源码
def create_outlined_artist(self, mask, color, **kwargs):
        artist = matplotlib.patches.Polygon(xy=mask.outline - 0.5, lw=1, picker=True, fill=False, color='gray',
                                            **kwargs)

        artist.color = color
        artist.mask = mask

        # todo: make the branches children a polygonCollection for better performance

        def set_selected(self, a):
            if a is True:
                self.set_linewidth(5)
                self.set_edgecolor(self.color)
            else:
                self.set_linewidth(1)
                self.set_edgecolor('gray')

        artist.set_selected = types.MethodType(set_selected, artist)
        self.__artists[mask] = artist
        self.axes.add_artist(artist)

        self.create_outlined_child_artits(parent=mask)
项目:SamuROI    作者:samuroi    | 项目源码 | 文件源码
def create_circle_artist(self, mask, color, **kwargs):
        artist = matplotlib.patches.Circle(radius=mask.radius, xy=mask.center - 0.5, lw=1, picker=True, fill=False,
                                           color='gray', **kwargs)

        artist.color = color
        artist.mask = mask

        def set_selected(self, a):
            if a is True:
                self.set_linewidth(5)
                self.set_edgecolor(self.color)
            else:
                self.set_linewidth(1)
                self.set_edgecolor('gray')

        artist.set_selected = types.MethodType(set_selected, artist)
        self.__artists[mask] = artist
        self.axes.add_artist(artist)
项目:tf-Faster-RCNN    作者:kevinjliang    | 项目源码 | 文件源码
def vis_detections(self, im, class_name, gt_boxes, dets):
        """Visual debugging of detections."""
        import matplotlib
        matplotlib.use('TkAgg')  # For Mac OS
        import matplotlib.pyplot as plt
        import matplotlib.patches as patches
        fig, ax = plt.subplots(1)
        for i in range(np.minimum(10, dets.shape[0])):
            bbox = dets[i,1:]
            print(bbox)
            ax.imshow(np.squeeze(im), cmap="gray")
            self.plot_patch(ax, patches, bbox, gt=False)
        plt.title(class_name)
        self.plot_patch(ax, patches, gt_boxes[0][:4], gt=True)

        # Display Final composite image
        plt.show()
项目:poreduck    作者:alexiswl    | 项目源码 | 文件源码
def plot_pore_yield_hist():
    # Close any previous plots
    plt.close('all')
    num_bins = 50
    new_yield_data = ALL_READS.groupby(["channel", "mux"])['seq_length'].sum()
    fig, ax = plt.subplots(1)
    (n, bins, patches) = ax.hist(new_yield_data, num_bins, weights=None,
                                 # [1],#channels_by_yield_df['seq_length'],
                                 normed=1, facecolor='blue', alpha=0.76)
    ax.xaxis.set_major_formatter(FuncFormatter(x_hist_to_human_readable))

    def y_muxhist_to_human_readable(y, position):
        # Get numbers of reads per bin in the histogram
        s = humanfriendly.format_size((bins[1]-bins[0])*y*new_yield_data.count(), binary=False)
        return reformat_human_friendly(s)
    ax.yaxis.set_major_formatter(FuncFormatter(y_muxhist_to_human_readable))

    # Set the titles and axis labels
    ax.set_title(f"Yield by pore {SAMPLE_NAME}")
    ax.grid(color='black', linestyle=':', linewidth=0.5)
    ax.set_xlabel("Yield in single pore")
    ax.set_ylabel("Pores per bin")
    # Ensure labels are not missed.
    fig.tight_layout()
    savefig(os.path.join(PLOTS_DIR, f"{SAMPLE_NAME.replace(' ', '_')}_hist_yield_by_pore.png"))
项目:pauvre    作者:conchoecia    | 项目源码 | 文件源码
def generate_histogram(panel, data_list, max_plot_length, min_plot_length,
                       bin_interval, hist_horizontal=True,
                       left_spine=True, bottom_spine=True,
                       top_spine=False, right_spine=False, x_label=None,
                       y_label=None):

    bins = np.arange(0, max_plot_length, bin_interval)

    bin_values, bins2 = np.histogram(data_list, bins)

    # hist_horizontal is used for quality
    if hist_horizontal:
        panel.set_xlim([min_plot_length, max_plot_length])
        panel.set_ylim([0, max(bin_values * 1.1)])
    # and hist_horizontal == Fale is for read length
    else:
        panel.set_xlim([0, max(bin_values * 1.1)])
        panel.set_ylim([min_plot_length, max_plot_length])

    # Generate histogram bin patches, depending on whether we're plotting
    # vertically or horizontally
    _generate_histogram_bin_patches(panel, bins, bin_values, hist_horizontal)

    panel.spines['left'].set_visible(left_spine)
    panel.spines['bottom'].set_visible(bottom_spine)
    panel.spines['top'].set_visible(top_spine)
    panel.spines['right'].set_visible(right_spine)

    if y_label is not None:
        panel.set_ylabel(y_label)
    if x_label is not None:
        panel.set_xlabel(x_label)
项目:em_examples    作者:geoscixyz    | 项目源码 | 文件源码
def addCylinder2Mod(xc,zc,r,modd,sigCylinder):

    # Get points for cylinder outline
    cylinderPoints = getCylinderPoints(xc,zc,r)
    mod = copy.copy(modd)

    verts = []
    codes = []
    for ii in range(0,cylinderPoints.shape[0]):
        verts.append(cylinderPoints[ii,:])

        if(ii == 0):
            codes.append(Path.MOVETO)
        elif(ii == cylinderPoints.shape[0]-1):
            codes.append(Path.CLOSEPOLY)
        else:
            codes.append(Path.LINETO)

    path = Path(verts, codes)
    CCLocs = mesh.gridCC
    insideInd = np.where(path.contains_points(CCLocs))

    # #Check selected cell centers by plotting
    # # print insideInd
    # fig = plt.figure()
    # ax = fig.add_subplot(111)
    # patch = patches.PathPatch(path, facecolor='none', lw=2)
    # ax.add_patch(patch)
    # plt.scatter(CCLocs[insideInd,0],CCLocs[insideInd,1])
    # ax.set_xlim(-40,40)
    # ax.set_ylim(-35,0)
    # plt.axes().set_aspect('equal')
    # plt.show()

    mod[insideInd] = sigCylinder
    return mod
项目:em_examples    作者:geoscixyz    | 项目源码 | 文件源码
def addPlate2Mod(xc,zc,dx,dz,rotAng,modd,sigPlate):
    # use matplotlib paths to find CC inside of polygon
    plateCorners = getPlateCorners(xc,zc,dx,dz,rotAng)
    mod = copy.copy(modd)

    verts = [
        (plateCorners[0,:]), # left, top
        (plateCorners[1,:]), # right, top
        (plateCorners[3,:]), # right, bottom
        (plateCorners[2,:]), # left, bottom
        (plateCorners[0,:]), # left, top (closes polygon)
        ]

    codes = [Path.MOVETO,
             Path.LINETO,
             Path.LINETO,
             Path.LINETO,
             Path.CLOSEPOLY,
             ]

    path = Path(verts, codes)
    CCLocs = mesh.gridCC
    insideInd = np.where(path.contains_points(CCLocs))

    #Check selected cell centers by plotting
    # print insideInd
    # fig = plt.figure()
    # ax = fig.add_subplot(111)
    # patch = patches.PathPatch(path, facecolor='none', lw=2)
    # ax.add_patch(patch)
    # plt.scatter(CCLocs[insideInd,0],CCLocs[insideInd,1])
    # ax.set_xlim(-10,10)
    # ax.set_ylim(-20,0)
    # plt.axes().set_aspect('equal')
    # plt.show()

    mod[insideInd] = sigPlate
    return mod
项目:em_examples    作者:geoscixyz    | 项目源码 | 文件源码
def createPlateMod(xc, zc, dx, dz, rotAng, sigplate, sighalf):
    # use matplotlib paths to find CC inside of polygon
    plateCorners = getPlateCorners(xc,zc,dx,dz,rotAng)

    verts = [
        (plateCorners[0,:]), # left, top
        (plateCorners[1,:]), # right, top
        (plateCorners[3,:]), # right, bottom
        (plateCorners[2,:]), # left, bottom
        (plateCorners[0,:]), # left, top (closes polygon)
        ]

    codes = [Path.MOVETO,
             Path.LINETO,
             Path.LINETO,
             Path.LINETO,
             Path.CLOSEPOLY,
             ]

    path = Path(verts, codes)
    CCLocs = mesh.gridCC
    insideInd = np.where(path.contains_points(CCLocs))

    #Check selected cell centers by plotting
    # print insideInd
    # fig = plt.figure()
    # ax = fig.add_subplot(111)
    # patch = patches.PathPatch(path, facecolor='none', lw=2)
    # ax.add_patch(patch)
    # plt.scatter(CCLocs[insideInd,0],CCLocs[insideInd,1])
    # ax.set_xlim(-10,10)
    # ax.set_ylim(-20,0)
    # plt.axes().set_aspect('equal')
    # plt.show()

    mtrue = sighalf*np.ones([mesh.nC,])
    mtrue[insideInd] = sigplate
    mtrue = np.log(mtrue)
    return mtrue
项目:em_examples    作者:geoscixyz    | 项目源码 | 文件源码
def createPlateMod(xc, zc, dx, dz, rotAng, sigplate, sighalf):
    # use matplotlib paths to find CC inside of polygon
    plateCorners = getPlateCorners(xc,zc,dx,dz,rotAng)

    verts = [
        (plateCorners[0,:]), # left, top
        (plateCorners[1,:]), # right, top
        (plateCorners[3,:]), # right, bottom
        (plateCorners[2,:]), # left, bottom
        (plateCorners[0,:]), # left, top (closes polygon)
        ]

    codes = [Path.MOVETO,
             Path.LINETO,
             Path.LINETO,
             Path.LINETO,
             Path.CLOSEPOLY,
             ]

    path = Path(verts, codes)
    CCLocs = mesh.gridCC
    insideInd = np.where(path.contains_points(CCLocs))

    #Check selected cell centers by plotting
    # print insideInd
    # fig = plt.figure()
    # ax = fig.add_subplot(111)
    # patch = patches.PathPatch(path, facecolor='none', lw=2)
    # ax.add_patch(patch)
    # plt.scatter(CCLocs[insideInd,0],CCLocs[insideInd,1])
    # ax.set_xlim(-10,10)
    # ax.set_ylim(-20,0)
    # plt.axes().set_aspect('equal')
    # plt.show()

    mtrue = sighalf*np.ones([mesh.nC,])
    mtrue[insideInd] = sigplate
    mtrue = np.log(mtrue)
    return mtrue
项目:Dragonfly    作者:duaneloh    | 项目源码 | 文件源码
def end_track_positions(self):
        pos = np.array(self.positions)
        if pos.size == 0:
            return
        try:
            xnum = int(self.x_axis_num.text())
            ynum = int(self.y_axis_num.text())
        except ValueError:
            sys.stderr.write('Need axes numbers to be integers\n')
            return
        pos = np.append(pos, pos[-1]).reshape(-1,2)
        self.path_list.append(matplotlib.path.Path(pos, closed=True))
        points_inside = np.array([self.path_list[-1].contains_point((p[xnum], p[ynum])) for p in self.embed])
        sys.stderr.write('%d/%d frames inside ROI %d\n' % (points_inside.sum(), len(points_inside), len(self.points_inside_list)))
        self.points_inside_list.append(self.conversion.indices[np.where(points_inside)[0]])

        self.roi_list.append(
            matplotlib.patches.PathPatch(
                self.path_list[-1],
                color='white',
                fill=False,
                linewidth=2.,
                figure=self.frame.fig
            )
        )
        self.frame.fig.get_axes()[0].add_artist(self.roi_list[-1])
        for p in self.click_points_list:
            p.remove()
        self.frame.canvas.draw()

        self.frame.canvas.mpl_disconnect(self.connect_id)
        self.positions = []
        self.click_points_list = []
        if self.roi_summary is None:
            self.add_roi_frame()
        elif self.roi_summary.text() == '':
            self.roi_frame.show()
        self.gen_roi_summary()
        self.add_roi_radiobutton(len(self.roi_list)-1)
项目:johnson-county-ddj-public    作者:dssg    | 项目源码 | 文件源码
def venn2_circles(subsets, normalize_to=1.0, alpha=1.0, color='black', linestyle='solid', linewidth=2.0, ax=None, **kwargs):
    '''
    Plots only the two circles for the corresponding Venn diagram.
    Useful for debugging or enhancing the basic venn diagram.
    parameters ``subsets``, ``normalize_to`` and ``ax`` are the same as in venn2()
    ``kwargs`` are passed as-is to matplotlib.patches.Circle.
    returns a list of three Circle patches.

    >>> c = venn2_circles((1, 2, 3))
    >>> c = venn2_circles({'10': 1, '01': 2, '11': 3}) # Same effect
    >>> c = venn2_circles([set([1,2,3,4]), set([2,3,4,5,6])]) # Also same effect
    '''
    if isinstance(subsets, dict):
        subsets = [subsets.get(t, 0) for t in ['10', '01', '11']]
    elif len(subsets) == 2:
        subsets = compute_venn2_subsets(*subsets)
    areas = compute_venn2_areas(subsets, normalize_to)
    centers, radii = solve_venn2_circles(areas)

    if ax is None:
        ax = gca()
    prepare_venn_axes(ax, centers, radii)
    result = []
    for (c, r) in zip(centers, radii):
        circle = Circle(c, r, alpha=alpha, edgecolor=color, facecolor='none', linestyle=linestyle, linewidth=linewidth, **kwargs)
        ax.add_patch(circle)
        result.append(circle)
    return result
项目:yt    作者:yt-project    | 项目源码 | 文件源码
def __call__(self, plot):
        from matplotlib.patches import Circle

        if iterable(self.radius):
            self.radius = plot.data.ds.quan(self.radius[0], self.radius[1])
            self.radius = np.float64(self.radius.in_units(plot.xlim[0].units))

        # This assures the radius has the appropriate size in
        # the different coordinate systems, since one cannot simply
        # apply a different transform for a length in the same way
        # you can for a coordinate.
        if self.coord_system == 'data' or self.coord_system == 'plot':
            self.radius = self.radius * self.pixel_scale(plot)[0]
        else:
            self.radius /= (plot.xlim[1]-plot.xlim[0]).v

        x,y = self.sanitize_coord_system(plot, self.center,
                               coord_system=self.coord_system)

        cir = Circle((x, y), self.radius, transform=self.transform,
                     **self.circle_args)
        xx0, xx1 = plot._axes.get_xlim()
        yy0, yy1 = plot._axes.get_ylim()

        plot._axes.add_patch(cir)
        if self.text is not None:
            label = plot._axes.text(x, y, self.text, transform=self.transform,
                                    **self.text_args)
            self._set_font_properties(plot, [label], **self.text_args)

        plot._axes.set_xlim(xx0,xx1)
        plot._axes.set_ylim(yy0,yy1)
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def remove_overplot_on_image(self, msg=None):
        if self.primary_image_patch is not None:
            self.ztv_frame.primary_image_panel.axes.patches.remove(self.primary_image_patch)
        self.ztv_frame.primary_image_panel.figure.canvas.draw()
        self.primary_image_patch = None
        self.hideshow_button.SetLabel(u"Show")
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def on_button_release(self, event):
        if event.button == 1:  # left button
            if self.cursor_mode == 'Zoom':
                # this catches for the first click-release of a double-click
                if (time.time() - self.zoom_start_timestamp) > self.max_doubleclick_sec:
                    # this catches for a long click-and-release without motion
                    x0,y0 = self.zoom_rect.get_x(),self.zoom_rect.get_y()
                    x1 = x0 + self.zoom_rect.get_width()
                    y1 = y0 + self.zoom_rect.get_height()
                    if hasattr(event, 'xdata') and event.xdata is not None:
                        x1 = event.xdata
                    if hasattr(event, 'ydata') and event.ydata is not None:
                        y1 = event.ydata
                    if abs(x0 - x1) >= 2 and abs(y0 - y1) >= 2:
                        self.center = wx.RealPoint((x0 + x1)/2., (y0 + y1)/2.)
                        panel_size = self.canvas.GetSize()
                        x_zoom_factor = panel_size.x / abs(x1 - x0)
                        y_zoom_factor = panel_size.y / abs(y1 - y0)
                        self.ztv_frame.zoom_factor = min(x_zoom_factor, y_zoom_factor)
                        self.set_and_get_xy_limits()
                if self.zoom_rect in self.axes.patches:
                    self.axes.patches.remove(self.zoom_rect)
                self.zoom_rect = None
                self.figure.canvas.draw()
            else:
                if (self.available_cursor_modes.has_key(self.cursor_mode) and
                    self.available_cursor_modes[self.cursor_mode].has_key('on_button_release')):
                    self.available_cursor_modes[self.cursor_mode]['on_button_release'](event)
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def remove_overplot_on_image(self, *args):
        if self.star_center_patch is not None:
            self.ztv_frame.primary_image_panel.axes.patches.remove(self.star_center_patch)
            self.star_center_patch = None
        if self.star_aperture_patch is not None:
            self.ztv_frame.primary_image_panel.axes.patches.remove(self.star_aperture_patch)
            self.star_aperture_patch = None
        if self.sky_aperture_patch is not None:
            self.ztv_frame.primary_image_panel.axes.patches.remove(self.sky_aperture_patch)
            self.sky_aperture_patch = None
        self.ztv_frame.primary_image_panel.figure.canvas.draw()
        self.hideshow_button.SetLabel(u"Show")
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def remove_overplot_on_image(self, msg=None):
        if self.primary_image_patch is not None:
            self.ztv_frame.primary_image_panel.axes.patches.remove(self.primary_image_patch)
        self.ztv_frame.primary_image_panel.figure.canvas.draw()
        self.primary_image_patch = None
        self.hideshow_button.SetLabel(u"Show")
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def on_button_release(self, event):
        if event.button == 1:  # left button
            if self.cursor_mode == 'Zoom':
                # this catches for the first click-release of a double-click
                if (time.time() - self.zoom_start_timestamp) > self.max_doubleclick_sec:
                    # this catches for a long click-and-release without motion
                    x0,y0 = self.zoom_rect.get_x(),self.zoom_rect.get_y()
                    x1 = x0 + self.zoom_rect.get_width()
                    y1 = y0 + self.zoom_rect.get_height()
                    if hasattr(event, 'xdata') and event.xdata is not None:
                        x1 = event.xdata
                    if hasattr(event, 'ydata') and event.ydata is not None:
                        y1 = event.ydata
                    if abs(x0 - x1) >= 2 and abs(y0 - y1) >= 2:
                        self.center = wx.RealPoint((x0 + x1)/2., (y0 + y1)/2.)
                        panel_size = self.canvas.GetSize()
                        x_zoom_factor = panel_size.x / abs(x1 - x0)
                        y_zoom_factor = panel_size.y / abs(y1 - y0)
                        self.ztv_frame.zoom_factor = min(x_zoom_factor, y_zoom_factor)
                        self.set_and_get_xy_limits()
                if self.zoom_rect in self.axes.patches:
                    self.axes.patches.remove(self.zoom_rect)
                self.zoom_rect = None
                self.figure.canvas.draw()
            else:
                if (self.available_cursor_modes.has_key(self.cursor_mode) and
                    self.available_cursor_modes[self.cursor_mode].has_key('on_button_release')):
                    self.available_cursor_modes[self.cursor_mode]['on_button_release'](event)
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def remove_overplot_on_image(self, *args):
        if self.star_center_patch is not None:
            self.ztv_frame.primary_image_panel.axes.patches.remove(self.star_center_patch)
            self.star_center_patch = None
        if self.star_aperture_patch is not None:
            self.ztv_frame.primary_image_panel.axes.patches.remove(self.star_aperture_patch)
            self.star_aperture_patch = None
        if self.sky_aperture_patch is not None:
            self.ztv_frame.primary_image_panel.axes.patches.remove(self.sky_aperture_patch)
            self.sky_aperture_patch = None
        self.ztv_frame.primary_image_panel.figure.canvas.draw()
        self.hideshow_button.SetLabel(u"Show")
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def redraw_overplot_on_image(self, *args):
        if self.star_center_patch is not None:
            self.ztv_frame.primary_image_panel.axes.patches.remove(self.star_center_patch)
        if self.star_aperture_patch is not None:
            self.ztv_frame.primary_image_panel.axes.patches.remove(self.star_aperture_patch)
        if self.sky_aperture_patch is not None:
            self.ztv_frame.primary_image_panel.axes.patches.remove(self.sky_aperture_patch)
        self.star_center_patch = Circle([self.xcentroid, self.ycentroid], 0.125, color=self.aprad_color)
        self.ztv_frame.primary_image_panel.axes.add_patch(self.star_center_patch)
        self.star_aperture_patch = Circle([self.xcentroid, self.ycentroid], self.aprad, color=self.aprad_color, alpha=self.alpha)
        self.ztv_frame.primary_image_panel.axes.add_patch(self.star_aperture_patch)
        self.sky_aperture_patch = Wedge([self.xcentroid, self.ycentroid], self.skyradout, 0., 360., 
                                        width=self.skyradout - self.skyradin, color=self.skyrad_color, alpha=self.alpha)
        self.ztv_frame.primary_image_panel.axes.add_patch(self.sky_aperture_patch)
        self.ztv_frame.primary_image_panel.figure.canvas.draw()
        self.hideshow_button.SetLabel(u"Hide")
项目:Doc-Analysis-Public-Data    作者:AdnanMuhib    | 项目源码 | 文件源码
def draw_prediction(self, arr, img, file_name):
        image = np.array(Image.open(img))
        fig, ax = plt.subplots(1)
        ax.imshow(image)
        for items in arr:
            # If it was predicted correctly table so green
            if (items.prediction == 1) and (items.table == 1):
                rect = patches.Rectangle((items.x, items.y),
                                     items.width, items.height,
                                     linewidth=1, edgecolor='g',
                                               facecolor='none')
                ax.add_patch(rect)
            # If it was predicted correctly non table so blue 
            elif(items.prediction == 0) and (items.table == 0):
                rect = patches.Rectangle((items.x, items.y),
                                     items.width, items.height,
                                     linewidth=1, edgecolor='b',
                                               facecolor='none')
                ax.add_patch(rect)
            # If it was predicted incorrectly table so red
            elif(items.prediction == 1) and (items.table == 0):
                rect = patches.Rectangle((items.x, items.y),
                                     items.width, items.height,
                                     linewidth=1, edgecolor='r',
                                               facecolor='none')
                ax.add_patch(rect)
            # If it was predicted incorrectly non-table so yellow
            elif(items.prediction == 0) and (items.table == 1):
                rect = patches.Rectangle((items.x, items.y),
                                     items.width, items.height,
                                     linewidth=1, edgecolor='y',
                                               facecolor='none')
                ax.add_patch(rect)
        plt.savefig(file_name + "_post_processor.png", transparent=True, dpi=300)
        plt.close()
        return

##############################################################################################
########################################END###################################################
##############################################################################################
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def test_hist_bins_legacy(self):
        df = DataFrame(np.random.randn(10, 2))
        ax = df.hist(bins=2)[0][0]
        self.assertEqual(len(ax.patches), 2)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def test_radviz(self):
        from pandas.tools.plotting import radviz
        from matplotlib import cm

        df = self.iris
        _check_plot_works(radviz, frame=df, class_column='Name')

        rgba = ('#556270', '#4ECDC4', '#C7F464')
        ax = _check_plot_works(
            radviz, frame=df, class_column='Name', color=rgba)
        # skip Circle drawn as ticks
        patches = [p for p in ax.patches[:20] if p.get_label() != '']
        self._check_colors(
            patches[:10], facecolors=rgba, mapping=df['Name'][:10])

        cnames = ['dodgerblue', 'aquamarine', 'seagreen']
        _check_plot_works(radviz, frame=df, class_column='Name', color=cnames)
        patches = [p for p in ax.patches[:20] if p.get_label() != '']
        self._check_colors(patches, facecolors=cnames, mapping=df['Name'][:10])

        _check_plot_works(radviz, frame=df,
                          class_column='Name', colormap=cm.jet)
        cmaps = lmap(cm.jet, np.linspace(0, 1, df['Name'].nunique()))
        patches = [p for p in ax.patches[:20] if p.get_label() != '']
        self._check_colors(patches, facecolors=cmaps, mapping=df['Name'][:10])

        colors = [[0., 0., 1., 1.],
                  [0., 0.5, 1., 1.],
                  [1., 0., 0., 1.]]
        df = DataFrame({"A": [1, 2, 3],
                        "B": [2, 1, 3],
                        "C": [3, 2, 1],
                        "Name": ['b', 'g', 'r']})
        ax = radviz(df, 'Name', color=colors)
        handles, labels = ax.get_legend_handles_labels()
        self._check_colors(handles, facecolors=colors)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def _add_legend_handle(self, handle, label, index=None):
        from matplotlib.patches import Rectangle
        # Because fill_between isn't supported in legend,
        # specifically add Rectangle handle here
        alpha = self.kwds.get('alpha', None)
        handle = Rectangle((0, 0), 1, 1, fc=handle.get_color(), alpha=alpha)
        LinePlot._add_legend_handle(self, handle, label, index=index)
项目:pyMHT    作者:erikliland    | 项目源码 | 文件源码
def _plotCovarianceEllipse(self, eta2):
        from matplotlib.patches import Ellipse
        lambda_, _ = np.linalg.eig(self.kalmanFilter.S)
        ell = Ellipse(xy=(self.kalmanFilter.x_bar[0], self.kalmanFilter.x_bar[1]),
                      width=np.sqrt(lambda_[0]) * np.sqrt(eta2) * 2,
                      height=np.sqrt(lambda_[1]) * np.sqrt(eta2) * 2,
                      angle=np.rad2deg(np.arctan2(lambda_[1], lambda_[0])),
                      linewidth=2,
                      )
        ell.set_facecolor('none')
        ell.set_linestyle("dotted")
        ell.set_alpha(0.5)
        ax = plt.subplot(111)
        ax.add_artist(ell)
项目:tf-Faster-RCNN    作者:kevinjliang    | 项目源码 | 文件源码
def _plot_patch(ax, bbox, prob, class_name, color):
    """ Plot a rectangle (labeled with color, class_name, and prob) on the test image """

    # Calculate Bounding Box Rectangle and plot it
    height = bbox[3] - bbox[1]
    width = bbox[2] - bbox[0]
    rect = patches.Rectangle((bbox[0], bbox[1]), width, height, linewidth=2, edgecolor=color, facecolor='none')
    ax.add_patch(rect)

    # Add confidence prob and class text to box
    if prob is not None:
        ax.text(bbox[0], bbox[1] - 2,
                '{:s} {:.3f}'.format(class_name, prob),
                bbox=dict(facecolor=color, alpha=0.5),
                fontsize=8, color='white')
项目:tf-Faster-RCNN    作者:kevinjliang    | 项目源码 | 文件源码
def plot_patch(ax, patches, bbox, gt):
        if gt is True:
            color = 'g'
        else:
            color = 'r'
        # Calculate Bounding Box Rectangle and plot it
        width = bbox[3] - bbox[1]
        height = bbox[2] - bbox[0]
        rect = patches.Rectangle((bbox[1], bbox[0]), height, width, linewidth=2, edgecolor=color, facecolor='none')
        ax.add_patch(rect)
项目:tf-Faster-RCNN    作者:kevinjliang    | 项目源码 | 文件源码
def plot_img(image, gt_box):
        """ Takes an image and bounding box coordinates and displays it using matplotlib """

        # First print out image metrics
        print("Using First Image of the Batch..")
        print("Image Max Value (should be less than 1): %f" % image.max())
        print("Image Min Value (should be greater than -1): %f" % image.min())
        print("Image Mean Value (should be equal to 0): %f" % image.mean())
        print("Digit: %d" % gt_box[4])

        # Import matplotlib and setup axes
        import matplotlib
        matplotlib.use('TkAgg')  # For Mac OS
        import matplotlib.pyplot as plt
        import matplotlib.patches as patches
        fig, ax = plt.subplots(1)

        # Plot Image First
        ax.imshow(np.squeeze(image), cmap="gray")

        # Calculate Bounding Box Rectangle and plot it
        width = gt_box[3] - gt_box[1]
        height = gt_box[2] - gt_box[0]
        rect = patches.Rectangle((gt_box[1], gt_box[0]), height, width, linewidth=2, edgecolor='r', facecolor='none')
        ax.add_patch(rect)

        # Display Final composite image
        plt.show()
项目:kvae    作者:simonkamronn    | 项目源码 | 文件源码
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
项目:em_examples    作者:geoscixyz    | 项目源码 | 文件源码
def sumCylinderCharges(xc, zc, r, qSecondary):
    chargeRegionVerts = getCylinderPoints(xc, zc, r+0.5)

    codes = chargeRegionVerts.shape[0]*[Path.LINETO]
    codes[0] = Path.MOVETO
    codes[-1] = Path.CLOSEPOLY

    chargeRegionPath = Path(chargeRegionVerts, codes)
    CCLocs = mesh.gridCC
    chargeRegionInsideInd = np.where(chargeRegionPath.contains_points(CCLocs))

    plateChargeLocs = CCLocs[chargeRegionInsideInd]
    plateCharge = qSecondary[chargeRegionInsideInd]
    posInd = np.where(plateCharge >= 0)
    negInd = np.where(plateCharge < 0)
    qPos = Utils.mkvc(plateCharge[posInd])
    qNeg = Utils.mkvc(plateCharge[negInd])

    qPosLoc = plateChargeLocs[posInd,:][0]
    qNegLoc = plateChargeLocs[negInd,:][0]

    qPosData = np.vstack([qPosLoc[:,0], qPosLoc[:,1], qPos]).T
    qNegData = np.vstack([qNegLoc[:,0], qNegLoc[:,1], qNeg]).T

    if qNeg.shape == (0,) or qPos.shape == (0,):
        qNegAvgLoc = np.r_[-10, -10]
        qPosAvgLoc = np.r_[+10, -10]
    else:
        qNegAvgLoc = np.average(qNegLoc, axis=0, weights=qNeg)
        qPosAvgLoc = np.average(qPosLoc, axis=0, weights=qPos)

    qPosSum = np.sum(qPos)
    qNegSum = np.sum(qNeg)

    # # Check things by plotting
    # fig = plt.figure()
    # ax = fig.add_subplot(111)
    # platePatch = patches.PathPatch(platePath, facecolor='none', lw=2)
    # ax.add_patch(platePatch)
    # chargeRegionPatch = patches.PathPatch(chargeRegionPath, facecolor='none', lw=2)
    # ax.add_patch(chargeRegionPatch)
    # plt.scatter(qNegAvgLoc[0],qNegAvgLoc[1],color='b')
    # plt.scatter(qPosAvgLoc[0],qPosAvgLoc[1],color='r')
    # ax.set_xlim(-15,5)
    # ax.set_ylim(-25,-5)
    # plt.axes().set_aspect('equal')
    # plt.show()

    return qPosSum, qNegSum, qPosAvgLoc, qNegAvgLoc

# The only thing we need to make it work is a 2.5D field object in SimPEG
项目:em_examples    作者:geoscixyz    | 项目源码 | 文件源码
def sumCylinderCharges(xc, zc, r, qSecondary):
    chargeRegionVerts = getCylinderPoints(xc, zc, r+0.5)

    codes = chargeRegionVerts.shape[0]*[Path.LINETO]
    codes[0] = Path.MOVETO
    codes[-1] = Path.CLOSEPOLY

    chargeRegionPath = Path(chargeRegionVerts, codes)
    CCLocs = mesh.gridCC
    chargeRegionInsideInd = np.where(chargeRegionPath.contains_points(CCLocs))

    plateChargeLocs = CCLocs[chargeRegionInsideInd]
    plateCharge = qSecondary[chargeRegionInsideInd]
    posInd = np.where(plateCharge >= 0)
    negInd = np.where(plateCharge < 0)
    qPos = Utils.mkvc(plateCharge[posInd])
    qNeg = Utils.mkvc(plateCharge[negInd])

    qPosLoc = plateChargeLocs[posInd,:][0]
    qNegLoc = plateChargeLocs[negInd,:][0]

    qPosData = np.vstack([qPosLoc[:,0], qPosLoc[:,1], qPos]).T
    qNegData = np.vstack([qNegLoc[:,0], qNegLoc[:,1], qNeg]).T

    if qNeg.shape == (0,) or qPos.shape == (0,):
        qNegAvgLoc = np.r_[-10, -10]
        qPosAvgLoc = np.r_[+10, -10]
    else:
        qNegAvgLoc = np.average(qNegLoc, axis=0, weights=qNeg)
        qPosAvgLoc = np.average(qPosLoc, axis=0, weights=qPos)

    qPosSum = np.sum(qPos)
    qNegSum = np.sum(qNeg)

    # # Check things by plotting
    # fig = plt.figure()
    # ax = fig.add_subplot(111)
    # platePatch = patches.PathPatch(platePath, facecolor='none', lw=2)
    # ax.add_patch(platePatch)
    # chargeRegionPatch = patches.PathPatch(chargeRegionPath, facecolor='none', lw=2)
    # ax.add_patch(chargeRegionPatch)
    # plt.scatter(qNegAvgLoc[0],qNegAvgLoc[1],color='b')
    # plt.scatter(qPosAvgLoc[0],qPosAvgLoc[1],color='r')
    # ax.set_xlim(-15,5)
    # ax.set_ylim(-25,-5)
    # plt.axes().set_aspect('equal')
    # plt.show()

    return qPosSum, qNegSum, qPosAvgLoc, qNegAvgLoc
项目:TradingGym    作者:Yvictor    | 项目源码 | 文件源码
def _plot_trading(self):
        price_x = list(range(len(self.price[:self.step_st+self.obs_len])))
        self.price_plot = self.ax.plot(price_x, self.price[:self.step_st+self.obs_len], c=(0, 0.68, 0.95, 0.9),zorder=1)
        # maybe seperate up down color
        #self.price_plot = self.ax.plot(price_x, self.price[:self.step_st+self.obs_len], c=(0, 0.75, 0.95, 0.9),zorder=1)
        self.features_plot = [self.ax3.plot(price_x, self.obs_features[:self.step_st+self.obs_len, i], 
                                            c=self.features_color[i])[0] for i in range(self.feature_len)]
        rect_high = self.obs_price.max() - self.obs_price.min()
        self.target_box = self.ax.add_patch(
                            patches.Rectangle(
                            (self.step_st, self.obs_price.min()), self.obs_len, rect_high,
                            label='observation',edgecolor=(0.9, 1, 0.2, 0.8),facecolor=(0.95,1,0.1,0.3),
                            linestyle='-',linewidth=1.5,
                            fill=True)
                            )     # remove background)
        self.fluc_reward_plot_p = self.ax2.fill_between(price_x, 0, self.reward_fluctuant_arr[:self.step_st+self.obs_len],
                                                        where=self.reward_fluctuant_arr[:self.step_st+self.obs_len]>=0, 
                                                        facecolor=(1, 0.8, 0, 0.2), edgecolor=(1, 0.8, 0, 0.9), linewidth=0.8)
        self.fluc_reward_plot_n = self.ax2.fill_between(price_x, 0, self.reward_fluctuant_arr[:self.step_st+self.obs_len],
                                                        where=self.reward_fluctuant_arr[:self.step_st+self.obs_len]<=0, 
                                                        facecolor=(0, 1, 0.8, 0.2), edgecolor=(0, 1, 0.8, 0.9), linewidth=0.8)
        self.posi_plot_long = self.ax2.fill_between(price_x, 0, self.posi_arr[:self.step_st+self.obs_len], 
                                                    where=self.posi_arr[:self.step_st+self.obs_len]>=0, 
                                                    facecolor=(1, 0.5, 0, 0.2), edgecolor=(1, 0.5, 0, 0.9), linewidth=1)
        self.posi_plot_short = self.ax2.fill_between(price_x, 0, self.posi_arr[:self.step_st+self.obs_len], 
                                                     where=self.posi_arr[:self.step_st+self.obs_len]<=0, 
                                                     facecolor=(0, 0.5, 1, 0.2), edgecolor=(0, 0.5, 1, 0.9), linewidth=1)
        self.reward_plot_p = self.ax2.fill_between(price_x, 0, 
                                                   self.reward_arr[:self.step_st+self.obs_len].cumsum(),
                                                   where=self.reward_arr[:self.step_st+self.obs_len].cumsum()>=0,
                                                   facecolor=(1, 0, 0, 0.2), edgecolor=(1, 0, 0, 0.9), linewidth=1)
        self.reward_plot_n = self.ax2.fill_between(price_x, 0, 
                                                   self.reward_arr[:self.step_st+self.obs_len].cumsum(),
                                                   where=self.reward_arr[:self.step_st+self.obs_len].cumsum()<=0,
                                                   facecolor=(0, 1, 0, 0.2), edgecolor=(0, 1, 0, 0.9), linewidth=1)

        trade_x = self.posi_variation_arr.nonzero()[0]
        trade_x_buy = [i for i in trade_x if self.posi_variation_arr[i]>0]
        trade_x_sell = [i for i in trade_x if self.posi_variation_arr[i]<0]
        trade_y_buy = [self.price[i] for i in trade_x_buy]
        trade_y_sell =  [self.price[i] for i in trade_x_sell]
        trade_color_buy = [self._gen_trade_color(i) for i in trade_x_buy] 
        trade_color_sell = [self._gen_trade_color(i) for i in trade_x_sell]
        self.trade_plot_buy = self.ax.scatter(x=trade_x_buy, y=trade_y_buy, s=100, marker='^', 
                                              c=trade_color_buy, edgecolors=(1,0,0,0.9), zorder=2)
        self.trade_plot_sell = self.ax.scatter(x=trade_x_sell, y=trade_y_sell, s=100, marker='v', 
                                               c=trade_color_sell, edgecolors=(0,1,0,0.9), zorder=2)
项目:TradingGym    作者:Yvictor    | 项目源码 | 文件源码
def _plot_trading(self):
        price_x = list(range(len(self.price[:self.step_st+self.obs_len])))
        self.price_plot = self.ax.plot(price_x, self.price[:self.step_st+self.obs_len], c=(0, 0.68, 0.95, 0.9),zorder=1)
        # maybe seperate up down color
        #self.price_plot = self.ax.plot(price_x, self.price[:self.step_st+self.obs_len], c=(0, 0.75, 0.95, 0.9),zorder=1)
        self.features_plot = [self.ax3.plot(price_x, self.obs_features[:self.step_st+self.obs_len, i], 
                                            c=self.features_color[i])[0] for i in range(self.feature_len)]
        rect_high = self.obs_price.max() - self.obs_price.min()
        self.target_box = self.ax.add_patch(
                            patches.Rectangle(
                            (self.step_st, self.obs_price.min()), self.obs_len, rect_high,
                            label='observation',edgecolor=(0.9, 1, 0.2, 0.8),facecolor=(0.95,1,0.1,0.3),
                            linestyle='-',linewidth=1.5,
                            fill=True)
                            )     # remove background)
        self.fluc_reward_plot_p = self.ax2.fill_between(price_x, 0, self.reward_fluctuant_arr[:self.step_st+self.obs_len],
                                                        where=self.reward_fluctuant_arr[:self.step_st+self.obs_len]>=0, 
                                                        facecolor=(1, 0.8, 0, 0.2), edgecolor=(1, 0.8, 0, 0.9), linewidth=0.8)
        self.fluc_reward_plot_n = self.ax2.fill_between(price_x, 0, self.reward_fluctuant_arr[:self.step_st+self.obs_len],
                                                        where=self.reward_fluctuant_arr[:self.step_st+self.obs_len]<=0, 
                                                        facecolor=(0, 1, 0.8, 0.2), edgecolor=(0, 1, 0.8, 0.9), linewidth=0.8)
        self.posi_plot_long = self.ax2.fill_between(price_x, 0, self.posi_arr[:self.step_st+self.obs_len], 
                                                    where=self.posi_arr[:self.step_st+self.obs_len]>=0, 
                                                    facecolor=(1, 0.5, 0, 0.2), edgecolor=(1, 0.5, 0, 0.9), linewidth=1)
        self.posi_plot_short = self.ax2.fill_between(price_x, 0, self.posi_arr[:self.step_st+self.obs_len], 
                                                     where=self.posi_arr[:self.step_st+self.obs_len]<=0, 
                                                     facecolor=(0, 0.5, 1, 0.2), edgecolor=(0, 0.5, 1, 0.9), linewidth=1)
        self.reward_plot_p = self.ax2.fill_between(price_x, 0, 
                                                   self.reward_arr[:self.step_st+self.obs_len].cumsum(),
                                                   where=self.reward_arr[:self.step_st+self.obs_len].cumsum()>=0,
                                                   facecolor=(1, 0, 0, 0.2), edgecolor=(1, 0, 0, 0.9), linewidth=1)
        self.reward_plot_n = self.ax2.fill_between(price_x, 0, 
                                                   self.reward_arr[:self.step_st+self.obs_len].cumsum(),
                                                   where=self.reward_arr[:self.step_st+self.obs_len].cumsum()<=0,
                                                   facecolor=(0, 1, 0, 0.2), edgecolor=(0, 1, 0, 0.9), linewidth=1)

        trade_x = self.posi_variation_arr.nonzero()[0]
        trade_x_buy = [i for i in trade_x if self.posi_variation_arr[i]>0]
        trade_x_sell = [i for i in trade_x if self.posi_variation_arr[i]<0]
        trade_y_buy = [self.price[i] for i in trade_x_buy]
        trade_y_sell =  [self.price[i] for i in trade_x_sell]
        trade_color_buy = [self._gen_trade_color(i) for i in trade_x_buy] 
        trade_color_sell = [self._gen_trade_color(i) for i in trade_x_sell]
        self.trade_plot_buy = self.ax.scatter(x=trade_x_buy, y=trade_y_buy, s=100, marker='^', 
                                              c=trade_color_buy, edgecolors=(1,0,0,0.9), zorder=2)
        self.trade_plot_sell = self.ax.scatter(x=trade_x_sell, y=trade_y_sell, s=100, marker='v', 
                                               c=trade_color_sell, edgecolors=(0,1,0,0.9), zorder=2)
项目:nanopores    作者:mitschabaude    | 项目源码 | 文件源码
def porestreamlines(polygon=None, rx=10., ry=10., Nx=100, Ny=100,
                    maxvalue=None, **fields):
    "streamlines plot of vector field around nanopore"

    # interpolate on regular mesh symmetric w.r.t. center axis
    mesh2D = nanopores.RectangleMesh([-rx-0.1,-ry-0.1], [rx+0.1,ry+0.1], Nx, Ny)
    fields2 = nanopores.convert2D(mesh2D, *(fields.values()))

    # prepare polygon and copy to left half
    settings = dict(closed=True, facecolor="#eeeeee", linewidth=3.,
                    edgecolor="black")
    if polygon is not None:
        polygon = np.array(polygon)
        polygon_m = np.column_stack([-polygon[:,0], polygon[:,1]])

    # prepare plots
    Ny += 1
    Nx += 1
    Y, X = np.mgrid[-ry:ry:Ny*1j, -rx:rx:Nx*1j]
    U = np.zeros((Ny,Nx))
    V = np.zeros((Ny,Nx))
    formt = matplotlib.ticker.FuncFormatter(fmt)
    ticks = [0] + [10**n for n in range(-16, -9)]

    # determine uniform color range from fields (maybe round to nearest 10-power)
    if maxvalue is None:
        maxvalue = max(dolfin.norm(F.vector(), "linf") for F in fields2)
        #maxvalue = 10**int(np.log10(maxvalue))

    for i, F in enumerate(fields2):
        Fstr = fields.keys()[i]
        fig, ax = plt.subplots(figsize=(5, 4.5), num=Fstr)

        # fill array with function values
        for y in range(Ny):
            for x in range(Nx):
                f = F(X[y][x], Y[y][x])
                U[y][x] = f[0]
                V[y][x] = f[1]

        # streamplot with logarithmic scale
        strength = np.sqrt(U*U+V*V)
        norm = matplotlib.colors.SymLogNorm(linthresh=ticks[1], linscale=1.0,
                                            vmin=0., vmax=maxvalue)
        strm = plt.streamplot(X, Y, U, V, arrowsize=1.5, linewidth=1.5, density=1.5,
                              cmap=cm.viridis, color=strength, norm=norm)
        plt.colorbar(strm.lines, ticks=ticks, format=formt)
        plt.xlabel('x [nm]') #, fontsize=20)
        plt.ylabel('z [nm]') #, fontsize=20)

        # plot pore polygon on top
        if polygon is not None:
            patch = patches.Polygon(polygon, **settings)
            patchm = patches.Polygon(polygon_m, **settings)
            patch.set_zorder(10)
            patchm.set_zorder(10)
            ax.add_patch(patch)
            ax.add_patch(patchm)
项目:rec-attend-public    作者:renmengye    | 项目源码 | 文件源码
def plot_input(fname, x, y_gt, s_gt, max_items_per_row=9):
  """Plot input, transformed input and output groundtruth sequence.
    """
  num_ex = y_gt.shape[0]
  num_items = y_gt.shape[1]
  num_row, num_col, calc = calc_row_col(
      num_ex, num_items, max_items_per_row=max_items_per_row)

  f1, axarr = plt.subplots(num_row, num_col, figsize=(20, num_row))
  set_axis_off(axarr, num_row, num_col)
  cmap = ['r', 'y', 'c', 'g', 'm']

  for ii in xrange(num_ex):
    _x = x[ii]
    _x = _x[:, :, [2, 1, 0]]
    # _x = x[ii, :, :, [2, 1, 0]]
    for jj in xrange(num_items):
      row, col = calc(ii, jj)
      axarr[row, col].imshow(_x)
      nz = y_gt[ii, jj].nonzero()
      if nz[0].size > 0:
        top_left_x = nz[1].min()
        top_left_y = nz[0].min()
        bot_right_x = nz[1].max() + 1
        bot_right_y = nz[0].max() + 1
        axarr[row, col].add_patch(
            patches.Rectangle(
                (top_left_x, top_left_y),
                bot_right_x - top_left_x,
                bot_right_y - top_left_y,
                fill=False,
                color=cmap[jj % len(cmap)]))
        axarr[row, col].add_patch(
            patches.Rectangle(
                (top_left_x, top_left_y - 25),
                25,
                25,
                fill=True,
                color=cmap[jj % len(cmap)]))
        axarr[row, col].text(
            top_left_x + 5, top_left_y - 5, '{}'.format(jj), size=5)

  plt.tight_layout(pad=2.0, w_pad=0.0, h_pad=0.0)
  plt.savefig(fname, dpi=150)
  plt.close('all')
  pass
项目:RVO_Py_MAS    作者:MengGuo    | 项目源码 | 文件源码
def visualize_traj_dynamic(ws_model, X, U, goal, time = None, name=None):
    figure = pyplot.figure()
    ax = figure.add_subplot(1,1,1)
    cmap = get_cmap(len(X))
    # plot obstacles
    for hole in ws_model['circular_obstacles']:
        srec = matplotlib.patches.Rectangle(
                (hole[0]-hole[2], hole[1]-hole[2]),
                2*hole[2], 2*hole[2],
                facecolor= 'red',
                fill = True,
                alpha=1)
        ax.add_patch(srec)
    # ---plot traj---
    for i in range(0,len(X)):
        #-------plot car
        robot = matplotlib.patches.Circle(
            (X[i][0],X[i][1]),
            radius = ws_model['robot_radius'],
            facecolor=cmap(i),
            edgecolor='black',
            linewidth=1.0,
            ls='solid',
            alpha=1,
            zorder=2)
        ax.add_patch(robot)
        #----------plot velocity
        ax.arrow(X[i][0], X[i][1], U[i][0], U[i][1], head_width=0.05, head_length=0.1, fc=cmap(i), ec=cmap(i))
        ax.text(X[i][0]-0.1, X[i][1]-0.1, r'$%s$' %i, fontsize=15, fontweight = 'bold',zorder=3)
        ax.plot([goal[i][0]], [goal[i][1]], '*', color=cmap(i), markersize =15,linewidth=3.0)
    if time:
        ax.text(2,5.5,'$t=%.1f s$' %time,
                fontsize=20, fontweight ='bold')                
    # ---set axes ---
    ax.set_aspect('equal')
    ax.set_xlim(-1.0, 6.0)
    ax.set_ylim(-1.0, 6.0)
    ax.set_xlabel(r'$x (m)$')
    ax.set_ylabel(r'$y (m)$')
    ax.grid('on')
    if name:
        pyplot.savefig(name, dpi = 200)
        #pyplot.savefig(name,bbox_inches='tight')
    pyplot.cla()
    pyplot.close(figure)
    return figure
项目:Particle-Picking-Cryo-EM    作者:hqythu    | 项目源码 | 文件源码
def main():
    # matplotlib.use('qt5agg')
    import matplotlib.pyplot as plt
    from matplotlib.patches import Rectangle

    init_model()
    MAT_DIR = './mat/test'
    LABEL_DIR = './label/test'
    for dirpath, dirnames, filenames in os.walk(MAT_DIR):
        print(dirpath)
        for filename in filenames:
            if filename == 'full.mat':
                data = sio.loadmat(os.path.join(dirpath, filename))
                img = data['data']
                centers = detection(img)
                img_id = dirpath.split('/')[-1]
                label_file = os.path.join(LABEL_DIR, img_id + '.mat')
                labels = sio.loadmat(label_file)['label']
                distance = (lambda x1, y1, x2, y2: abs(x1 - x2) + abs(y1 - y2))

                centers = cluster(centers)

                TP = 0
                for x, y in labels:
                    for x_, y_ in centers:
                        if distance(x, y, x_, y_) < 36:
                            TP += 1
                            break
                precision = float(TP) / len(centers)
                recall = float(TP) / len(labels)
                f_score = 2 * (precision * recall) / (precision + recall)
                six.print_(precision, recall, f_score)

                f = open(dirpath.split('/')[-1] + '-predict.txt', 'w')
                for x, y in centers:
                    f.write(str(x) + ' ' + str(y) + '\n')
                f.close()
                f = open(dirpath.split('/')[-1] + '-label.txt', 'w')
                for x, y in labels:
                    f.write(str(x) + ' ' + str(y) + '\n')
                f.close()

                # img = img / np.float32(256)
                # plt.imshow(img, cmap=plt.cm.gray)
                # currentAxis = plt.gca()
                # for x, y in labels:
                #     currentAxis.add_patch(Rectangle((y - 90, x - 90),
                #                                     180, 180, fill=None,
                #                                     alpha=1, color='blue'))
                # for x, y in centers:
                #     currentAxis.add_patch(Rectangle((y - 90, x - 90),
                #                                     180, 180, fill=None,
                #                                     alpha=1, color='red'))
                # plt.show()
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def test_hist_df_legacy(self):
        from matplotlib.patches import Rectangle
        _check_plot_works(self.hist_df.hist)

        # make sure layout is handled
        df = DataFrame(randn(100, 3))
        axes = _check_plot_works(df.hist, grid=False)
        self._check_axes_shape(axes, axes_num=3, layout=(2, 2))
        self.assertFalse(axes[1, 1].get_visible())

        df = DataFrame(randn(100, 1))
        _check_plot_works(df.hist)

        # make sure layout is handled
        df = DataFrame(randn(100, 6))
        axes = _check_plot_works(df.hist, layout=(4, 2))
        self._check_axes_shape(axes, axes_num=6, layout=(4, 2))

        # make sure sharex, sharey is handled
        _check_plot_works(df.hist, sharex=True, sharey=True)

        # handle figsize arg
        _check_plot_works(df.hist, figsize=(8, 10))

        # check bins argument
        _check_plot_works(df.hist, bins=5)

        # make sure xlabelsize and xrot are handled
        ser = df[0]
        xf, yf = 20, 18
        xrot, yrot = 30, 40
        axes = ser.hist(xlabelsize=xf, xrot=xrot, ylabelsize=yf, yrot=yrot)
        self._check_ticks_props(axes, xlabelsize=xf, xrot=xrot,
                                ylabelsize=yf, yrot=yrot)

        xf, yf = 20, 18
        xrot, yrot = 30, 40
        axes = df.hist(xlabelsize=xf, xrot=xrot, ylabelsize=yf, yrot=yrot)
        self._check_ticks_props(axes, xlabelsize=xf, xrot=xrot,
                                ylabelsize=yf, yrot=yrot)

        tm.close()
        # make sure kwargs to hist are handled
        ax = ser.hist(normed=True, cumulative=True, bins=4)
        # height of last bin (index 5) must be 1.0
        rects = [x for x in ax.get_children() if isinstance(x, Rectangle)]
        self.assertAlmostEqual(rects[-1].get_height(), 1.0)

        tm.close()
        ax = ser.hist(log=True)
        # scale of y must be 'log'
        self._check_ax_scales(ax, yaxis='log')

        tm.close()

        # propagate attr exception from matplotlib.Axes.hist
        with tm.assertRaises(AttributeError):
            ser.hist(foo='bar')
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def test_grouped_hist_legacy(self):
        from matplotlib.patches import Rectangle

        df = DataFrame(randn(500, 2), columns=['A', 'B'])
        df['C'] = np.random.randint(0, 4, 500)
        df['D'] = ['X'] * 500

        axes = plotting.grouped_hist(df.A, by=df.C)
        self._check_axes_shape(axes, axes_num=4, layout=(2, 2))

        tm.close()
        axes = df.hist(by=df.C)
        self._check_axes_shape(axes, axes_num=4, layout=(2, 2))

        tm.close()
        # group by a key with single value
        axes = df.hist(by='D', rot=30)
        self._check_axes_shape(axes, axes_num=1, layout=(1, 1))
        self._check_ticks_props(axes, xrot=30)

        tm.close()
        # make sure kwargs to hist are handled
        xf, yf = 20, 18
        xrot, yrot = 30, 40
        axes = plotting.grouped_hist(df.A, by=df.C, normed=True,
                                     cumulative=True, bins=4,
                                     xlabelsize=xf, xrot=xrot,
                                     ylabelsize=yf, yrot=yrot)
        # height of last bin (index 5) must be 1.0
        for ax in axes.ravel():
            rects = [x for x in ax.get_children() if isinstance(x, Rectangle)]
            height = rects[-1].get_height()
            self.assertAlmostEqual(height, 1.0)
        self._check_ticks_props(axes, xlabelsize=xf, xrot=xrot,
                                ylabelsize=yf, yrot=yrot)

        tm.close()
        axes = plotting.grouped_hist(df.A, by=df.C, log=True)
        # scale of y must be 'log'
        self._check_ax_scales(axes, yaxis='log')

        tm.close()
        # propagate attr exception from matplotlib.Axes.hist
        with tm.assertRaises(AttributeError):
            plotting.grouped_hist(df.A, by=df.C, foo='bar')

        with tm.assert_produces_warning(FutureWarning):
            df.hist(by='C', figsize='default')
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def _make_plot(self):
        colors = self._get_colors(
            num_colors=len(self.data), color_kwds='colors')
        self.kwds.setdefault('colors', colors)

        for i, (label, y) in enumerate(self._iter_data()):
            ax = self._get_ax(i)
            if label is not None:
                label = com.pprint_thing(label)
                ax.set_ylabel(label)

            kwds = self.kwds.copy()

            def blank_labeler(label, value):
                if value == 0:
                    return ''
                else:
                    return label

            idx = [com.pprint_thing(v) for v in self.data.index]
            labels = kwds.pop('labels', idx)
            # labels is used for each wedge's labels
            # Blank out labels for values of 0 so they don't overlap
            # with nonzero wedges
            if labels is not None:
                blabels = [blank_labeler(l, value) for
                           l, value in zip(labels, y)]
            else:
                blabels = None
            results = ax.pie(y, labels=blabels, **kwds)

            if kwds.get('autopct', None) is not None:
                patches, texts, autotexts = results
            else:
                patches, texts = results
                autotexts = []

            if self.fontsize is not None:
                for t in texts + autotexts:
                    t.set_fontsize(self.fontsize)

            # leglabels is used for legend labels
            leglabels = labels if labels is not None else idx
            for p, l in zip(patches, leglabels):
                self._add_legend_handle(p, l)
项目:matplotlib    作者:DaveL17    | 项目源码 | 文件源码
def chartMultilineText(self, dev, p_dict, k_dict, text_to_plot, return_queue):
        """"""

        log = {'Threaddebug': [], 'Debug': [], 'Info': [], 'Warning': [], 'Critical': []}
        try:

            import textwrap

            if self.verboseLogging:
                log['Debug'].append(u"{0:<19}{1}".format("p_dict: ", [(k, v) for (k, v) in sorted(p_dict.items())]))
                log['Debug'].append(u"{0:<19}{1}".format("k_dict: ", [(k, v) for (k, v) in sorted(k_dict.items())]))

            p_dict['textColor'] = r"#{0}".format(p_dict['textColor'].replace(' ', '').replace('#', ''))

            # If the value to be plotted is empty, use the default text from the device configuration.
            if len(text_to_plot) <= 1:
                text_to_plot = unicode(p_dict['defaultText'])
            else:
                # The cleanUpString method tries to remove some potential ugliness from the text to be plotted. It's optional--defaulted to on. No need to call this if the default text
                # is used.
                if p_dict['cleanTheText']:
                    text_to_plot = self.cleanUpString(text_to_plot)

            # Wrap the text and prepare it for plotting.
            text_to_plot = textwrap.fill(text_to_plot, int(p_dict['numberOfCharacters']), replace_whitespace=p_dict['cleanTheText'])

            ax = self.chartMakeFigure(p_dict['figureWidth'], p_dict['figureHeight'], p_dict)

            ax.text(0.01, 0.95, text_to_plot, transform=ax.transAxes, color=p_dict['textColor'], fontname=p_dict['fontMain'], fontsize=p_dict['multilineFontSize'],
                    verticalalignment='top')

            ax.axes.get_xaxis().set_visible(False)
            ax.axes.get_yaxis().set_visible(False)

            if not p_dict['textAreaBorder']:
                [s.set_visible(False) for s in ax.spines.values()]

            # Transparent Charts Fill
            if p_dict['transparent_charts'] and p_dict['transparent_filled']:
                ax.add_patch(patches.Rectangle((0, 0), 1, 1, transform=ax.transAxes, facecolor=p_dict['faceColor'], zorder=1))

            # Chart title
            plt.title(p_dict['chartTitle'], position=(0.5, 1.0), **k_dict['k_title_font'])

            plt.tight_layout(pad=1)
            plt.subplots_adjust(left=0.02, right=0.98, top=0.9, bottom=0.05)

            if p_dict['fileName'] != '':
                plt.savefig(u'{0}{1}'.format(p_dict['chartPath'], p_dict['fileName']), **k_dict['k_plot_fig'])

            plt.clf()
            plt.close('all')

            return_queue.put({'Error': False, 'Log': log, 'Message': 'updated successfully.', 'Name': dev.name})

        except (KeyError, IndexError, ValueError, UnicodeEncodeError) as sub_error:
            return_queue.put({'Error': True, 'Log': log, 'Message': str(sub_error), 'Name': dev.name})
        except Exception as sub_error:
            return_queue.put({'Error': True, 'Log': log, 'Message': str(sub_error), 'Name': dev.name})
项目:P_MDP_TG    作者:MengGuo    | 项目源码 | 文件源码
def visualize_run(XX, LL, UU, MM, name=None):
    #-----plot the sequence of states for the test run    
    figure = plt.figure()
    ax = figure.add_subplot(1,1,1)
    N = len(XX)
    #print 'N: %s' %N
    #----
    for n in xrange(0, N):
        X = list(XX[n])
        L = list(LL[n])
        U = list(UU[n])
        M = list(MM[n])
        K = len(X)
        #print 'K: %s' %K
        RAD = 0.3
        for k in xrange(0, K):
            if M[k] == 0:
                color = 'blue'
            if M[k] == 1:
                color = 'magenta'
            if M[k] == 2:
                color = 'black'
            #----
            rec = matplotlib.patches.Rectangle((4*k-RAD, 3*n-RAD),
                                               RAD*2, RAD*2,
                                               fill = False,
                                               edgecolor = color,
                                               linewidth = 3,
                                               ls = 'solid',
                                               alpha =1)
            ax.add_patch(rec)
            setstr = r''
            for s in L[k]:
                setstr += s
                setstr +=','
            ax.text(4*k-RAD, 3*n+RAD*4, r'$(%s, \{%s\})$' %(str(X[k]), str(setstr)), fontsize = 6, fontweight = 'bold')
            #----
            if (k<= K-2):
                line = matplotlib.lines.Line2D([4*k+RAD,4*k+4-RAD],
                                               [3*n, 3*n],
                                               linestyle='-',
                                               linewidth=1,
                                               color='black')
                ax.add_line(line)
                actstr = r''
                for s in U[k]:
                    actstr += s
                ax.text(4*k+2, 3*n+RAD, r'%s' %str(actstr), fontsize = 6, fontweight = 'bold')
    ax.set_aspect(0.7)
    ax.set_xlim(-1, 4*K)
    ax.set_ylim(-1, 3*N)
    ax.set_xlabel(r'$state\; sequence$')
    ax.set_ylabel(r'$run$')    
    #ax.axis('off')
    if name:
        plt.savefig('%s.pdf' %name,bbox_inches='tight')
    return figure
项目:P_MDP_TG    作者:MengGuo    | 项目源码 | 文件源码
def visualize_world(WS_d, WS_node_dict, name=None):
    #----visualization for square-partitioned-workspace----
    #----see case_study.py for details----
    figure = plt.figure()
    ax = figure.add_subplot(1,1,1)
    #----- draw the workspace
    for node, prop in WS_node_dict.iteritems():
        if frozenset(['base1','base']) in prop.keys():
            text = '$Base1$'
            color = 'yellow'
        elif frozenset(['base2','base']) in prop.keys():
            text = '$Base2$'
            color = 'yellow'
        elif frozenset(['base3','base']) in prop.keys():
            text = '$Base3$'
            color = 'yellow'
        elif frozenset(['obstacle','low']) in prop.keys():
            text = '$Obs: 0.2$'
            color = '#ff8000'
        elif frozenset(['obstacle','top']) in prop.keys():
            text = '$Obs: 1.0$'
            color = 'red'
        elif frozenset(['supply',]) in prop.keys():
            text = '$Sply: %s$' %str(prop[frozenset(['supply',])])
            if prop[frozenset(['supply',])]>=0.8:
                color = '#0000ff'
            elif prop[frozenset(['supply',])]>=0.6:
                color = '#0040ff'
            elif prop[frozenset(['supply',])]>=0.4:
                color = '#0080ff'
            elif prop[frozenset(['supply',])]>=0.2:
                color = '#00bfff'
        else:
            text = None
            color = 'white'
        rec = matplotlib.patches.Rectangle((node[0]-WS_d, node[1]-WS_d),
                                               WS_d*2, WS_d*2,
                                               fill = True,
                                               facecolor = color,
                                               edgecolor = 'black',
                                               linewidth = 1,
                                               ls = '--',
                                               alpha =0.8)
        ax.add_patch(rec)
        if text:
            ax.text(node[0]-0.7, node[1], r'%s' %text, fontsize = 10, fontweight = 'bold')
    ax.set_aspect('equal')
    ax.set_xlim(0, 10)
    ax.set_ylim(0, 10)
    ax.set_xlabel(r'$x(m)$')
    ax.set_ylabel(r'$y(m)$')    
    if name:
        plt.savefig('%s.pdf' %name,bbox_inches='tight')
    return figure