当前位置: 首页>>代码示例>>Python>>正文


Python Rectangle.set_x方法代码示例

本文整理汇总了Python中matplotlib.patches.Rectangle.set_x方法的典型用法代码示例。如果您正苦于以下问题:Python Rectangle.set_x方法的具体用法?Python Rectangle.set_x怎么用?Python Rectangle.set_x使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在matplotlib.patches.Rectangle的用法示例。


在下文中一共展示了Rectangle.set_x方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: Canvas

# 需要导入模块: from matplotlib.patches import Rectangle [as 别名]
# 或者: from matplotlib.patches.Rectangle import set_x [as 别名]
class Canvas(object):
    def __init__(self, img, name='misc', patch_size=(100, 100),
                 axes=None):
        """

        Parameters
        ----------
        img : 2-D ndarray
            Image to crop from.
        name : str
            Basename of output files for images cropped from this canvas.
        patch_size : tuple of ints
            Size of the patch to crop (rows, cols).
        axes : matplotlib axes object
            Axes on which to draw the patch.

        """
        self.name = name
        self.img = img
        self.x = 0
        self.y = 0
        self.patch_size = patch_size
        h, w = self.patch_size
        self.patch = Rectangle((self.x, self.y), h, w, alpha=0.3)
        self.axes = axes
        axes.add_patch(self.patch)

    def paint(self):
        self.patch.set_x(self.x)
        self.patch.set_y(self.y)

        # This is probably not the right call.  Should call redraw on canvas?
        plt.draw()

        print self.name
开发者ID:Wichard-S,项目名称:supreme,代码行数:37,代码来源:mpl_cut.py

示例2: resizeGraphics

# 需要导入模块: from matplotlib.patches import Rectangle [as 别名]
# 或者: from matplotlib.patches.Rectangle import set_x [as 别名]
    def resizeGraphics(self, width, height):

        """ It is time to set a magnitude to our currently normalized
            lines, and send them to the figure. Here we assume that
            __normLines & __normPatches are already fully populated. """
        self.__fig.lines   = [] # clear all old lines from figure
        self.__fig.patches = [] # clear all old patches from figure
        self.__xsz = width
        self.__ysz = height

        # scale each text item
        for t in self.__fig.texts:
            t.set_size(self.getTextPointSize(t.gkiTextSzFactor, width, height))

        # scale each line, then apply it to the figure
        for nrln in self.__normLines:
            ll = Line2D([], [])
            ll.update_from(nrln)
            ll.set_data(nrln.get_xdata(True)*self.__xsz,
                        nrln.get_ydata(True)*self.__ysz)
            self.__fig.lines.append(ll)

        # scale each patch, then apply it to the figure
        for nrpa in self.__normPatches:
            rr = Rectangle((0,0),0,0)
            rr.update_from(nrpa)
            rr.set_x(nrpa.get_x()*self.__xsz)
            rr.set_y(nrpa.get_y()*self.__ysz)
            rr.set_width(nrpa.get_width()*self.__xsz)
            rr.set_height(nrpa.get_height()*self.__ysz)
            self.__fig.patches.append(rr)
开发者ID:jhunkeler,项目名称:pyraf,代码行数:33,代码来源:GkiMpl.py

示例3: IncomingCube

# 需要导入模块: from matplotlib.patches import Rectangle [as 别名]
# 或者: from matplotlib.patches.Rectangle import set_x [as 别名]
class IncomingCube(object):
    def __init__(self, axis, m, x0, x0_prime):
        self._t = 0
        self._pot = Rectangle((x0, -CUBE_HEIGHT/2), CUBE_WIDTH, CUBE_HEIGHT, color='red')

        self._ax = axis
        axis.add_patch(self._pot)
        self._cubePos = CubePhysics(m, x0, x0_prime)

    def set_time(self, t):
        if not pause:
            self._t = t * delta
            self.update()
        # yield self._t

    @property
    def u(self):
        return 1 + self._cubePos(self._t)

    def update(self):
        self._pot.set_x(self.u-CUBE_WIDTH)
开发者ID:janMaha,项目名称:CompanionCube_SAC2015,代码行数:23,代码来源:dockingAnim2.py

示例4: CustomToolbar

# 需要导入模块: from matplotlib.patches import Rectangle [as 别名]
# 或者: from matplotlib.patches.Rectangle import set_x [as 别名]

#.........这里部分代码省略.........
    def release_zoom(self, ev):
        if wx.Platform == "__WXMAC__":
            self.to_draw.set_visible(False)
        NavToolbar.release_zoom(self, ev)

    def draw_rubberband(self, event, x0, y0, x1, y1):
        # XOR does not work on MacOS ...
        if wx.Platform != "__WXMAC__":
            NavToolbar.draw_rubberband(self, event, x0, y0, x1, y1)
        else:
            if self.background is not None:
                self.canvas.restore_region(self.background)
            c0, c1 = self.ax.transData.inverted().transform([[x0, y0], [x1, y1]])
            l, b = c0
            r, t = c1
            self.to_draw.set_bounds(l, b, r - l, t - b)
            self.ax.draw_artist(self.to_draw)
            self.canvas.blit(self.ax.bbox)

    def update_background(self):
        """force an update of the background"""
        self.background = self.canvas.copy_from_bbox(self.ax.bbox)

    # Turn on selection
    # TODO: Proper handling of states, actual functionality.
    def _on_custom_select(self, evt):
        #        for id in ['Zoom','Pan']:
        #            self.ToggleTool(self.wx_ids[id], False)
        #        print('Select ROI: %s' % (self.GetToolState(self.wx_ids['ROI'])))
        #        self.ToggleTool(self.wx_ids['ROI'],
        #                self.GetToolState(self.wx_ids['ROI']) )
        self.toggle_selector()

    #        print('Select ROI: %s' % (self.GetToolState(self.wx_ids['ROI'])))

    def onSelect(self, eclick, erelease):
        "eclick and erelease are matplotlib events at press and release"
        #        print(' startposition : (%f, %f)' % (eclick.xdata, eclick.ydata))
        #        print(' endposition   : (%f, %f)' % (erelease.xdata, erelease.ydata))
        #        print(' used button   : ', eclick.button)
        self.updateROI(
            min(eclick.xdata, erelease.xdata),
            min(eclick.ydata, erelease.ydata),
            abs(eclick.xdata - erelease.xdata),
            abs(eclick.ydata - erelease.ydata),
        )
        if self.canvas.parentFrame.fixedNumberCB.IsChecked():
            # We are working in the fixed-number mode
            # We need to find new roi for this center point
            # The handler will call the update ROI function for us.
            self.canvas.parentFrame.handleROIforN()

    def updateROI(self, x, y, w, h):
        if self.roi is None:
            # print('upd ROI:', x, y, w, h)
            self.roi = Rectangle((x, y), w, h, ls="solid", lw=2, color="r", fill=False, zorder=5)
            self.canvas.figure.axes[0].add_patch(self.roi)
        else:
            self.roi.set_bounds(x, y, w, h)
        self.updateCanvas()

    def toggle_selector(self):
        self.selector.set_active(not self.selector.active)

    def onFixedSize(self, ev):
        self.fixedSize = ev.IsChecked()
        self.updateCanvas()

    def onWidthChange(self, ev):
        if self.roi:
            x = self.roi.get_x()
            w = self.roi.get_width()
            nw = ev.GetValue()
            dw = {"C": (w - nw) / 2, "L": 0, "R": w - nw}[self.canvas.parentFrame.anchorRB.GetStringSelection()[0]]
            self.roi.set_x(x + dw)
            self.roi.set_width(nw)
            self.updateCanvas()

    def onHeightChange(self, ev):
        if self.roi:
            y = self.roi.get_y()
            h = self.roi.get_height()
            nh = ev.GetValue()
            dh = {"C": (h - nh) / 2, "B": 0, "T": h - nh}[self.canvas.parentFrame.anchorRB.GetStringSelection()[-1]]
            self.roi.set_y(y + dh)
            self.roi.set_height(nh)
            self.updateCanvas()

    def updateCanvas(self, redraw=True):
        if self.roi:
            self.canvas.parentFrame.showROI(
                self.roi.get_x(), self.roi.get_y(), self.roi.get_width(), self.roi.get_height()
            )
            self.canvas.parentFrame.setWH(self.roi.get_width(), self.roi.get_height())
            if self.fixedSize:
                self.selector.setSize(self.roi.get_width(), self.roi.get_height())
            else:
                self.selector.setSize()
        if redraw:
            self.draw()
开发者ID:jochym,项目名称:pointsel,代码行数:104,代码来源:pointsel.py

示例5: __init__

# 需要导入模块: from matplotlib.patches import Rectangle [as 别名]
# 或者: from matplotlib.patches.Rectangle import set_x [as 别名]

#.........这里部分代码省略.........
            xmin, ymin = self.eventpress.xdata, self.eventpress.ydata
            xmax, ymax = self.eventrelease.xdata, self.eventrelease.ydata
            # calculate dimensions of box 
            if xmin > xmax: xmin, xmax = xmax, xmin
            if ymin > ymax: ymin, ymax = ymax, ymin
            spanx = xmax - xmin
            spany = ymax - ymin
            xproblems = self.minspanx is not None and spanx < self.minspanx
            yproblems = self.minspany is not None and spany < self.minspany
        # call desired function
        self.onselect()
        self.eventpress = None                # reset the variables to their
        self.eventrelease = None              #   inital values

    def update(self):
        """draw using blit or old draw depending on useblit"""
        if self.useblit:
            if self.background is not None:
                self.canvas.restore_region(self.background)
            self.ax.draw_artist(self.to_draw)
            self.canvas.blit(self.ax.bbox)
        else:
            self.canvas.draw_idle()

    def onmove(self, event):
        """on move event"""
        if self.eventpress is None or self.ignore(event): return
        x, y = event.xdata, event.ydata         # actual position 
                                                # with button still pressed
        minx, maxx = self.eventpress.xdata, x   # click-x and actual mouse-x
        miny, maxy = self.eventpress.ydata, y   # click-y and actual mouse-y
        if minx > maxx: minx, maxx = maxx, minx # get them in the right order
        if miny > maxy: miny, maxy = maxy, miny
        self.to_draw.set_x(minx)                # set lower left of box
        self.to_draw.set_y(miny)
        self.to_draw.set_width(maxx - minx)     # set width and height of box
        self.to_draw.set_height(maxy - miny)
        self.update()

    def keypress(self, event):
        """on key press event"""
        if self.ignore(event): return
        self.eventpress = event
        if event.key == 'q':
            self.eventpress = None
            self.close()

    def plot_gaussians(self, params):
        """plot Gaussian components and profile"""
        plt.subplot(211)
        plt.cla()
        # Re-plot the original profile
        plt.hlines(0, 0.0, 1.0, color='black', lw=1, alpha=0.3, linestyle=':')
        plt.plot(self.phases, self.profile, c='black', lw=3, alpha=0.3)
        plt.xlabel('Pulse Phase')
        plt.ylabel('Pulse Amplitude')
        prefit_buff = 0.1
        postfit_buff = 0.1
        if self.fit_scattering: prefit_buff = 1.0
        ymin,ymax = plt.ylim()
        ymin = params[0] - prefit_buff*(self.profile.max()-self.profile.min())
        ymax = self.profile.max() + prefit_buff * \
                (self.profile.max()-self.profile.min())
        plt.ylim(ymin, ymax)
        DC = params[0]
        tau = params[1]
开发者ID:pennucci,项目名称:PulsePortraiture,代码行数:70,代码来源:ppgauss.py

示例6: __init__

# 需要导入模块: from matplotlib.patches import Rectangle [as 别名]
# 或者: from matplotlib.patches.Rectangle import set_x [as 别名]
class GaussianSelector:
    def __init__(self, ax, profile, errs, profnm, minspanx=None,
                 minspany=None, useblit=True):
        self.ax = ax.axes
        self.profile = profile
        self.proflen = len(profile)
        self.profnm = profnm
        self.phases = Num.arange(self.proflen, dtype='d')/self.proflen
        self.errs = errs
        self.visible = True
        self.DCguess = sorted(profile)[len(profile)/10+1]
        self.init_params = [self.DCguess]
        self.numgaussians = 0
        self.canvas = ax.figure.canvas
        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)
        self.background = None
        self.rectprops = dict(facecolor='white', edgecolor = 'black',
                              alpha=0.5, fill=False)
        self.to_draw = Rectangle((0,0), 0, 1, visible=False, **self.rectprops)
        self.ax.add_patch(self.to_draw)
        self.useblit = useblit
        self.minspanx = minspanx
        self.minspany = minspany
        # will save the data (position at mouseclick)
        self.eventpress = None            
        # will save the data (pos. at mouserelease)
        self.eventrelease = None          
        self.plot_gaussians(self.init_params)

    def update_background(self, event):
        'force an update of the background'
        if self.useblit:
            self.background = self.canvas.copy_from_bbox(self.ax.bbox)
        
    def ignore(self, event):
        'return True if event should be ignored'
        # If no button was pressed yet ignore the event if it was out
        # of the axes
        if self.eventpress == None:
            return event.inaxes!= self.ax       
        # If a button was pressed, check if the release-button is the
        # same.
        return (event.inaxes!=self.ax or
                event.button != self.eventpress.button)
      
    def press(self, event):
        'on button press event'
        # Is the correct button pressed within the correct axes?
        if self.ignore(event): return         
        # make the drawed box/line visible get the click-coordinates,
        # button, ...
        self.eventpress = event               
        if event.button==1:
            self.to_draw.set_visible(self.visible)
            self.eventpress.ydata = self.DCguess

    def release(self, event):
        'on button release event'
        if self.eventpress is None or self.ignore(event): return
        # release coordinates, button, ...
        self.eventrelease = event             
        if event.button==1:
            # make the box/line invisible again
            self.to_draw.set_visible(False)       
            self.canvas.draw()
            xmin, ymin = self.eventpress.xdata, self.eventpress.ydata
            xmax, ymax = self.eventrelease.xdata, self.eventrelease.ydata
            # calculate dimensions of box 
            if xmin>xmax: xmin, xmax = xmax, xmin        
            if ymin>ymax: ymin, ymax = ymax, ymin
            spanx = xmax - xmin                  
            spany = ymax - ymin
            xproblems = self.minspanx is not None and spanx<self.minspanx
            yproblems = self.minspany is not None and spany<self.minspany
        # call desired function
        self.onselect()
        self.eventpress = None                # reset the variables to their
        self.eventrelease = None              #   inital values

    def update(self):
        'draw using newfangled blit or oldfangled draw depending on useblit'
        if self.useblit:
            if self.background is not None:
                self.canvas.restore_region(self.background)
            self.ax.draw_artist(self.to_draw)
            self.canvas.blit(self.ax.bbox)
        else:
            self.canvas.draw_idle()

    def onmove(self, event):
        if self.eventpress is None or self.ignore(event): return
        x,y = event.xdata, event.ydata # actual position with button still pressed
        minx, maxx = self.eventpress.xdata, x # click-x and actual mouse-x
        miny, maxy = self.eventpress.ydata, y # click-y and actual mouse-y
        if minx>maxx: minx, maxx = maxx, minx # get them in the right order
        if miny>maxy: miny, maxy = maxy, miny
        self.to_draw.set_x(minx)             # set lower left of box
#.........这里部分代码省略.........
开发者ID:ariofrio,项目名称:presto,代码行数:103,代码来源:pygaussfit.py

示例7: __init__

# 需要导入模块: from matplotlib.patches import Rectangle [as 别名]
# 或者: from matplotlib.patches.Rectangle import set_x [as 别名]
class RangeSelector:
    def __init__(self, axes, callbackPre, callbackPost):
        self.axes = axes
        self.callbackPre = callbackPre
        self.callbackPost = callbackPost

        self.eventPressed = None
        self.eventReleased = None

        props = dict(facecolor="red", edgecolor="white", alpha=0.25, fill=True, zorder=100, gid="range")
        self.rect = Rectangle((0, 0), 0, 0, **props)
        self.axes.add_patch(self.rect)

        figure = self.axes.get_figure()
        figure.canvas.mpl_connect("motion_notify_event", self.__on_move)
        figure.canvas.mpl_connect("button_press_event", self.__on_press)
        figure.canvas.mpl_connect("button_release_event", self.__on_release)

    def __on_press(self, event):
        if self.__skip_event(event):
            return

        self.eventPressed = event
        self.callbackPre()
        self.rect.set_visible(True)
        return

    def __on_move(self, event):
        if self.eventPressed is None or self.__skip_event(event):
            return

        xMin = self.eventPressed.xdata
        xMax = event.xdata
        if xMin > xMax:
            xMin, xMax = xMax, xMin
        self.callbackPost(xMin, xMax)

        return

    def __on_release(self, event):
        if self.eventPressed is None or self.__skip_event(event):
            return

        self.eventReleased = event
        xMin, xMax = self.eventPressed.xdata, self.eventReleased.xdata
        if xMin > xMax:
            xMin, xMax = xMax, xMin
        self.callbackPost(xMin, xMax)
        self.eventPressed = None
        self.eventReleased = None
        return

    def __skip_event(self, event):
        if event.button != 2:
            return True

        if self.eventPressed is None:
            return event.inaxes != self.axes

        if event.button == self.eventPressed.button and event.inaxes != self.axes:
            transform = self.axes.transData.inverted()
            (x, _y) = transform.transform_point((event.x, event.y))
            x0, x1 = self.axes.get_xbound()
            x = max(x0, x)
            x = min(x1, x)
            event.xdata = x
            return False

        return event.inaxes != self.axes or event.button != self.eventPressed.button

    def draw(self, xMin, xMax):
        self.rect.set_visible(True)
        yMin, yMax = self.axes.get_ylim()
        height = yMax - yMin
        yMin -= height * 100.0
        yMax += height * 100.0
        self.rect.set_x(xMin)
        self.rect.set_y(yMin)
        self.rect.set_width(xMax - xMin)
        self.rect.set_height(yMax - yMin)

        if self.axes._cachedRenderer is not None:
            self.axes.draw_artist(self.rect)

    def hide(self):
        self.rect.set_visible(False)

    def clear(self):
        self.rect.set_visible(False)
        canvas = self.axes.get_figure().canvas
        canvas.draw()
开发者ID:B-Rich,项目名称:RTLSDR-Scanner,代码行数:93,代码来源:plot_controls.py

示例8: CaseSelector

# 需要导入模块: from matplotlib.patches import Rectangle [as 别名]
# 或者: from matplotlib.patches.Rectangle import set_x [as 别名]

#.........这里部分代码省略.........
        # Reset canvas so that `new_axes` connects events.
        self.canvas = None
        self.new_axes(ax, nrect)

    def new_axes(self, ax, nrect):
        self.ax = ax
        if self.canvas is not ax.figure.canvas:
            if self.canvas is not None:
                self.disconnect_events()
            self.canvas = ax.figure.canvas
            self.connect_default_events()
        # span
        trans = blended_transform_factory(self.ax.transData, self.ax.transAxes)
        w, h = 0, 1
        self.rect = Rectangle((0, 0), w, h, transform=trans, visible=False,
                              animated=True, **self.rectprops)
        self.ax.add_patch(self.rect)
        self.artists = [self.rect]
        # stay rect
        self.stay_rects = []
        for set in range(0, len(nrect)):
            self.stay_rects.append([])
            for n in range(0, nrect[set]):
                stay_rect = Rectangle((0, 0), w, h, transform=trans, visible=False,
                                      animated=True, **self.stay_rectprops[set])
                self.ax.add_patch(stay_rect)
                self.stay_rects[set].append(stay_rect)
            self.artists.extend(self.stay_rects[set])
        # bar
        self.bar = ax.axvline(0, w, h, visible=False, **self.lineprops)
        self.artists.append(self.bar)

    def set_bar_position(self, x):
        self.bar.set_xdata(x)
        self.bar.set_visible(True)

    def set_stay_rects_x_bounds(self, xarr, set=0):
        for n, stay_rect in enumerate(self.stay_rects[set]):
            try:
                xmin, xmax = xarr[n]
            except IndexError:
                stay_rect.set_visible(False)
            else:
                stay_rect.set_x(xmin)
                stay_rect.set_y(self.rect.get_y())
                stay_rect.set_width(abs(xmax - xmin))
                stay_rect.set_height(self.rect.get_height())
                stay_rect.set_visible(True)

    def set_stay_rect_visible(self, b=True, set=0):
        for stay_rect in self.stay_rects[set]:
            stay_rect.set_visible(b)

    def ignore(self, event):
        """return *True* if *event* should be ignored"""
        return _SelectorWidget.ignore(self, event) or not self.visible

    def _press(self, event):
        """on button press event"""
        xdata, ydata = self._get_data(event)
        self.pressv = xdata
        return False

    def _release(self, event):
        """on button release event"""
        if self.pressv is None:
开发者ID:e-sr,项目名称:KG,代码行数:70,代码来源:mpl_widgets.py

示例9: Spring

# 需要导入模块: from matplotlib.patches import Rectangle [as 别名]
# 或者: from matplotlib.patches.Rectangle import set_x [as 别名]
class Spring(object):
    N = 100
    _hist_length = 100

    _spring_coords = np.zeros(N)
    _spring_coords[30:70] = 0.05 * (-1) ** np.arange(40)

    def __init__(self, axis, axis_history, k, m, c, F, x0, x0_prime):
        zeta = c/(2*np.sqrt(k*m))
        print zeta
        if c == 0 or F == 0:
            self._model = FreeUndamped(k, m, x0, x0_prime)
        elif zeta < 1:
            self._model = FreeUnderDamped(k, m, c, x0, x0_prime)
        elif zeta == 1:
            self._model = FreeCriticallyDamped(k, m, c, x0, x0_prime)
        elif zeta > 1:
            self._model = FreeOverDamped(k, m, c, x0, x0_prime)
        else:
            raise NotImplementedError()

        self._t = 0
        self._anchor = axis.vlines([0], -0.1, 0.1, linewidth=5, color='black')
        self._pot = Rectangle((self.u-PLAT_WIDTH, -PLAT_HEIGHT/2), PLAT_WIDTH, PLAT_HEIGHT, color='black')
        self._pot2 = Rectangle((self.u+CUBE_WIDTH, -CUBE_HEIGHT/2), CUBE_WIDTH, CUBE_HEIGHT, color='red')
        # self._pot = Circle((self.u, 0), 0.05, color='black')
        self._spring, = axis.plot(*self._spring_xy(), color='black')

        axis.vlines([1], -0.1, -0.2)
        axis.text(1, -0.25, '$x = 0$', horizontalalignment='center')

        self._ax = axis
        axis.add_patch(self._pot)
        axis.add_patch(self._pot2)
        axis.set_xlim([XLIMMIN, XLIMMAX])
        axis.set_ylim([YLIMMIN, YLIMMAX])
        axis.set_axis_off()
        axis.set_aspect('equal')

        self._history = [self.u - 1] * self._hist_length
        self._history_plot, = axis_history.plot(np.arange(self._hist_length) * delta, self._history)
        axis_history.annotate('Now',
                              (self._hist_length * delta, 1.5),
                              (self._hist_length * delta, 1.8),
                              arrowprops=dict(arrowstyle='->'),
                              horizontalalignment='center')
        axis_history.set_ylim(-2, 1.5)
        axis_history.set_xticks([])
        axis_history.set_xlabel(r'$\mathrm{Time}$')
        axis_history.set_ylabel(r'$\mathrm{Position,\, x}$')

    def _spring_xy(self):
        return np.linspace(0, self.u, self.N), self._spring_coords

    def set_time(self, t):
        if not pause:
            self._t = t * delta
            self.update()
        # yield self._t

    @property
    def u(self):
        # print self._t
        # print self._model(self._t)
        return 1 + self._model(self._t)

    def update(self):
        # self._pot.center = (self.u, 0)
        self._pot.set_x(self.u-PLAT_WIDTH)
        self._pot2.set_x(self.u)
        
        x, y = self._spring_xy()
        self._spring.set_xdata(x)

        self._history.append(self.u - 1)
        self._history = self._history[-self._hist_length:]

        self._history_plot.set_ydata(self._history)
开发者ID:janMaha,项目名称:CompanionCube_SAC2015,代码行数:80,代码来源:dockingAnim2.py

示例10: Brusher

# 需要导入模块: from matplotlib.patches import Rectangle [as 别名]
# 或者: from matplotlib.patches.Rectangle import set_x [as 别名]
class Brusher():
    '''
    A generic brusher.
    
    Expects:
    fig:  a mpl figure with subplots
      NOTE: each individual point, in each subplot, must be assigned its own color.
            e.g. use `scatter(x_coords, y_coords, c=array_of_rgba_colors)`
    data: a tuple of numpy arrays, with one entry for each axis in fig, in order (i.e. left->right then top->bottom)
      each item in the tuple must by a 2d numpy array with:
      array[0] --> 1d array of x coordinates
      array[1] --> 1d array of y coordinates
      and each list must be in the same order.
      i.e. the nth pair of values in the first array of the tuple must correspond
           to the nth pair of values in every other array in the tuple.
    '''
    
    def __init__(self, fig, data):
        '''
        fig:  a pre-rendered figure, with subplot axes
        data: the data represented in fig, formatted as described above
        '''
        self.fig  = fig
        self.data = data
        self.axl  = fig.get_axes()
        
        # internal things to keep track of
        self.button_down = False
        self.brush       = None
        self.brush_axis  = None
        self.start_xy    = (None, None)
        
        # define the colors we want to use (overwrites original figure's colors)
        self.unbrushed_color = [.5, .5, .5, .5]  # this is a transparent gray
        self.brushed_color   = [0., 0., 1., .75]  # this is a transparent blue

        # register events to track
        self.fig.canvas.mpl_connect('button_press_event', self.button_press)
        self.fig.canvas.mpl_connect('motion_notify_event', self.mouse_motion)
        self.fig.canvas.mpl_connect('button_release_event', self.button_release)


    def button_press(self, event):
        ''' handles a mouse click '''
        # if clicked outside of axes, ignore
        if not event.inaxes: return

        # remove old brush object if it's there
        if self.brush:
            self.brush.remove()
            self.unbrush_me()
            plt.draw()
    
        # start a brush here
        self.button_down = True
        self.start_xy    = (event.xdata,event.ydata)
        self.brush       = Rectangle( self.start_xy, 0,0, facecolor='gray', alpha=.15 )
        self.brush_axis  = event.inaxes
        
        # add brush to axis
        event.inaxes.add_patch(self.brush)
        plt.draw()
        
        
    def mouse_motion(self, event):
        ''' handles the mouse moving around '''
        # if we haven't already clicked and started a brush, ignore the motion
        if not (self.button_down and self.brush): return
        # if we've moved the mouse outside the starting axis, ignore
        if self.brush_axis != event.inaxes: return

        # otherwise, track the motion and update the brush
        self.brush.set_width( abs(self.start_xy[0] - event.xdata) )
        self.brush.set_height( abs(self.start_xy[1] - event.ydata) )
        self.brush.set_x( min(self.start_xy[0], event.xdata) )
        self.brush.set_y( min(self.start_xy[1], event.ydata) )
        plt.draw()


    def button_release(self, event):
        ''' handles a mouse button release '''
        self.button_down = False
        
        # if we didn't start with a brush, ignore
        if not self.brush: return
        
        # if we just clicked without drawing, remove the brush
        if (event.xdata, event.ydata) == self.start_xy:
            self.unbrush_me()
            plt.draw()
            return
        
        # if we stopped inside the same axis, update the brush one last time
        if event.inaxes == self.brush_axis:
            self.brush.set_width( abs(self.start_xy[0] - event.xdata) )
            self.brush.set_height( abs(self.start_xy[1] - event.ydata) )
            self.brush.set_x( min(self.start_xy[0], event.xdata) )
            self.brush.set_y( min(self.start_xy[1], event.ydata) )
        
        self.brush_me()
#.........这里部分代码省略.........
开发者ID:matarhaller,项目名称:Seminar,代码行数:103,代码来源:brusher.py

示例11: ModelStar

# 需要导入模块: from matplotlib.patches import Rectangle [as 别名]
# 或者: from matplotlib.patches.Rectangle import set_x [as 别名]
class ModelStar( Star ):   #StarApertures
    #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     
    psf = GaussianPSF()
    
    #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     
    #@unhookPyQt
    def __init__(self, idx, window, resolution=None):
        
        banner( 'ModelStar.__init__', bg='green' )
        
        #TODO:  kill idx
        self.idx = idx
        self.window = window
        self.resolution = resolution or window
        
        #self.psf = psf
        coo = [( window/2, window/2 )]
        wslice = (slice(0, window),)*2
        
        super().__init__( coo=coo[0], 
                          slice=wslice,
                          sky_mean=0 )      #won't calculate rprofile as no image kw
        
        #self.apertures = ApertureCollection( radii=np.zeros(4), 
                                             #coords=fakecoo, 
                                             #colours=['k','w','g','g'], 
                                             #ls=['dotted','dotted','solid','solid'])
        
        orange = colorConverter.to_rgba_array('orangered')         #HACK!
        
        psfaps = dict( coords=[coo,coo], 
                        radii=np.zeros(2), 
                        ls=':', 
                        colours=['k','w'],
                        pickradius=0, )
                        #**kw)
        photaps = dict( coords=coo, 
                        radii=[0],
                        gc='c',
                        badcolour=orange)     #FIXME:  keyword translation
        skyaps = dict( radii=np.zeros(2), 
                        coords=[coo,coo], )
                                    #**kw )
                                    
        self.apertures = StarApertures( psfaps, photaps, skyaps )
        
        self.has_plot = False
    
    #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
    #@profile()
    @unhookPyQt
    def init_plots(self, fig):
        #print('!'*88, '\ninitializing model plots\n', '!'*88, )
        
        ##### Plots for mean profile #####
        self.mainfig = fig
        _, self.ax_zoom, self.ax_prof, _ = fig.axes
        
        self.radial = RadialProfiles( self.ax_prof )
        
        #TODO:  AxesContainer
        
        self.pl_zoom = self.ax_zoom.imshow([[0]], origin='lower', cmap = 'gist_heat')  #, animated=True #vmin=self.zlims[0], vmax=self.zlims[1]
        self.colour_bar = fig.colorbar( self.pl_zoom, ax=self.ax_zoom )
        
        self.pl_zoom.set_clim( 0, 1 )
        self.pl_zoom.set_extent( [0, self.window, 0, self.window] )

        
        ##### stellar profile + psf model #####
       
        #self.pl_prof = 
        
        #embed()
        
        ##### apertures #####
        for aps in self.apertures:
            lines = aps.aplines = ApLineCollection( aps, self.ax_prof  )
            #lines.set_animated( True )
            self.ax_prof.add_collection( lines )
            #lines.axadd( self.ax_prof )
            aps.axadd( self.ax_zoom )
        
        #w2b(self.apertures.psf.aplines)      #convert white lines to black for displaying on white canvas
        
        ##### sky fill #####
        from matplotlib.patches import Rectangle
        
        trans = self.apertures.psf.aplines.get_transform()
        self.sky_fill = Rectangle( (0,0), width=0, height=1, transform=trans, color='b', alpha=0.3)     #, animated=True
        self.ax_prof.add_artist( self.sky_fill )
        
        self.ax_prof.set_xlim( 0, self.window/2 )
        
        self.has_plot = True
        lines.set_visible( False )
        
        #set all the artist invisible to start with - we'll create a background from this for blitting
        #self.set_visible( False )
        
#.........这里部分代码省略.........
开发者ID:apodemus,项目名称:obstools,代码行数:103,代码来源:stars.py


注:本文中的matplotlib.patches.Rectangle.set_x方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。