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

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

项目:pyfds    作者:emtpb    | 项目源码 | 文件源码
def plot_region(self, region):
        """Shows the given region in the field plot.

        Args:
            region: Region to be plotted.
        """

        if type(region) == reg.PointRegion:
            self.axes.scatter(region.point_coordinates[0] / self._x_axis_factor,
                              region.point_coordinates[1] / self._y_axis_factor, color='black')
        elif type(region) == reg.LineRegion:
            self.axes.plot([region.line_coordinates[0] / self._x_axis_factor,
                            region.line_coordinates[2] / self._x_axis_factor],
                           [region.line_coordinates[1] / self._y_axis_factor,
                            region.line_coordinates[3] / self._y_axis_factor],
                           color='black')
        elif type(region) == reg.RectRegion:
            self.axes.add_patch(pa.Rectangle((region.rect_coordinates[0] / self._x_axis_factor,
                                              region.rect_coordinates[1] / self._y_axis_factor),
                                             region.rect_coordinates[2] / self._x_axis_factor,
                                             region.rect_coordinates[3] / self._y_axis_factor,
                                             fill=False))
        else:
            raise TypeError('Unknown type in region list: {}'.format(type(region)))
项目:multimodal_varinf    作者:tmoer    | 项目源码 | 文件源码
def plot_predictions(self,world):
        for i in range(7):
            for j in range(7):
                for k in range(3):
                    if k==1:
                        col = "yellow"
                    elif k == 2:
                        col = "red"
                    elif k == 3:
                        col = 'blue'
                    if world[i,j,k]>0.0:
                        self.ax1.add_patch(patches.Rectangle(
                                (i,j),1,1,
                                #fill=False,
                                edgecolor='black',
                                linewidth = 2,
                                facecolor = col,
                                alpha=world[i,j,k]),
                            )
项目:structured-output-ae    作者:sbelharbi    | 项目源码 | 文件源码
def debug_plot_over_img(self, img, x, y, bb_d, bb_gt):
        """Plot the landmarks over the image with the bbox."""
        plt.close("all")
        fig = plt.figure()  # , figsize=(15, 10.8), dpi=200
        ax = plt.Axes(fig, [0., 0., 1., 1.])
        ax.set_axis_off()
        ax.imshow(img, aspect="auto", cmap='Greys_r')
        ax.scatter(x, y, s=10, color='r')
        rect1 = patches.Rectangle(
            (bb_d[0], bb_d[1]), bb_d[2]-bb_d[0], bb_d[3]-bb_d[1],
            linewidth=1, edgecolor='r', facecolor='none')
        ax.add_patch(rect1)
        rect2 = patches.Rectangle(
            (bb_gt[0], bb_gt[1]), bb_gt[2]-bb_gt[0], bb_gt[3]-bb_gt[1],
            linewidth=1, edgecolor='b', facecolor='none')
        ax.add_patch(rect2)
        fig.add_axes(ax)

        return fig
项目:structured-output-ae    作者:sbelharbi    | 项目源码 | 文件源码
def plot_over_img(self, img, x, y, x_pr, y_pr, bb_gt):
        """Plot the landmarks over the image with the bbox."""
        plt.close("all")
        fig = plt.figure(frameon=False)  # , figsize=(15, 10.8), dpi=200
        ax = plt.Axes(fig, [0., 0., 1., 1.])
        ax.set_axis_off()
        ax.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB), aspect="auto")
        ax.scatter(x, y, s=10, color='r')
        ax.scatter(x_pr, y_pr, s=10, color='g')
        rect = patches.Rectangle(
            (bb_gt[0], bb_gt[1]), bb_gt[2]-bb_gt[0], bb_gt[3]-bb_gt[1],
            linewidth=1, edgecolor='b', facecolor='none')
        ax.add_patch(rect)
        fig.add_axes(ax)

        return fig
项目:pauvre    作者:conchoecia    | 项目源码 | 文件源码
def generate_legend(panel, counts, color):

    # completely custom for more control
    panel.set_xlim([0, 1])
    panel.set_ylim([0, 1000])
    panel.set_yticks([int(x) for x in np.linspace(0, 1000, 6)])
    panel.set_yticklabels([int(x) for x in np.linspace(0, max(counts), 6)])
    for i in np.arange(0, 1001, 1):
        rgba = color(i / 1001)
        alpha = rgba[-1]
        facec = rgba[0:3]
        hist_rectangle = mplpatches.Rectangle((0, i), 1, 1,
                                              linewidth=0.0,
                                              facecolor=facec,
                                              edgecolor=(0, 0, 0),
                                              alpha=alpha)
        panel.add_patch(hist_rectangle)
    panel.spines['top'].set_visible(False)
    panel.spines['left'].set_visible(False)
    panel.spines['bottom'].set_visible(False)
    panel.yaxis.set_label_position("right")
    panel.set_ylabel('Number of Reads')
项目:plotnine    作者:has2k1    | 项目源码 | 文件源码
def draw_legend(data, da, lyr):
        """
        Draw letter 'a' in the box

        Parameters
        ----------
        data : dataframe
        da : DrawingArea
        lyr : layer

        Returns
        -------
        out : DrawingArea
        """
        if data['fill']:
            rect = Rectangle((0, 0),
                             width=da.width,
                             height=da.height,
                             linewidth=0,
                             alpha=data['alpha'],
                             facecolor=data['fill'],
                             capstyle='projecting')
            da.add_artist(rect)
        return geom_text.draw_legend(data, da, lyr)
项目:segyviewer    作者:Statoil    | 项目源码 | 文件源码
def __init__(self, axes, model, interpolation="nearest", aspect="auto"):
        super(SliceView, self).__init__()
        data = np.zeros((1, 1))
        self._image = axes.imshow(data, interpolation=interpolation, aspect=aspect, origin='upper')
        """ :type: AxesImage """
        self._model = model
        """ :type: SliceModel """

        style = {"fill": False,
                 "alpha": 1,
                 "color": 'black',
                 "linestyle": 'dotted',
                 "linewidth": 0.75
                 }

        self._vertical_indicator = patches.Rectangle((-0.5, -0.5), 1, model.height, **style)
        self._horizontal_indicator = patches.Rectangle((-0.5, -0.5), model.width, 1, **style)
        self._zoom_factor = 1.0

        self._view_limits = None

        self._min_xlim = 0
        self._max_xlim = model.width
        self._min_ylim = 0
        self._max_ylim = model.height
项目:BRITE-data-reduction-tool    作者:Ashoka42    | 项目源码 | 文件源码
def __init__(self, axis1):
        # Defines the axis used
        self.ax1 = axis1
        # Defines the default y-coordinate of the rectangle
        self.y0 = -50
        self.y1 = 50
        # Defines variables for drawing enabled/disabled and default output
        self.draw = 0
        self.output = "-50 50"
        # Defines a rectangle for the plot (mag/hjd)
        # Sets the rectangular width to 10000 - should be enough
        self.rect1 = Rectangle((0, 0), 10000, 0, alpha=0.3)
        # Adds the rectangle to the corresponding axis
        self.ax1.add_patch(self.rect1)

    # Defines what should happen on pressing the mousebutton
项目:BRITE-data-reduction-tool    作者:Ashoka42    | 项目源码 | 文件源码
def __init__(self, axis1, axis2, axis3, xmin, xmax, ymin, ymax):
        # Defines the axes used by the specific rectangular for each plot
        self.ax1 = axis1
        self.ax2 = axis2
        self.ax3 = axis3
        # Defines the default x- and y-coordinates of the rectangle
        self.x0 = xmin
        self.x1 = xmax
        self.y0 = ymin
        self.y1 = ymax
        # Defines variables for drawing enabled/disabled and default output
        self.draw = 0
        self.output = str(xmin) + " " + str(xmax) + " " + str(ymin) + " " + str(ymax)
        # Defines a rectangule for each plot (y/x, mag/x, mag/y)
        # Sets the rectangular y-position for the 2nd and 3rd plot to -50 and the
        # height to 100 to cover a default range from -50 to 50 (mag)
        self.rect1 = Rectangle((xmin, ymin), (xmax - xmin), (ymax - ymin), alpha=0.3)
        self.rect2 = Rectangle((xmin, -50), (xmax - xmin), 100, alpha=0.3)
        self.rect3 = Rectangle((ymin, -50), (ymax - ymin), 100, alpha=0.3)
        # Connects the rectangle to the corresponding axis
        self.ax1.add_patch(self.rect1)
        self.ax2.add_patch(self.rect2)
        self.ax3.add_patch(self.rect3)

    # Defines what should happen on pressing the mouse-button
项目:BRITE-data-reduction-tool    作者:Ashoka42    | 项目源码 | 文件源码
def __init__(self, axis1, axis2, axis3):
        # Defines the axes used by the specific rectangular for each plot
        self.ax1 = axis1
        self.ax2 = axis2
        self.ax3 = axis3
        # Defines the default x- and y-coordinates of the rectangle
        self.x0 = 0
        self.x1 = 100
        self.y0 = 0
        self.y1 = 100
        # Defines variables for drawing enabled/disabled and default output
        self.draw = 0
        self.output = "0 100 0 100"
        # Defines a rectangule for each plot (y/x, mag/x, mag/y)
        # Sets the rectangular y-position for the 2nd and 3rd plot to -50 and the
        # height to 100 to cover a default range from -50 to 50 (mag)
        self.rect1 = Rectangle((0, 0), 0, 0, alpha=0.3)
        self.rect2 = Rectangle((0, -50), 0, 100, alpha=0.3)
        self.rect3 = Rectangle((0, -50), 0, 100, alpha=0.3)
        # Connects the rectangle to the corresponding axis
        self.ax1.add_patch(self.rect1)
        self.ax2.add_patch(self.rect2)
        self.ax3.add_patch(self.rect3)

    # Defines what should happen on pressing the mousebutton
项目:tadtool    作者:vaquerizaslab    | 项目源码 | 文件源码
def _plot(self, region=None, cax=None):
        self.current_region = region
        try:
            sr, start_ix, end_ix = sub_regions(self.regions, region)
            trans = self.ax.get_xaxis_transform()
            for r in sr:
                region_patch = patches.Rectangle(
                    (r.start, .2),
                    width=abs(r.end - r.start), height=.6,
                    transform=trans,
                    facecolor=self.color,
                    edgecolor='white',
                    linewidth=2.
                )
                self.ax.add_patch(region_patch)
        except ValueError:
            pass
        self.ax.axis('off')
项目:PyFRAP    作者:alexblaessle    | 项目源码 | 文件源码
def genAsOpenscad(self):

        """Generates ROI as solid python object.

        Useful if ROI is used to be passed to openscad.

        Returns:
            solid.solidpython.cube: Solid python object. 

        """

        z=self.getOpenscadZExtend()
        zmin,zmax=min(z),max(z)
        openScadROI=solid.translate([self.offset[0],self.offset[1],zmin])(solid.cube([self.sidelength,self.sidelength,abs(zmax-zmin)]))
        return openScadROI

#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
#Rectangle ROI class
项目:PyFRAP    作者:alexblaessle    | 项目源码 | 文件源码
def genAsOpenscad(self):

        """Generates ROI as solid python object.

        Useful if ROI is used to be passed to openscad.

        .. note:: Will grab extent of geometry to find bounds in z-direction. 

        Returns:
            solid.solidpython.cube: Solid python object. 

        """

        try:
            ext=self.embryo.geometry.getZExtend()
        except AttributeError:
            printError("genAsOpenscad: Cannot greab extend from geometry of type " + self.embryo.geometry.typ)

        openScadROI=solid.translate([self.offset[0],self.offset[1],min(ext)])(solid.cube([self.sidelengthX,self.sidelengthY,abs(max(ext)-min(ext))]))
        return openScadROI


#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
#Rectangle and slice ROI class
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def on_button_press(self, event):
        if event.button == 1:  # left button
            if self.cursor_mode == 'Zoom':
                if event.dblclick:
                    self.center = wx.RealPoint(event.xdata, event.ydata)
                    self.ztv_frame.zoom_factor /= 2.
                    self.set_and_get_xy_limits()
                else:
                    self.zoom_start_timestamp = time.time()
                    self.zoom_rect = Rectangle((event.xdata, event.ydata), 0, 0,
                                               color='orange', fill=False, zorder=100)
                    self.axes.add_patch(self.zoom_rect)
                    self.figure.canvas.draw()
            elif self.cursor_mode == 'Pan':
                self.center = wx.RealPoint(event.xdata, event.ydata)
                self.set_and_get_xy_limits()
            else:
                if (self.available_cursor_modes.has_key(self.cursor_mode) and
                    self.available_cursor_modes[self.cursor_mode].has_key('on_button_press')):
                    self.available_cursor_modes[self.cursor_mode]['on_button_press'](event)
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def __init__(self, parent, size=wx.Size(128,128), dpi=None, **kwargs):
        self.size = size
        self.dragging_curview_is_active = False
        wx.Panel.__init__(self, parent, wx.ID_ANY, wx.DefaultPosition, size, 0, **kwargs)
        self.ztv_frame = self.GetTopLevelParent()
        self.figure = Figure(None, dpi)
        self.axes = self.figure.add_axes([0., 0., 1., 1.])
        self.curview_rectangle = Rectangle((0, 0), 1, 1, color='orange', fill=False, zorder=100)
        self.axes.add_patch(self.curview_rectangle)
        self.canvas = FigureCanvasWxAgg(self, -1, self.figure)
        self.overview_zoom_factor = 1.
        self._SetSize()
        self.set_xy_limits()
        self.axes_widget = AxesWidget(self.figure.gca())
        self.axes_widget.connect_event('button_press_event', self.on_button_press)
        self.axes_widget.connect_event('button_release_event', self.on_button_release)
        self.axes_widget.connect_event('motion_notify_event', self.on_motion)
        pub.subscribe(self.redraw_overview_image, 'redraw-image')   
        pub.subscribe(self.redraw_box, 'primary-xy-limits-changed')
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def on_button_press(self, event):
        if event.button == 1:  # left button
            if self.cursor_mode == 'Zoom':
                if event.dblclick:
                    self.center = wx.RealPoint(event.xdata, event.ydata)
                    self.ztv_frame.zoom_factor /= 2.
                    self.set_and_get_xy_limits()
                else:
                    self.zoom_start_timestamp = time.time()
                    self.zoom_rect = Rectangle((event.xdata, event.ydata), 0, 0,
                                               color='orange', fill=False, zorder=100)
                    self.axes.add_patch(self.zoom_rect)
                    self.figure.canvas.draw()
            elif self.cursor_mode == 'Pan':
                self.center = wx.RealPoint(event.xdata, event.ydata)
                self.set_and_get_xy_limits()
            else:
                if (self.available_cursor_modes.has_key(self.cursor_mode) and
                    self.available_cursor_modes[self.cursor_mode].has_key('on_button_press')):
                    self.available_cursor_modes[self.cursor_mode]['on_button_press'](event)
项目:learning-tensorflow    作者:Salon-sai    | 项目源码 | 文件源码
def plot(error_index, dataset_path):
    img = mpimg.imread(dataset_path)
    plt.imshow(img)
    currentAxis = plt.gca()
    for index in error_index:
        row = index // 2
        column = index % 2
        currentAxis.add_patch(
            patches.Rectangle(
                xy=(
                     47 * 9 if column == 0 else 47 * 19,
                     row * 57
                    ),
                width=47,
                height=57,
                linewidth=1,
                edgecolor='r',
                facecolor='none'
            )
    )
    fig = plt.gcf()
    fig.set_size_inches(11.40, 9.42)
    plt.savefig("fig_result.png", bbox_inches="tight", dpi=100)
    plt.show()
项目:yolo-tf    作者:ruiminshen    | 项目源码 | 文件源码
def onclick(self, event):
        for p in self.plots:
            p.remove()
        self.plots = []
        height, width, _ = self.image.shape
        ix = int(event.xdata * self.cell_width / width)
        iy = int(event.ydata * self.cell_height / height)
        self.plots.append(self.ax.add_patch(patches.Rectangle((ix * width / self.cell_width, iy * height / self.cell_height), width / self.cell_width, height / self.cell_height, linewidth=0, facecolor='black', alpha=.2)))
        index = iy * self.cell_width + ix
        prob, iou, xy_min, wh = self.sess.run([self.model.prob[0][index], self.model.iou[0][index], self.model.xy_min[0][index], self.model.wh[0][index]], feed_dict=self.feed_dict)
        xy_min = xy_min * self.scale
        wh = wh * self.scale
        for _prob, _iou, (x, y), (w, h), color in zip(prob, iou, xy_min, wh, self.colors):
            index = np.argmax(_prob)
            name = self.names[index]
            _prob = _prob[index]
            _conf = _prob * _iou
            linewidth = min(_conf * 10, 3)
            self.plots.append(self.ax.add_patch(patches.Rectangle((x, y), w, h, linewidth=linewidth, edgecolor=color, facecolor='none')))
            self.plots.append(self.ax.annotate(name + ' (%.1f%%, %.1f%%)' % (_iou * 100, _prob * 100), (x, y), color=color))
        self.fig.canvas.draw()
项目:cellcomplex    作者:VirtualPlants    | 项目源码 | 文件源码
def bar_plot(figure,X,Y,color1,color2,xlabel="",ylabel="",label=""):
    font = fm.FontProperties(family = 'Trebuchet', weight ='light')
    #font = fm.FontProperties(family = 'CenturyGothic',fname = '/Library/Fonts/Microsoft/Century Gothic', weight ='light')
    figure.patch.set_facecolor('white')
    axes = figure.add_subplot(111)
    width = X[1]-X[0]
    axes.plot(X,Y,linewidth=1,color=tuple(color2),alpha=0.0,label=label)
    for x in xrange(X.size):
        i = (Y[x]-Y.min())/(Y.max()-Y.min())
        color = tuple(color1*(1.0-i) + color2*(i))
        axes.add_patch(Rectangle((X[x] - width/2, 0), width, Y[x], facecolor=color, edgecolor=(0.8,0.8,0.8), alpha = 0.5))
    axes.set_xlim(X.min(),X.max())
    axes.set_xlabel(xlabel,fontproperties=font, size=10, style='italic')
    axes.set_xticklabels(axes.get_xticks(),fontproperties=font, size=12)
    if '%' in ylabel:
        axes.set_ylim(0,np.minimum(2*Y.max(),100))
    axes.set_ylabel(ylabel, fontproperties=font, size=10, style='italic')
    axes.set_yticklabels(axes.get_yticks(),fontproperties=font, size=12)
项目:Py2DSpectroscopy    作者:SvenBo90    | 项目源码 | 文件源码
def create_area_map(self, x1, x2, y1, y2):

        # check boundaries for consistency
        if x2 < x1:
            tmp = x2
            x2 = x1
            x1 = tmp
        if y2 < y1:
            tmp = y2
            y2 = y1
            y1 = tmp

        # create rectangle patch
        self._area_rectangle = patches.Rectangle((x1-0.5, y1-0.5), x2-x1+1, y2-y1+1, linewidth=1.5,
                                                 facecolor=(1, 1, 1, 0.5), edgecolor=(0, 0, 0, 1))
        self._axes.add_patch(self._area_rectangle)

        # redraw
        self._fig.canvas.draw()
项目:CatchGame-QLearningExample-TensorFlow    作者:solaris33    | 项目源码 | 文件源码
def drawState(fruitRow, fruitColumn, basket):
  global gridSize
  # column is the x axis
  fruitX = fruitColumn 
  # Invert matrix style points to coordinates
  fruitY = (gridSize - fruitRow + 1)
  statusTitle = "Wins: " + str(winCount) + "  Losses: " + str(loseCount) + "  TotalGame: " + str(numberOfGames)
  axis.set_title(statusTitle, fontsize=30)
  for p in [
    patches.Rectangle(
        ((ground - 1), (ground)), 11, 10,
        facecolor="#000000"      # Black
    ),
    patches.Rectangle(
        (basket - 1, ground), 2, 0.5,
        facecolor="#FF0000"     # No background
    ),
    patches.Rectangle(
        (fruitX - 0.5, fruitY - 0.5), 1, 1,
        facecolor="#FF0000"       # red 
    ),   
    ]:
      axis.add_patch(p)
  display.clear_output(wait=True)
  display.display(pl.gcf())
项目:adversarial-autoencoder    作者:musyoku    | 项目源码 | 文件源码
def scatter_labeled_z(z_batch, label_batch, filename="labeled_z"):
    fig = pylab.gcf()
    fig.set_size_inches(20.0, 16.0)
    pylab.clf()
    colors = ["#2103c8", "#0e960e", "#e40402","#05aaa8","#ac02ab","#aba808","#151515","#94a169", "#bec9cd", "#6a6551"]
    for n in range(z_batch.shape[0]):
        result = pylab.scatter(z_batch[n, 0], z_batch[n, 1], c=colors[label_batch[n]], s=40, marker="o", edgecolors='none')

    classes = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
    recs = []
    for i in range(0, len(colors)):
        recs.append(mpatches.Rectangle((0, 0), 1, 1, fc=colors[i]))

    ax = pylab.subplot(111)
    box = ax.get_position()
    ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
    ax.legend(recs, classes, loc="center left", bbox_to_anchor=(1.1, 0.5))
    pylab.xticks(pylab.arange(-4, 5))
    pylab.yticks(pylab.arange(-4, 5))
    pylab.xlabel("z1")
    pylab.ylabel("z2")
    pylab.savefig(filename)
项目:ATLeS    作者:liffiton    | 项目源码 | 文件源码
def draw_legend(self, legend_ax):
        # Make a legend with proxy artists
        xpos_artist = lines.Line2D([],[], color='orange')
        ypos_artist = lines.Line2D([],[], color='limegreen')
        numpts_artist = lines.Line2D([],[], color='purple', linewidth=1)
        frozen_artist = patches.Rectangle((0,0), 1, 1, fc='lightblue', ec='None')
        missing_artist = patches.Rectangle((0,0), 1, 1, fc='yellow', ec='None')
        lost_artist = patches.Rectangle((0,0), 1, 1, fc='red', ec='None')
        # Place it in center of top "subplot" area
        legend_ax.legend(
            [xpos_artist, ypos_artist, numpts_artist,
                frozen_artist, missing_artist, lost_artist],
            ['x-pos', 'y-pos', '# Detection pts',
                'Frozen', 'Missing', 'Lost'],
            loc='center',
            fontsize=12,
            ncol=4,
        )
        legend_ax.axis('off')
        format_axis(legend_ax)
项目:TensorFlow_Examples    作者:solaris33    | 项目源码 | 文件源码
def drawState(fruitRow, fruitColumn, basket):
  global gridSize
  # column is the x axis
  fruitX = fruitColumn 
  # Invert matrix style points to coordinates
  fruitY = (gridSize - fruitRow + 1)
  statusTitle = "Wins: " + str(winCount) + "  Losses: " + str(loseCount) + "  TotalGame: " + str(numberOfGames)
  axis.set_title(statusTitle, fontsize=30)
  for p in [
    patches.Rectangle(
        ((ground - 1), (ground)), 11, 10,
        facecolor="#000000"      # Black
    ),
    patches.Rectangle(
        (basket - 1, ground), 2, 0.5,
        facecolor="#FF0000"     # No background
    ),
    patches.Rectangle(
        (fruitX - 0.5, fruitY - 0.5), 1, 1,
        facecolor="#FF0000"       # red 
    ),   
    ]:
      axis.add_patch(p)
  display.clear_output(wait=True)
  display.display(pl.gcf())
项目:Learn-to-identify-similar-images    作者:MashiMaroLjc    | 项目源码 | 文件源码
def picture(image,exampless,colors):
    """

    :param img:
    :param example:
    :return:
    """
    plt.imshow(image)
    ax = plt.gca()
    i = 0
    for examples in exampless:
        for exa in examples:
            rect = Rectangle((exa.left_top.x,exa.left_top.y), exa.right_bottom.x-exa.left_top.x,
                             exa.right_bottom.y - exa.left_top.y, fill=None, color=colors[i],linewidth=3)
            ax.add_patch(rect)
        i += 1
    plt.show()
    #plt.clf()


#example1
项目:faampy    作者:ncasuk    | 项目源码 | 文件源码
def plot_heater(ax, data):
    """
    plots deiced heater status i.e. ON/OFF

    """
    if not 'PRTAFT_deiced_temp_flag' in data:
        return
    ax.text(0.05, 0.98,'Heater', axes_title_style, transform=ax.transAxes)
    ax.grid(False)
    ax.set_ylim(0,1)
    ax.yaxis.set_major_locator(plt.NullLocator())
    plt.setp(ax.get_xticklabels(), visible=False)
    heater_status=np.array(data['PRTAFT_deiced_temp_flag'], dtype=np.int8)
    toggle=np.diff(heater_status.ravel())
    time_periods=zip(list(np.where(toggle == 1)[0]),
                     list(np.where(toggle == -1)[0]))
    for t in time_periods:
        #plt.barh(0, data['mpl_timestamp'][0,1], left=data['mpl_timestamp'][0,0])
        width=data['mpl_timestamp'][t[1],0]-data['mpl_timestamp'][t[0],0]
        ax.add_patch(patches.Rectangle((data['mpl_timestamp'][t[0],0], 0), width, 1, alpha=0.8, color='#ffaf4d'))
    return ax
项目:GRIPy    作者:giruenf    | 项目源码 | 文件源码
def __init__(self, canvas, ax, onselect, rectprops):
        self.canvas = canvas
        self.ax = ax

        self.rect = None
        self.background = None
        self.pressv = None

        self.onselect = onselect

        self.buttonDown = False
        self.prev = 0

        self.canvas.mpl_connect('motion_notify_event', self.onmove)
        self.canvas.mpl_connect('button_press_event', self.press)
        self.canvas.mpl_connect('button_release_event', self.release)
        self.canvas.mpl_connect('draw_event', self.update_background)

        trans = blended_transform_factory(self.ax.transAxes,
                                          self.ax.transData)
        self.rect = Rectangle((0, 0), 1, 0, transform=trans, visible=False,
                              **rectprops)
项目:variational-autoencoder    作者:musyoku    | 项目源码 | 文件源码
def visualize_labeled_z(z_batch, label_batch, dir=None):
    fig = pylab.gcf()
    fig.set_size_inches(20.0, 16.0)
    pylab.clf()
    colors = ["#2103c8", "#0e960e", "#e40402","#05aaa8","#ac02ab","#aba808","#151515","#94a169", "#bec9cd", "#6a6551"]
    for n in xrange(z_batch.shape[0]):
        result = pylab.scatter(z_batch[n, 0], z_batch[n, 1], c=colors[label_batch[n]], s=40, marker="o", edgecolors='none')

    classes = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
    recs = []
    for i in range(0, len(colors)):
        recs.append(mpatches.Rectangle((0, 0), 1, 1, fc=colors[i]))

    ax = pylab.subplot(111)
    box = ax.get_position()
    ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
    ax.legend(recs, classes, loc="center left", bbox_to_anchor=(1.1, 0.5))
    pylab.xticks(pylab.arange(-4, 5))
    pylab.yticks(pylab.arange(-4, 5))
    pylab.xlabel("z1")
    pylab.ylabel("z2")
    pylab.savefig("%s/labeled_z.png" % dir)
项目:attend_infer_repeat    作者:akosiorek    | 项目源码 | 文件源码
def rect(bbox, c=None, facecolor='none', label=None, ax=None, line_width=1):
    r = Rectangle((bbox[1], bbox[0]), bbox[3], bbox[2], linewidth=line_width,
                  edgecolor=c, facecolor=facecolor, label=label)

    if ax is not None:
        ax.add_patch(r)
    return r
项目:Feon    作者:YaoyaoBae    | 项目源码 | 文件源码
def draw_fixed_sup(ax,node,factor = (1,1),**kwargs):
    width = 0.1*factor[0]
    height = 0.1*factor[1]
    patch = mpatches.Rectangle((node.x - width * 0.5, node.y - height * 0.5),
                                           width, height,**kwargs)
    ax.add_patch(patch)
项目:openanalysis    作者:OpenWeavers    | 项目源码 | 文件源码
def __init_animation(self):
        masked_array = np.ma.array(self.frames[0], mask=np.isinf(self.frames[0]))
        vmin = 0
        vmax = np.max(np.ma.array(self.frames[-1], mask=np.isinf(self.frames[-1])))
        from mpl_toolkits.axes_grid1 import make_axes_locatable
        div = make_axes_locatable(self.ax2)
        cax = div.append_axes('right', '5%', '5%')
        cax.axis('off')
        div = make_axes_locatable(self.ax3)
        cax = div.append_axes('right', '5%', '5%')
        self.img = self.ax3.imshow(masked_array, interpolation='nearest', vmin=vmin, vmax=vmax, alpha=0.7)
        if self.matrix_labels:
            self.lables = self.__plot_matrix_labels(self.frames[0], self.ax3)
        else:
            self.lables = []
        self.fig.colorbar(self.img, cax=cax)
        self.active_cells.append(self.ax3.add_patch(
            patches.Rectangle((0, 0), 1, 1, fill=False, linestyle='--', color='k', linewidth=3)
        ))
        self.active_cells.append(self.ax3.add_patch(
            patches.Rectangle((0, 0), 1, 1, fill=False, linestyle='--', color='k', linewidth=3)
        ))
        self.active_cells.append(self.ax3.add_patch(
            patches.Rectangle((0, 0), 1, 1, fill=False, linestyle='-', color='k', linewidth=3)
        ))
        return self.lables + [self.img]
项目:pauvre    作者:conchoecia    | 项目源码 | 文件源码
def _generate_histogram_bin_patches(panel, bins, bin_values, horizontal=True):
    """This helper method generates the histogram that is added to the panel.

    In this case, horizontal = True applies to the mean quality histogram.
    So, horizontal = False only applies to the length histogram.
    """
    l_width = 0.0
    f_color = (0.5, 0.5, 0.5)
    e_color = (0, 0, 0)
    if horizontal:
        for step in np.arange(0, len(bin_values), 1):
            left = bins[step]
            bottom = 0
            width = bins[step + 1] - bins[step]
            height = bin_values[step]
            hist_rectangle = mplpatches.Rectangle((left, bottom), width, height,
                                                  linewidth=l_width,
                                                  facecolor=f_color,
                                                  edgecolor=e_color)
            panel.add_patch(hist_rectangle)
    else:
        for step in np.arange(0, len(bin_values), 1):
            left = 0
            bottom = bins[step]
            width = bin_values[step]
            height = bins[step + 1] - bins[step]

            hist_rectangle = mplpatches.Rectangle((left, bottom), width, height,
                                                  linewidth=l_width,
                                                  facecolor=f_color,
                                                  edgecolor=e_color)
            panel.add_patch(hist_rectangle)
项目:PyMDNet    作者:HungWei-Andy    | 项目源码 | 文件源码
def draw(path, bb):
  im = np.array(Image.open(path), dtype=np.uint8)
  fig,ax = plt.subplots(1)
  ax.imshow(im)
  rect = patches.Rectangle(bb, im.size[0], im.size[1],linewidth=1,edgecolor='r',facecolor='none'))
  ax.add_patch(rect)
  plt.show()
项目:plotnine    作者:has2k1    | 项目源码 | 文件源码
def draw_legend(data, da, lyr):
        """
        Draw a rectangle with a horizontal strike in the box

        Parameters
        ----------
        data : dataframe
        da : DrawingArea
        lyr : layer

        Returns
        -------
        out : DrawingArea
        """
        data['size'] *= SIZE_FACTOR

        # background
        facecolor = to_rgba(data['fill'], data['alpha'])
        if facecolor is None:
            facecolor = 'none'

        bg = Rectangle((da.width*.125, da.height*.25),
                       width=da.width*.75,
                       height=da.height*.5,
                       linewidth=data['size'],
                       facecolor=facecolor,
                       edgecolor=data['color'],
                       linestyle=data['linetype'],
                       capstyle='projecting',
                       antialiased=False)
        da.add_artist(bg)

        strike = mlines.Line2D([da.width*.125, da.width*.875],
                               [da.height*.5, da.height*.5],
                               linestyle=data['linetype'],
                               linewidth=data['size'],
                               color=data['color'])
        da.add_artist(strike)
        return da
项目:plotnine    作者:has2k1    | 项目源码 | 文件源码
def draw_legend(data, da, lyr):
        """
        Draw letter 'a' in the box

        Parameters
        ----------
        data : dataframe
        params : dict
        lyr : layer

        Returns
        -------
        out : DrawingArea
        """
        if lyr.stat.params['se']:
            r = lyr.geom.params['legend_fill_ratio']
            bg = Rectangle((0, (1-r)*da.height/2),
                           width=da.width,
                           height=r*da.height,
                           alpha=data['alpha'],
                           facecolor=data['fill'],
                           linewidth=0)
            da.add_artist(bg)

        data['alpha'] = 1
        return geom_path.draw_legend(data, da, lyr)
项目:plotnine    作者:has2k1    | 项目源码 | 文件源码
def draw_legend(data, da, lyr):
        """
        Draw a rectangle in the box

        Parameters
        ----------
        data : dataframe
        da : DrawingArea
        lyr : layer

        Returns
        -------
        out : DrawingArea
        """
        data['size'] *= SIZE_FACTOR
        # We take into account that the linewidth
        # bestrides the boundary of the rectangle
        linewidth = np.min([data['size'],
                            da.width/4, da.height/4])
        if data['color'] is None:
            linewidth = 0

        facecolor = to_rgba(data['fill'], data['alpha'])
        if facecolor is None:
            facecolor = 'none'

        rect = Rectangle((0+linewidth/2, 0+linewidth/2),
                         width=da.width-linewidth,
                         height=da.height-linewidth,
                         linewidth=linewidth,
                         linestyle=data['linetype'],
                         facecolor=facecolor,
                         edgecolor=data['color'],
                         capstyle='projecting')
        da.add_artist(rect)
        return da
项目:Bitcoin-Crypto-python-charts    作者:Whalepool    | 项目源码 | 文件源码
def fooCandlestick(ax, quotes, width=0.5, colorup='#FFA500', colordown='#222', alpha=1.0):
    OFFSET = width/2.0
    lines = []
    boxes = []

    for q in quotes:

        timestamp, op, hi, lo, close = q[:5]
        box_h = max(op, close)
        box_l = min(op, close)
        height = box_h - box_l

        if close>=op:
            color = '#3fd624'
        else:
            color = '#e83e2c'

        vline_lo = Line2D( xdata=(timestamp, timestamp), ydata=(lo, box_l), color = 'k', linewidth=0.5, antialiased=True, zorder=10 )
        vline_hi = Line2D( xdata=(timestamp, timestamp), ydata=(box_h, hi), color = 'k', linewidth=0.5, antialiased=True, zorder=10 )
        rect = Rectangle( xy = (timestamp-OFFSET, box_l), width = width, height = height, facecolor = color, edgecolor = color, zorder=10)
        rect.set_alpha(alpha)
        lines.append(vline_lo)
        lines.append(vline_hi)
        boxes.append(rect)
        ax.add_line(vline_lo)
        ax.add_line(vline_hi)
        ax.add_patch(rect)

    ax.autoscale_view()

    return lines, boxes


# Enable a Grid
项目:PedWorks    作者:BrnCPrz    | 项目源码 | 文件源码
def draw_adjacency_matrix(G, node_order=None, partitions=[], colors=[]):
    """
    - G is a networkx graph
    - node_order (optional) is a list of nodes, where each node in G
          appears exactly once
    - partitions is a list of node lists, where each node in G appears
          in exactly one node list
    - colors is a list of strings indicating what color each
          partition should be
    If partitions is specified, the same number of colors needs to be
    specified.
    """
    adjacency_matrix = nx.to_numpy_matrix(G, dtype=np.bool, nodelist=node_order)

    # Plot adjacency matrix in toned-down black and white
    fig = plt.figure(figsize=(8, 8))  # in inches
    plt.imshow(adjacency_matrix,
               cmap="Paired",
               interpolation="none")

    # The rest is just if you have sorted nodes by a partition and want to
    # highlight the module boundaries
    assert len(partitions) == len(colors)
    ax = plt.gca()
    for partition, color in zip(partitions, colors):
        current_idx = 0
        for module in partition:
            ax.add_patch(patches.Rectangle((current_idx, current_idx),
                                           len(module),  # Width
                                           len(module),  # Height
                                           facecolor="none",
                                           edgecolor=color,
                                           linewidth="1"))
            current_idx += len(module)
    plt.show()
项目:johnson-county-ddj-public    作者:dssg    | 项目源码 | 文件源码
def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans):
        ''' Return square patch legend list which is going to used in legend handles

        :params : all the arguments to make a square legend
        :return: A list of mpatches object
        :rtype: list
        '''
        center = xdescent + 0.5 * (width - height), ydescent
        p = mpatches.Rectangle(xy=center, width=height,height=height, angle=0.0)
        self.update_prop(p, orig_handle, legend)
        p.set_transform(trans)
        return [p]
项目:coquery    作者:gkunter    | 项目源码 | 文件源码
def paint_rectangle(self, p, q, name, weight=None):
        rect = Rectangle((p[0], p[1]), q[0] - p[0], q[1] - p[1], 
                         facecolor=self.colors[name], label=name)
        self.subplot.add_patch(rect)
项目:coquery    作者:gkunter    | 项目源码 | 文件源码
def plotTextgrid(self):
        tier_labels = []
        n_tiers = len(self._textgrid.tiers)
        for i, tier in enumerate(self._textgrid.tiers):
            tier_labels.append(tier.name)
            y_start = 1 - i / n_tiers
            y_end = 1 - (i+1) / n_tiers
            for interval in tier.intervals:
                patch = Rectangle(
                    (interval.start_time, y_start),
                    interval.duration(),
                    y_end - y_start,
                    fill=False)
                self.ax_textgrid.add_patch(patch)
                x_pos = interval.start_time + 0.5 * (interval.duration())
                self.ax_textgrid.text(
                    x_pos,
                    y_start + 0.5 * (y_end - y_start),
                    interval.text,
                    verticalalignment="center",
                    horizontalalignment="center")
                self.ax_spectrogram.vlines((interval.start_time,
                                            interval.end_time), 5000, 0)
                self.ax_waveform.vlines((interval.start_time,
                                         interval.end_time), -1, 1)

        self.ax_textgrid.yaxis.set_ticks(
            [(i + 0.5) / n_tiers for i in range(n_tiers)])
        self.ax_textgrid.yaxis.set_ticklabels(reversed(tier_labels))
项目:odnl    作者:lilhope    | 项目源码 | 文件源码
def vis_all_detection(all_boxes,roidb):
    """
    visualize all detections in one image
    :param im_array: [b=1 c h w] in rgb
    :param detections: [ numpy.ndarray([[x1 y1 x2 y2 score]]) for j in classes ]
    :param class_names: list of names in imdb
    :param scale: visualize the scaled image
    :return:
    """

    for i in range(len(roidb)):
        # show image
        ax = plt.gca()
        plt.figure()
        file_name = roidb[i]['image']
        I = io.imread(file_name)
        ax.imshow(I)
        # show refer expression
        print("raw:{}".format(roidb[i]['sent']))
        gt_box = roidb[i]['bbox'][0]
        gt_box_plot = Rectangle((gt_box[0], gt_box[1]), gt_box[2]-gt_box[0]+1, gt_box[3]-gt_box[1]+1, fill=False, edgecolor='green', linewidth=3)
        ax.add_patch(gt_box_plot)
        pred_boxes = all_boxes[i]
        if pred_boxes.shape[0] == 0:
            continue
        pred_box_ind = np.argmax(pred_boxes[:,4])
        pred_box = pred_boxes[pred_box_ind,:]
        pred_box_plot = Rectangle((pred_box[0], pred_box[1]), pred_box[2]-gt_box[0]+1, gt_box[3]-gt_box[1]+1, fill=False, edgecolor='red', linewidth=3)
        ax.add_patch(pred_box_plot)
        plt.show()
    plt.show()
项目:PyFRAP    作者:alexblaessle    | 项目源码 | 文件源码
def showBoundary(self,color=None,linewidth=3,ax=None):

        """Shows ROI in a 2D plot.

        If no color is specified, will use color specified in ``ROI.color``.

        Keyword Args:
            ax (matplotlib.axes): Matplotlib axes used for plotting. If not specified, will generate new one.
            color (str): Color of plot.
            linewidth (float): Linewidth of plot.

        Returns:
            matplotlib.axes: Axes used for plotting.    

        """

        if color==None:
            color=self.color

        if ax==None:
            fig,axes = pyfrp_plot_module.makeSubplot([1,1],titles=["boundary"],sup=self.name+" boundary")
            ax = axes[0]

            img=np.nan*np.ones((self.embryo.dataResPx,self.embryo.dataResPx))
            ax.imshow(img)

        patch = ptc.Rectangle(self.offset,self.sidelength,self.sidelength,fill=False,linewidth=linewidth,color=color)
        ax.add_patch(patch)
        return ax
项目:PyFRAP    作者:alexblaessle    | 项目源码 | 文件源码
def showBoundary(self,color=None,linewidth=3,ax=None):

        """Shows ROI in a 2D plot.

        If no color is specified, will use color specified in ``ROI.color``.

        Keyword Args:
            ax (matplotlib.axes): Matplotlib axes used for plotting. If not specified, will generate new one.
            color (str): Color of plot.
            linewidth (float): Linewidth of plot.

        Returns:
            matplotlib.axes: Axes used for plotting.    

        """

        if color==None:
            color=self.color

        if ax==None:
            fig,axes = pyfrp_plot_module.makeSubplot([1,1],titles=["boundary"],sup=self.name+" boundary")
            ax = axes[0]

            img=np.nan*np.ones((self.embryo.dataResPx,self.embryo.dataResPx))
            ax.imshow(img)

        patch = ptc.Rectangle(self.offset,self.sidelengthX,self.sidelengthY,fill=False,linewidth=linewidth,color=color)
        ax.add_patch(patch)
        return ax
项目:PyFRAP    作者:alexblaessle    | 项目源码 | 文件源码
def showBoundary(self,color=None,linewidth=3,ax=None):

        """Shows ROI in a 2D plot.

        If no color is specified, will use color specified in ``ROI.color``.

        Keyword Args:
            ax (matplotlib.axes): Matplotlib axes used for plotting. If not specified, will generate new one.
            color (str): Color of plot.
            linewidth (float): Linewidth of plot.

        Returns:
            matplotlib.axes: Axes used for plotting.    

        """

        if color==None:
            color=self.color

        if ax==None:
            fig,axes = pyfrp_plot_module.makeSubplot([1,1],titles=["boundary"],sup=self.name+" boundary")
            ax = axes[0]

            img=np.nan*np.ones((self.embryo.dataResPx,self.embryo.dataResPx))
            ax.imshow(img)
        patch = ptc.Rectangle(self.corners,closed=True,fill=False,linewidth=linewidth,color=color)

        ax.add_patch(patch)
        return ax
项目:tefla    作者:litan    | 项目源码 | 文件源码
def draw_top_regions(properties, n0):
    n = min(n0, len(properties))
    print('Drawing %d regions' % n)
    colors = ['red', 'blue', 'green']
    for i in range(n):
        region = properties[i]
        minr, minc, maxr, maxc = region.bbox
        print('Region bbox: %s' % str(region.bbox))
        rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr,
                                  fill=False, edgecolor=colors[i % len(colors)], linewidth=1)
        plt.gca().add_patch(rect)
        return minr, minc, maxr, maxc
项目:georges    作者:chernals    | 项目源码 | 文件源码
def draw_bpm_size(ax, s, x):
    ax.add_patch(
        patches.Rectangle(
            (s - 0.05, -x),
            0.1,
            2 * x,
        )
    )
项目:DGP    作者:DynamicGravitySystems    | 项目源码 | 文件源码
def onmotion(self, event: MouseEvent):
        if event.inaxes not in self._axes:
            return
        if self.clicked is not None:
            partners, x0, xclick, yclick = self.clicked
            dx = event.xdata - xclick
            new_x = x0 + dx
            for attrs in partners:
                rect = attrs['rect']  # type: Rectangle
                rect.set_x(new_x)
                canvas = rect.figure.canvas
                axes = rect.axes  # type: Axes
                canvas.restore_region(attrs['bg'])
                axes.draw_artist(rect)
                canvas.blit(axes.bbox)
项目:nuts-ml    作者:maet3608    | 项目源码 | 文件源码
def test_annotation2pltpatch():
    assert list(ni.annotation2pltpatch(np.NaN)) == []
    assert list(ni.annotation2pltpatch(())) == []

    anno = ('point', ((1, 1), (1, 2)))
    pltpatches = list(ni.annotation2pltpatch(anno))
    assert len(pltpatches) == 2
    assert isinstance(pltpatches[0], plp.CirclePolygon)
    assert isinstance(pltpatches[1], plp.CirclePolygon)

    anno = ('circle', ((2, 2, 2),))
    pltpatches = list(ni.annotation2pltpatch(anno))
    assert isinstance(pltpatches[0], plp.Circle)

    anno = ('rect', ((1, 2, 2, 3),))
    pltpatches = list(ni.annotation2pltpatch(anno))
    assert isinstance(pltpatches[0], plp.Rectangle)

    anno = ('polyline', (((1, 2), (3, 2), (3, 4), (1, 4), (1, 2)),))
    pltpatches = list(ni.annotation2pltpatch(anno))
    assert isinstance(pltpatches[0], plp.Polygon)

    anno = ('polyline', (((0, 0), (2, 2), (2, 4)),))
    pltpatches = list(ni.annotation2pltpatch(anno))
    assert isinstance(pltpatches[0], plp.Polygon)

    with pytest.raises(ValueError) as ex:
        anno = ('invalid', ((1,),))
        list(ni.annotation2pltpatch(anno))
    assert str(ex.value).startswith('Invalid kind of annotation')
项目:nuts-ml    作者:maet3608    | 项目源码 | 文件源码
def annotation2pltpatch(annotation, **kwargs):
    """
    Convert geometric annotation to matplotlib geometric objects (=patches)

    For details regarding matplotlib patches see:
    http://matplotlib.org/api/patches_api.html
    For annotation formats see:
    imageutil.annotation2coords

    :param annotation annotation: Annotation of an image region such as
      point, circle, rect or polyline
    :return: matplotlib.patches
    :rtype: generator over matplotlib patches
    """
    if not annotation or isnan(annotation):
        return
    kind, geometries = annotation
    for geo in geometries:
        if kind == 'point':
            pltpatch = plp.CirclePolygon((geo[0], geo[1]), 1, **kwargs)
        elif kind == 'circle':
            pltpatch = plp.Circle((geo[0], geo[1]), geo[2], **kwargs)
        elif kind == 'rect':
            x, y, w, h = geo
            pltpatch = plp.Rectangle((x, y), w, h, **kwargs)
        elif kind == 'polyline':
            pltpatch = plp.Polygon(geo, closed=False, **kwargs)
        else:
            raise ValueError('Invalid kind of annotation: ' + kind)
        yield pltpatch