def _get_handles(self, handles, texts): HEIGHT = self._approx_text_height() ret = [] # the returned legend lines for handle, label in zip(handles, texts): x, y = label.get_position() x -= self.HANDLELEN + self.HANDLETEXTSEP if isinstance(handle, Line2D): ydata = (y - HEIGHT / 2) * ones(self._xdata.shape, Float) legline = Line2D(self._xdata, ydata) self._set_artist_props(legline) legline.copy_properties(handle) legline.set_markersize(0.6 * legline.get_markersize()) legline.set_data_clipping(False) ret.append(legline) elif isinstance(handle, Patch): p = Rectangle( xy=(min(self._xdata), y - 3 / 4 * HEIGHT), width=self.HANDLELEN, height=HEIGHT / 2, ) self._set_artist_props(p) p.copy_properties(handle) ret.append(p) else: ret.append(None) return ret
def new_axes(self, ax): self.ax = ax if self.canvas is not ax.figure.canvas: for cid in self.cids: self.canvas.mpl_disconnect(cid) self.canvas = ax.figure.canvas self.cids.append( self.canvas.mpl_connect('motion_notify_event', self.onmove)) self.cids.append( self.canvas.mpl_connect('button_press_event', self.press)) self.cids.append( self.canvas.mpl_connect('button_release_event', self.release)) self.cids.append( self.canvas.mpl_connect('draw_event', self.update_background)) if self.direction == 'horizontal': trans = blended_transform_factory(self.ax.transData, self.ax.transAxes) w, h = 0, 1 else: trans = blended_transform_factory(self.ax.transAxes, self.ax.transData) w, h = 1, 0 self.rect = Rectangle((0, 0), w, h, transform=trans, visible=False, **self.rectprops) if not self.useblit: self.ax.add_patch(self.rect)
def __init__( self, figsize=None, # defaults to rc figure.figsize dpi=None, # defaults to rc figure.dpi facecolor=None, # defaults to rc figure.facecolor edgecolor=None, # defaults to rc figure.edgecolor linewidth=1.0, # the default linewidth of the frame frameon=True, # whether or not to draw the figure frame subplotpars=None, # default to rc ): """ figsize is a w,h tuple in inches dpi is dots per inch subplotpars is a SubplotParams instance, defaults to rc """ Artist.__init__(self) #self.set_figure(self) self._axstack = Stack() # maintain the current axes self._axobservers = [] self._seen = {} # axes args we've seen if figsize is None: figsize = rcParams['figure.figsize'] if dpi is None: dpi = rcParams['figure.dpi'] if facecolor is None: facecolor = rcParams['figure.facecolor'] if edgecolor is None: edgecolor = rcParams['figure.edgecolor'] self._unit_conversions = {} self.dpi = Value(dpi) self.figwidth = Value(figsize[0]) self.figheight = Value(figsize[1]) self.ll = Point(Value(0), Value(0)) self.ur = Point(self.figwidth * self.dpi, self.figheight * self.dpi) self.bbox = Bbox(self.ll, self.ur) self.frameon = frameon self.transFigure = get_bbox_transform(unit_bbox(), self.bbox) self.figurePatch = Rectangle( xy=(0, 0), width=1, height=1, facecolor=facecolor, edgecolor=edgecolor, linewidth=linewidth, ) self._set_artist_props(self.figurePatch) self._hold = rcParams['axes.hold'] self.canvas = None if subplotpars is None: subplotpars = SubplotParams() self.subplotpars = subplotpars self.clf() self._cachedRenderer = None
def __init__( self, xy, width, height, edgecolor='k', facecolor='w', fill=True, text='', loc=None, ): # Call base Rectangle.__init__( self, xy, width=width, height=height, edgecolor=edgecolor, facecolor=facecolor, ) self.set_clip_on(False) # Create text object if loc is None: loc = 'right' self._loc = loc self._text = Text(x=xy[0], y=xy[1], text=text) self._text.set_clip_on(False)
def _get_handles(self, handles, texts): HEIGHT = self._approx_text_height() ret = [] # the returned legend lines for handle, label in zip(handles, texts): x, y = label.get_position() x -= self.HANDLELEN + self.HANDLETEXTSEP if isinstance(handle, Line2D): ydata = (y - HEIGHT / 2) * ones(self._xdata.shape, Float) legline = Line2D(self._xdata, ydata) self._set_artist_props(legline) legline.copy_properties(handle) legline.set_markersize(0.6 * legline.get_markersize()) legline.set_data_clipping(False) ret.append(legline) elif isinstance(handle, Patch): p = Rectangle(xy=(min(self._xdata), y - 3 / 4 * HEIGHT), width=self.HANDLELEN, height=HEIGHT / 2) self._set_artist_props(p) p.copy_properties(handle) ret.append(p) else: ret.append(None) return ret
def draw(self, renderer): # draw the rectangle Rectangle.draw(self, renderer) # position the text self._set_text_position(renderer) self._text.draw(renderer)
def draw(self, renderer): if not self.get_visible(): return # draw the rectangle Rectangle.draw(self, renderer) # position the text self._set_text_position(renderer) self._text.draw(renderer)
def draw(self, renderer): # draw the rectangle Rectangle.draw(self, renderer) # position the text self._set_text_position() self._text.draw(renderer)
def __init__( self, xy, width, height, edgecolor="k", facecolor="w", fill=True, text="", loc=None, fontproperties=None ): Rectangle.__init__(self, xy, width=width, height=height, edgecolor=edgecolor, facecolor=facecolor) self.set_clip_on(False) if loc is None: loc = "right" self._loc = loc self._text = Text(x=xy[0], y=xy[1], text=text, fontproperties=fontproperties) self._text.set_clip_on(False)
def __init__( self, figsize=None, # defaults to rc figure.figsize dpi=None, # defaults to rc figure.dpi facecolor=None, # defaults to rc figure.facecolor edgecolor=None, # defaults to rc figure.edgecolor linewidth=1.0, # the default linewidth of the frame frameon=True, # whether or not to draw the figure frame subplotpars=None, # default to rc ): """ figsize is a w,h tuple in inches dpi is dots per inch subplotpars is a SubplotParams instance, defaults to rc """ Artist.__init__(self) if figsize is None: figsize = rcParams['figure.figsize'] if dpi is None: dpi = rcParams['figure.dpi'] if facecolor is None: facecolor = rcParams['figure.facecolor'] if edgecolor is None: edgecolor = rcParams['figure.edgecolor'] self._dpi_scale_trans = Affine2D() self.dpi = dpi self.bbox_inches = Bbox.from_bounds(0, 0, *figsize) self.bbox = TransformedBbox(self.bbox_inches, self._dpi_scale_trans) self.frameon = frameon self.transFigure = BboxTransformTo(self.bbox) self.figurePatch = Rectangle( xy=(0, 0), width=1, height=1, facecolor=facecolor, edgecolor=edgecolor, linewidth=linewidth, ) self._set_artist_props(self.figurePatch) self._hold = rcParams['axes.hold'] self.canvas = None if subplotpars is None: subplotpars = SubplotParams() self.subplotpars = subplotpars self._axstack = Stack() # maintain the current axes self.axes = [] self.clf() self._cachedRenderer = None self._autoLayout = rcParams['figure.autolayout']
def __init__(self, ax, onselect, minspan=None, useblit=False, rectprops=None): """ Create a span selector in ax. When a selection is made, clear the span and call onselect with onselect(xmin, xmax) and clear the span. If minspan is not None, ignore events smaller than minspan The span rect is drawn with rectprops; default rectprops = dict(facecolor='red', alpha=0.5) set the visible attribute to False if you want to turn off the functionality of the span selector """ if rectprops is None: rectprops = dict(facecolor='red', alpha=0.5) self.ax = ax self.visible = True 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.rect = None self.background = None self.rectprops = rectprops self.onselect = onselect self.useblit = useblit self.minspan = minspan trans = blend_xy_sep_transform(self.ax.transData, self.ax.transAxes) self.rect = Rectangle((0, 0), 0, 1, transform=trans, visible=False, **self.rectprops) if not self.useblit: self.ax.add_patch(self.rect) self.pressx = None
def candlestick(ax, quotes, width=0.2, colorup="k", colordown="r", alpha=1.0): """ quotes is a list of (time, open, close, high, low, ...) tuples. As long as the first 5 elements of the tuples are these values, the tuple can be as long as you want (eg it may store volume). time must be in float days format - see date2num Plot the time, open, close, high, low as a vertical line ranging from low to high. Use a rectangular bar to represent the open-close span. If close >= open, use colorup to color the bar, otherwise use colordown ax : an Axes instance to plot to width : fraction of a day for the rectangle width colorup : the color of the rectangle where close >= open colordown : the color of the rectangle where close < open alpha : the rectangle alpha level return value is lines, patches where lines is a list of lines added and patches is a list of the rectangle patches added """ OFFSET = width / 2.0 lines = [] patches = [] for q in quotes: t, open, close, high, low = q[:5] if close >= open: color = colorup lower = open height = close - open else: color = colordown lower = close height = open - close vline = Line2D(xdata=(t, t), ydata=(low, high), color="k", linewidth=0.5, antialiased=True) rect = Rectangle(xy=(t - OFFSET, lower), width=width, height=height, facecolor=color, edgecolor=color) rect.set_alpha(alpha) lines.append(vline) patches.append(rect) ax.add_line(vline) ax.add_patch(rect) ax.autoscale_view() return lines, patches
def __init__(self, ax, onselect, drawtype='box', minspanx=None, minspany=None, useblit=False, lineprops=None, rectprops=None, spancoords='data'): """ Create a selector in ax. When a selection is made, clear the span and call onselect with onselect(pos_1, pos_2) and clear the drawn box/line. There pos_i are arrays of length 2 containing the x- and y-coordinate. If minspanx is not None then events smaller than minspanx in x direction are ignored(it's the same for y). The rect is drawn with rectprops; default rectprops = dict(facecolor='red', edgecolor = 'black', alpha=0.5, fill=False) The line is drawn with lineprops; default lineprops = dict(color='black', linestyle='-', linewidth = 2, alpha=0.5) Use type if you want the mouse to draw a line, a box or nothing between click and actual position ny setting drawtype = 'line', drawtype='box' or drawtype = 'none'. spancoords is one of 'data' or 'pixels'. If 'data', minspanx and minspanx will be interpreted in the same coordinates as the x and ya axis, if 'pixels', they are in pixels """ self.ax = ax self.visible = True 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.active = True # for activation / deactivation self.to_draw = None self.background = None if drawtype == 'none': drawtype = 'line' # draw a line but make it self.visible = False # invisible if drawtype == 'box': if rectprops is None: rectprops = dict(facecolor='white', edgecolor = 'black', alpha=0.5, fill=False) self.rectprops = rectprops self.to_draw = Rectangle((0,0), 0, 1,visible=False,**self.rectprops) self.ax.add_patch(self.to_draw) if drawtype == 'line': if lineprops is None: lineprops = dict(color='black', linestyle='-', linewidth = 2, alpha=0.5) self.lineprops = lineprops self.to_draw = Line2D([0,0],[0,0],visible=False,**self.lineprops) self.ax.add_line(self.to_draw) self.onselect = onselect self.useblit = useblit self.minspanx = minspanx self.minspany = minspany assert(spancoords in ('data', 'pixels')) self.spancoords = spancoords self.drawtype = drawtype self.eventpress = None self.eventrelease = None
def new_axes(self,ax): self.ax = ax if self.canvas is not ax.figure.canvas: for cid in self.cids: self.canvas.mpl_disconnect(cid) self.canvas = ax.figure.canvas self.cids.append(self.canvas.mpl_connect('motion_notify_event', self.onmove)) self.cids.append(self.canvas.mpl_connect('button_press_event', self.press)) self.cids.append(self.canvas.mpl_connect('button_release_event', self.release)) self.cids.append(self.canvas.mpl_connect('draw_event', self.update_background)) if self.direction == 'horizontal': trans = blended_transform_factory(self.ax.transData, self.ax.transAxes) w,h = 0,1 else: trans = blended_transform_factory(self.ax.transAxes, self.ax.transData) w,h = 1,0 self.rect = Rectangle( (0,0), w, h, transform=trans, visible=False, **self.rectprops ) if not self.useblit: self.ax.add_patch(self.rect)
def __init__(self, figsize = None, # defaults to rc figure.figsize dpi = None, # defaults to rc figure.dpi facecolor = None, # defaults to rc figure.facecolor edgecolor = None, # defaults to rc figure.edgecolor linewidth = 1.0, # the default linewidth of the frame frameon = True, # whether or not to draw the figure frame subplotpars = None, # default to rc ): """ figsize is a w,h tuple in inches dpi is dots per inch subplotpars is a SubplotParams instance, defaults to rc """ Artist.__init__(self) #self.set_figure(self) self._axstack = Stack() # maintain the current axes self._axobservers = [] self._seen = {} # axes args we've seen if figsize is None : figsize = rcParams['figure.figsize'] if dpi is None : dpi = rcParams['figure.dpi'] if facecolor is None: facecolor = rcParams['figure.facecolor'] if edgecolor is None: edgecolor = rcParams['figure.edgecolor'] self._unit_conversions = {} self.dpi = Value(dpi) self.figwidth = Value(figsize[0]) self.figheight = Value(figsize[1]) self.ll = Point( Value(0), Value(0) ) self.ur = Point( self.figwidth*self.dpi, self.figheight*self.dpi ) self.bbox = Bbox(self.ll, self.ur) self.frameon = frameon self.transFigure = get_bbox_transform( unit_bbox(), self.bbox) self.figurePatch = Rectangle( xy=(0,0), width=1, height=1, facecolor=facecolor, edgecolor=edgecolor, linewidth=linewidth, ) self._set_artist_props(self.figurePatch) self._hold = rcParams['axes.hold'] self.canvas = None if subplotpars is None: subplotpars = SubplotParams() self.subplotpars = subplotpars self.clf() self._cachedRenderer = None
def __init__( self, figsize=None, # defaults to rc figure.figsize dpi=None, # defaults to rc figure.dpi facecolor=None, # defaults to rc figure.facecolor edgecolor=None, # defaults to rc figure.edgecolor linewidth=1.0, # the default linewidth of the frame frameon=True, ): """ paper size is a w,h tuple in inches DPI is dots per inch """ Artist.__init__(self) #self.set_figure(self) self._axstack = Stack() # maintain the current axes self._axobservers = [] self._seen = {} # axes args we've seen if figsize is None: figsize = rcParams['figure.figsize'] if dpi is None: dpi = rcParams['figure.dpi'] if facecolor is None: facecolor = rcParams['figure.facecolor'] if edgecolor is None: edgecolor = rcParams['figure.edgecolor'] self.dpi = Value(dpi) self.figwidth = Value(figsize[0]) self.figheight = Value(figsize[1]) self.ll = Point(Value(0), Value(0)) self.ur = Point(self.figwidth * self.dpi, self.figheight * self.dpi) self.bbox = Bbox(self.ll, self.ur) self.frameon = frameon self.transFigure = get_bbox_transform(unit_bbox(), self.bbox) self.figurePatch = Rectangle( xy=(0, 0), width=1, height=1, facecolor=facecolor, edgecolor=edgecolor, linewidth=linewidth, ) self._set_artist_props(self.figurePatch) self._hold = rcParams['axes.hold'] self.clf()
def __init__(self, xy, width, height, edgecolor='k', facecolor='w', fill=True, text='', loc=None, ): # Call base Rectangle.__init__(self, xy, width=width, height=height, edgecolor=edgecolor, facecolor=facecolor, ) self.set_clip_on(False) # Create text object if loc is None: loc = 'right' self._loc = loc self._text = Text(x=xy[0], y=xy[1], text=text) self._text.set_clip_on(False)
def _get_handles(self, handles, texts): HEIGHT = self._approx_text_height() ret = [] # the returned legend lines for handle, label in zip(handles, texts): x, y = label.get_position() x -= self.handlelen + self.handletextsep if isinstance(handle, Line2D): ydata = (y-HEIGHT/2)*ones(self._xdata.shape, Float) legline = Line2D(self._xdata, ydata) legline.update_from(handle) self._set_artist_props(legline) # after update legline.set_clip_box(None) legline.set_markersize(self.markerscale*legline.get_markersize()) legline.set_data_clipping(False) ret.append(legline) elif isinstance(handle, Patch): p = Rectangle(xy=(min(self._xdata), y-3/4*HEIGHT), width = self.handlelen, height=HEIGHT/2, ) p.update_from(handle) self._set_artist_props(p) p.set_clip_box(None) ret.append(p) elif isinstance(handle, LineCollection): ydata = (y-HEIGHT/2)*ones(self._xdata.shape, Float) legline = Line2D(self._xdata, ydata) self._set_artist_props(legline) legline.set_clip_box(None) lw = handle.get_linewidths()[0] dashes = handle.get_dashes() color = handle.get_colors()[0] legline.set_color(color) legline.set_linewidth(lw) legline.set_dashes(dashes) ret.append(legline) else: ret.append(None) return ret
def __init__(self, parent, handles, labels, loc, isaxes=True): Artist.__init__(self) if is_string_like(loc) and not self.codes.has_key(loc): verbose.report_error( 'Unrecognized location %s. Falling back on upper right; valid locations are\n%s\t' % (loc, '\n\t'.join(self.codes.keys()))) if is_string_like(loc): loc = self.codes.get(loc, 1) if isaxes: # parent is an Axes self.set_figure(parent.figure) else: # parent is a Figure self.set_figure(parent) self.parent = parent self.set_transform(get_bbox_transform(unit_bbox(), parent.bbox)) self._loc = loc # make a trial box in the middle of the axes. relocate it # based on it's bbox left, upper = 0.5, 0.5 if self.NUMPOINTS == 1: self._xdata = array([left + self.HANDLELEN * 0.5]) else: self._xdata = linspace(left, left + self.HANDLELEN, self.NUMPOINTS) textleft = left + self.HANDLELEN + self.HANDLETEXTSEP self.texts = self._get_texts(labels, textleft, upper) self.handles = self._get_handles(handles, self.texts) left, top = self.texts[-1].get_position() HEIGHT = self._approx_text_height() bottom = top - HEIGHT left -= self.HANDLELEN + self.HANDLETEXTSEP + self.PAD self.legendPatch = Rectangle( xy=(left, bottom), width=0.5, height=HEIGHT * len(self.texts), facecolor='w', edgecolor='k', ) self._set_artist_props(self.legendPatch) self._drawFrame = True
def __init__(self, figsize = None, # defaults to rc figure.figsize dpi = None, # defaults to rc figure.dpi facecolor = None, # defaults to rc figure.facecolor edgecolor = None, # defaults to rc figure.edgecolor linewidth = 1.0, # the default linewidth of the frame frameon = True, # whether or not to draw the figure frame subplotpars = None, # default to rc ): """ figsize is a w,h tuple in inches dpi is dots per inch subplotpars is a SubplotParams instance, defaults to rc """ Artist.__init__(self) self.callbacks = cbook.CallbackRegistry(('dpi_changed', )) if figsize is None : figsize = rcParams['figure.figsize'] if dpi is None : dpi = rcParams['figure.dpi'] if facecolor is None: facecolor = rcParams['figure.facecolor'] if edgecolor is None: edgecolor = rcParams['figure.edgecolor'] self.dpi_scale_trans = Affine2D() self.dpi = dpi self.bbox_inches = Bbox.from_bounds(0, 0, *figsize) self.bbox = TransformedBbox(self.bbox_inches, self.dpi_scale_trans) self.frameon = frameon self.transFigure = BboxTransformTo(self.bbox) self.figurePatch = Rectangle( xy=(0,0), width=1, height=1, facecolor=facecolor, edgecolor=edgecolor, linewidth=linewidth, ) self._set_artist_props(self.figurePatch) self._hold = rcParams['axes.hold'] self.canvas = None if subplotpars is None: subplotpars = SubplotParams() self.subplotpars = subplotpars self._axstack = Stack() # maintain the current axes self.axes = [] self.clf() self._cachedRenderer = None self._autoLayout = rcParams['figure.autolayout']
def update_bbox_position_size(self, renderer): """ Update the location and the size of the bbox. This method should be used when the position and size of the bbox needs to be updated before actually drawing the bbox. """ # For arrow_patch, use textbox as patchA by default. if not isinstance(self.arrow_patch, FancyArrowPatch): return if self._bbox_patch: trans = self.get_transform() # don't use self.get_position here, which refers to text position # in Text, and dash position in TextWithDash: posx = float(self.convert_xunits(self._x)) posy = float(self.convert_yunits(self._y)) posx, posy = trans.transform_point((posx, posy)) x_box, y_box, w_box, h_box = _get_textbox(self, renderer) self._bbox_patch.set_bounds(0., 0., w_box, h_box) theta = self.get_rotation()/180.*math.pi tr = mtransforms.Affine2D().rotate(theta) tr = tr.translate(posx+x_box, posy+y_box) self._bbox_patch.set_transform(tr) fontsize_in_pixel = renderer.points_to_pixels(self.get_size()) self._bbox_patch.set_mutation_scale(fontsize_in_pixel) #self._bbox_patch.draw(renderer) else: props = self._bbox if props is None: props = {} props = props.copy() # don't want to alter the pad externally pad = props.pop('pad', 4) pad = renderer.points_to_pixels(pad) bbox = self.get_window_extent(renderer) l,b,w,h = bbox.bounds l-=pad/2. b-=pad/2. w+=pad h+=pad r = Rectangle(xy=(l,b), width=w, height=h, ) r.set_transform(mtransforms.IdentityTransform()) r.set_clip_on( False ) r.update(props) self.arrow_patch.set_patchA(r)
def _get_handles(self, handles, texts): HEIGHT = self._approx_text_height() ret = [] # the returned legend lines for handle, label in zip(handles, texts): x, y = label.get_position() x -= self.handlelen + self.handletextsep if isinstance(handle, Line2D): ydata = (y - HEIGHT / 2) * ones(self._xdata.shape, Float) legline = Line2D(self._xdata, ydata) self._set_artist_props(legline) legline.copy_properties(handle) legline.set_markersize(0.6 * legline.get_markersize()) legline.set_data_clipping(False) ret.append(legline) elif isinstance(handle, Patch): p = Rectangle( xy=(min(self._xdata), y - 3 / 4 * HEIGHT), width=self.handlelen, height=HEIGHT / 2, ) p.copy_properties(handle) self._set_artist_props(p) ret.append(p) elif isinstance(handle, LineCollection): ydata = (y - HEIGHT / 2) * ones(self._xdata.shape, Float) legline = Line2D(self._xdata, ydata) self._set_artist_props(legline) lw = handle.get_linewidths()[0] color = handle.get_colors()[0] legline.set_color(color) legline.set_linewidth(lw) ret.append(legline) else: ret.append(None) return ret
def __init__(self, ax, onselect, minspan=None, useblit=False, rectprops=None): """ Create a span selector in ax. When a selection is made, clear the span and call onselect with onselect(xmin, xmax) and clear the span. If minspan is not None, ignore events smaller than minspan The span rect is drawn with rectprops; default rectprops = dict(facecolor='red', alpha=0.5) set the visible attribute to False if you want to turn off the functionality of the span selector """ if rectprops is None: rectprops = dict(facecolor='red', alpha=0.5) self.ax = ax self.visible = True 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.rect = None self.background = None self.rectprops = rectprops self.onselect = onselect self.useblit = useblit self.minspan = minspan trans = blend_xy_sep_transform(self.ax.transData, self.ax.transAxes) self.rect = Rectangle( (0,0), 0, 1, transform=trans, visible=False, **self.rectprops ) if not self.useblit: self.ax.add_patch(self.rect) self.pressx = None
def __init__( self, figsize=None, # defaults to rc figure.figsize dpi=None, # defaults to rc figure.dpi facecolor=None, # defaults to rc figure.facecolor edgecolor=None, # defaults to rc figure.edgecolor linewidth=1.0, # the default linewidth of the frame frameon=True, ): """ paper size is a w,h tuple in inches DPI is dots per inch """ Artist.__init__(self) # self.set_figure(self) self._axstack = Stack() # maintain the current axes self._axobservers = [] self._seen = {} # axes args we've seen if figsize is None: figsize = rcParams["figure.figsize"] if dpi is None: dpi = rcParams["figure.dpi"] if facecolor is None: facecolor = rcParams["figure.facecolor"] if edgecolor is None: edgecolor = rcParams["figure.edgecolor"] self.dpi = Value(dpi) self.figwidth = Value(figsize[0]) self.figheight = Value(figsize[1]) self.ll = Point(Value(0), Value(0)) self.ur = Point(self.figwidth * self.dpi, self.figheight * self.dpi) self.bbox = Bbox(self.ll, self.ur) self.frameon = frameon self.transFigure = get_bbox_transform(unit_bbox(), self.bbox) self.figurePatch = Rectangle( xy=(0, 0), width=1, height=1, facecolor=facecolor, edgecolor=edgecolor, linewidth=linewidth ) self._set_artist_props(self.figurePatch) self._hold = rcParams["axes.hold"] self.canvas = None self.clf()
def __init__(self, figsize = None, # defaults to rc figure.figsize dpi = None, # defaults to rc figure.dpi facecolor = None, # defaults to rc figure.facecolor edgecolor = None, # defaults to rc figure.edgecolor linewidth = 1.0, # the default linewidth of the frame frameon = True, ): """ paper size is a w,h tuple in inches DPI is dots per inch """ Artist.__init__(self) #self.set_figure(self) if figsize is None : figsize = rcParams['figure.figsize'] if dpi is None : dpi = rcParams['figure.dpi'] if facecolor is None: facecolor = rcParams['figure.facecolor'] if edgecolor is None: edgecolor = rcParams['figure.edgecolor'] self.dpi = Value(dpi) self.figwidth = Value(figsize[0]) self.figheight = Value(figsize[1]) self.ll = Point( Value(0), Value(0) ) self.ur = Point( self.figwidth*self.dpi, self.figheight*self.dpi ) self.bbox = Bbox(self.ll, self.ur) self.frameon = frameon self.transFigure = get_bbox_transform( unit_bbox(), self.bbox) self.figurePatch = Rectangle( xy=(0,0), width=1, height=1, facecolor=facecolor, edgecolor=edgecolor, linewidth=linewidth, ) self._set_artist_props(self.figurePatch) self._hold = rcParams['axes.hold'] self.clf()
def new_axes(self, ax): self.ax = ax if self.canvas is not ax.figure.canvas: self.disconnect_events() self.canvas = ax.figure.canvas self.connect_event("motion_notify_event", self.onmove) self.connect_event("button_press_event", self.press) self.connect_event("button_release_event", self.release) self.connect_event("draw_event", self.update_background) if self.direction == "horizontal": trans = blended_transform_factory(self.ax.transData, self.ax.transAxes) w, h = 0, 1 else: trans = blended_transform_factory(self.ax.transAxes, self.ax.transData) w, h = 1, 0 self.rect = Rectangle((0, 0), w, h, transform=trans, visible=False, **self.rectprops) if not self.useblit: self.ax.add_patch(self.rect)
def __init__(self, parent, handles, labels, loc, isaxes=True): Artist.__init__(self) if is_string_like(loc) and not self.codes.has_key(loc): verbose.report_error( "Unrecognized location %s. Falling back on upper right; valid locations are\n%s\t" % (loc, "\n\t".join(self.codes.keys())) ) if is_string_like(loc): loc = self.codes.get(loc, 1) if isaxes: # parent is an Axes self.set_figure(parent.figure) else: # parent is a Figure self.set_figure(parent) self.parent = parent self.set_transform(get_bbox_transform(unit_bbox(), parent.bbox)) self._loc = loc # make a trial box in the middle of the axes. relocate it # based on it's bbox left, upper = 0.5, 0.5 if self.NUMPOINTS == 1: self._xdata = array([left + self.HANDLELEN * 0.5]) else: self._xdata = linspace(left, left + self.HANDLELEN, self.NUMPOINTS) textleft = left + self.HANDLELEN + self.HANDLETEXTSEP self.texts = self._get_texts(labels, textleft, upper) self.handles = self._get_handles(handles, self.texts) left, top = self.texts[-1].get_position() HEIGHT = self._approx_text_height() bottom = top - HEIGHT left -= self.HANDLELEN + self.HANDLETEXTSEP + self.PAD self.legendPatch = Rectangle( xy=(left, bottom), width=0.5, height=HEIGHT * len(self.texts), facecolor="w", edgecolor="k" ) self._set_artist_props(self.legendPatch) self._drawFrame = True
class RectangleSelector: """ Select a min/max range of the x axes for a matplotlib Axes Example usage: from matplotlib.widgets import RectangleSelector from pylab import * def onselect(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 def toggle_selector(event): print ' Key pressed.' if event.key in ['Q', 'q'] and toggle_selector.RS.active: print ' RectangleSelector deactivated.' toggle_selector.RS.set_active(False) if event.key in ['A', 'a'] and not toggle_selector.RS.active: print ' RectangleSelector activated.' toggle_selector.RS.set_active(True) x = arange(100)/(99.0) y = sin(x) fig = figure ax = subplot(111) ax.plot(x,y) toggle_selector.RS = RectangleSelector(ax, onselect, drawtype='line') connect('key_press_event', toggle_selector) show() """ def __init__(self, ax, onselect, drawtype='box', minspanx=None, minspany=None, useblit=False, lineprops=None, rectprops=None): """ Create a selector in ax. When a selection is made, clear the span and call onselect with onselect(pos_1, pos_2) and clear the drawn box/line. There pos_i are arrays of length 2 containing the x- and y-coordinate. If minspanx is not None then events smaller than minspanx in x direction are ignored(it's the same for y). The rect is drawn with rectprops; default rectprops = dict(facecolor='red', edgecolor = 'black', alpha=0.5, fill=False) The line is drawn with lineprops; default lineprops = dict(color='black', linestyle='-', linewidth = 2, alpha=0.5) Use type if you want the mouse to draw a line, a box or nothing between click and actual position ny setting drawtype = 'line', drawtype='box' or drawtype = 'none'. """ self.ax = ax self.visible = True 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.active = True # for activation / deactivation self.to_draw = None self.background = None if drawtype == 'none': drawtype = 'line' # draw a line but make it self.visible = False # invisible if drawtype == 'box': if rectprops is None: rectprops = dict(facecolor='white', edgecolor='black', alpha=0.5, fill=False) self.rectprops = rectprops self.to_draw = Rectangle((0, 0), 0, 1, visible=False, **self.rectprops) self.ax.add_patch(self.to_draw) if drawtype == 'line': if lineprops is None: lineprops = dict(color='black', linestyle='-', linewidth=2, alpha=0.5) self.lineprops = lineprops self.to_draw = Line2D([0, 0], [0, 0], visible=False, **self.lineprops) self.ax.add_line(self.to_draw) self.onselect = onselect self.useblit = useblit self.minspanx = minspanx self.minspany = minspany self.drawtype = drawtype # will save the data (position at mouseclick) self.eventpress = None # will save the data (pos. at mouserelease) self.eventrelease = None 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 RectangleSelector is not active : if not self.active: return True # If canvas was locked if not self.canvas.widgetlock.available(self): return True # 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.to_draw.set_visible(self.visible) self.eventpress = event return False def release(self, event): 'on button release event' if self.eventpress is None or self.ignore(event): return # make the box/line invisible again self.to_draw.set_visible(False) self.canvas.draw() # release coordinates, button, ... self.eventrelease = event xmin, ymin = self.eventpress.xdata, self.eventpress.ydata xmax, ymax = self.eventrelease.xdata, self.eventrelease.ydata # calculate dimensions of box or line get values in the right # order 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 if (self.drawtype == 'box') and (xproblems or yproblems): """Box to small""" # check if drawed distance (if it exists) is return # not to small in neither x nor y-direction if (self.drawtype == 'line') and (xproblems and yproblems): """Line to small""" # check if drawed distance (if it exists) is return # not to small in neither x nor y-direction self.onselect(self.eventpress, self.eventrelease) # call desired function self.eventpress = None # reset the variables to their self.eventrelease = None # inital values return False 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() return False def onmove(self, event): 'on motion notify event if box/line is wanted' if self.eventpress is None or self.ignore(event): return x, y = event.xdata, event.ydata # actual position (with # (button still pressed) if self.drawtype == 'box': 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.xy[0] = minx # set lower left of box self.to_draw.xy[1] = miny self.to_draw.set_width(maxx - minx) # set width and height of box self.to_draw.set_height(maxy - miny) self.update() return False if self.drawtype == 'line': self.to_draw.set_data([self.eventpress.xdata, x], [self.eventpress.ydata, y]) self.update() return False def set_active(self, active): """ Use this to activate / deactivate the RectangleSelector from your program with an boolean variable 'active'. """ self.active = active def get_active(self): """ to get status of active mode (boolean variable)""" return self.active
def _get_handles(self, handles, texts): HEIGHT = self._approx_text_height() ret = [] # the returned legend lines for handle, label in zip(handles, texts): x, y = label.get_position() x -= self.handlelen + self.handletextsep if isinstance(handle, Line2D): ydata = (y-HEIGHT/2)*ones(self._xdata.shape, Float) legline = Line2D(self._xdata, ydata) legline.update_from(handle) self._set_artist_props(legline) # after update legline.set_clip_box(None) legline.set_markersize(self.markerscale*legline.get_markersize()) ret.append(legline) elif isinstance(handle, Patch): p = Rectangle(xy=(min(self._xdata), y-3/4*HEIGHT), width = self.handlelen, height=HEIGHT/2, ) p.update_from(handle) self._set_artist_props(p) p.set_clip_box(None) ret.append(p) elif isinstance(handle, LineCollection): ydata = (y-HEIGHT/2)*ones(self._xdata.shape, Float) legline = Line2D(self._xdata, ydata) self._set_artist_props(legline) legline.set_clip_box(None) lw = handle.get_linewidth()[0] dashes = handle.get_dashes() color = handle.get_colors()[0] legline.set_color(color) legline.set_linewidth(lw) legline.set_dashes(dashes) ret.append(legline) elif isinstance(handle, RegularPolyCollection): p = Rectangle(xy=(min(self._xdata), y-3/4*HEIGHT), width = self.handlelen, height=HEIGHT/2, ) p.set_facecolor(handle._facecolors[0]) if handle._edgecolors != 'None': p.set_edgecolor(handle._edgecolors[0]) self._set_artist_props(p) p.set_clip_box(None) ret.append(p) else: ret.append(None) return ret
class Figure(Artist): def __init__(self, figsize = None, # defaults to rc figure.figsize dpi = None, # defaults to rc figure.dpi facecolor = None, # defaults to rc figure.facecolor edgecolor = None, # defaults to rc figure.edgecolor linewidth = 1.0, # the default linewidth of the frame frameon = True, ): """ paper size is a w,h tuple in inches DPI is dots per inch """ Artist.__init__(self) #self.set_figure(self) if figsize is None : figsize = rcParams['figure.figsize'] if dpi is None : dpi = rcParams['figure.dpi'] if facecolor is None: facecolor = rcParams['figure.facecolor'] if edgecolor is None: edgecolor = rcParams['figure.edgecolor'] self.dpi = Value(dpi) self.figwidth = Value(figsize[0]) self.figheight = Value(figsize[1]) self.ll = Point( Value(0), Value(0) ) self.ur = Point( self.figwidth*self.dpi, self.figheight*self.dpi ) self.bbox = Bbox(self.ll, self.ur) self.frameon = frameon self.transFigure = get_bbox_transform( unit_bbox(), self.bbox) self.figurePatch = Rectangle( xy=(0,0), width=1, height=1, facecolor=facecolor, edgecolor=edgecolor, linewidth=linewidth, ) self._set_artist_props(self.figurePatch) self._hold = rcParams['axes.hold'] self.clf() def hold(self, b=None): """ Set the hold state. If hold is None (default), toggle the hold state. Else set the hold state to boolean value b. Eg hold() # toggle hold hold(True) # hold is on hold(False) # hold is off """ if b is None: self._hold = not self._hold else: self._hold = b def figimage(self, X, xo=0, yo=0, alpha=1.0, norm=None, cmap=None, vmin=None, vmax=None, origin=None): """\ FIGIMAGE(X) # add non-resampled array to figure FIGIMAGE(X, xo, yo) # with pixel offsets FIGIMAGE(X, **kwargs) # control interpolation ,scaling, etc Add a nonresampled figure to the figure from array X. xo and yo are offsets in pixels X must be a float array If X is MxN, assume luminance (grayscale) If X is MxNx3, assume RGB If X is MxNx4, assume RGBA The following kwargs are allowed: * cmap is a cm colormap instance, eg cm.jet. If None, default to the rc image.cmap valuex * norm is a matplotlib.colors.normalize instance; default is normalization(). This scales luminance -> 0-1 * vmin and vmax are used to scale a luminance image to 0-1. If either is None, the min and max of the luminance values will be used. Note if you pass a norm instance, the settings for vmin and vmax will be ignored. * alpha = 1.0 : the alpha blending value * origin is either 'upper' or 'lower', which indicates where the [0,0] index of the array is in the upper left or lower left corner of the axes. Defaults to the rc image.origin value This complements the axes image which will be resampled to fit the current axes. If you want a resampled image to fill the entire figure, you can define an Axes with size [0,1,0,1]. A image.FigureImage instance is returned. """ if not self._hold: self.clf() im = FigureImage(self, cmap, norm, xo, yo, origin) im.set_array(X) im.set_alpha(alpha) if norm is None: im.set_clim(vmin, vmax) self.images.append(im ) return im def set_figsize_inches(self, w, h): 'set the figure size in inches' self.figwidth.set(w) self.figheight.set(h) def get_size_inches(self): return self.figwidth.get(), self.figheight.get() def get_edgecolor(self): 'Get the edge color of the Figure rectangle' # return self.figurePatch.get_edgecolor() def get_facecolor(self): 'Get the face color of the Figure rectangle' return self.figurePatch.get_facecolor() def set_edgecolor(self, color): 'Set the edge color of the Figure rectangle' self.figurePatch.set_edgecolor(color) def set_facecolor(self, color): 'Set the face color of the Figure rectangle' self.figurePatch.set_facecolor(color) def add_axis(self, *args, **kwargs): raise SystemExit("""\ matplotlib changed its axes creation API in 0.54. Please see http://matplotlib.sourceforge.net/API_CHANGES for instructions on how to port your code. """) def add_axes(self, rect, axisbg=None, frameon=True, **kwargs): """ Add an a axes with axes rect [left, bottom, width, height] where all quantities are in fractions of figure width and height. The Axes instance will be returned """ if axisbg is None: axisbg=rcParams['axes.facecolor'] ispolar = kwargs.get('polar', False) if ispolar: a = PolarAxes(self, rect, axisbg, frameon) else: a = Axes(self, rect, axisbg, frameon) self.axes.append(a) return a def add_subplot(self, *args, **kwargs): """ Add an a subplot, eg add_subplot(111) or add_subplot(212, axisbg='r') The Axes instance will be returned """ ispolar = kwargs.get('polar', False) dict_delall(kwargs, ('polar', ) ) if ispolar: a = PolarSubplot(self, *args, **kwargs) else: a = Subplot(self, *args, **kwargs) self.axes.append(a) return a def clf(self): """ Clear the figure """ self.axes = [] self.lines = [] self.patches = [] self.texts=[] self.images = [] self.legends = [] def clear(self): """ Clear the figure """ self.clf() def draw(self, renderer): """ Render the figure using RendererGD instance renderer """ # draw the figure bounding box, perhaps none for white figure renderer.open_group('figure') self.transFigure.freeze() # eval the lazy objects if self.frameon: self.figurePatch.draw(renderer) for p in self.patches: p.draw(renderer) for l in self.lines: l.draw(renderer) if len(self.images)==1: im = self.images[0] im.draw(renderer) elif len(self.images)>1: # make a composite image blending alpha # list of (_image.Image, ox, oy) if not allequal([im.origin for im in self.images]): raise ValueError('Composite images with different origins not supported') else: origin = self.images[0].origin ims = [(im.make_image(), im.ox, im.oy) for im in self.images] im = _image.from_images(self.bbox.height(), self.bbox.width(), ims) im.is_grayscale = False l, b, w, h = self.bbox.get_bounds() renderer.draw_image(0, 0, im, origin, self.bbox) # render the axes for a in self.axes: a.draw(renderer) # render the figure text for t in self.texts: t.draw(renderer) for legend in self.legends: legend.draw(renderer) self.transFigure.thaw() # release the lazy objects renderer.close_group('figure') def get_axes(self): return self.axes def legend(self, handles, labels, loc, **kwargs): """ Place a legend in the figure. Labels are a sequence of strings, handles is a sequence of line or patch instances, and loc can be a string or an integer specifying the legend location USAGE: legend( (line1, line2, line3), ('label1', 'label2', 'label3'), 'upper right') The LOC location codes are 'best' : 0, (currently not supported, defaults to upper right) 'upper right' : 1, (default) 'upper left' : 2, 'lower left' : 3, 'lower right' : 4, 'right' : 5, 'center left' : 6, 'center right' : 7, 'lower center' : 8, 'upper center' : 9, 'center' : 10, The legend instance is returned """ handles = flatten(handles) l = Legend(self, handles, labels, loc, isaxes=False, **kwargs) self._set_artist_props(l) self.legends.append(l) return l def text(self, x, y, s, *args, **kwargs): """ Add text to figure at location x,y (relative 0-1 coords) See the help for Axis text for the meaning of the other arguments """ override = _process_text_args({}, *args, **kwargs) t = Text( x=x, y=y, text=s, ) t.update(override) self._set_artist_props(t) self.texts.append(t) return t def _set_artist_props(self, a): if a!= self: a.set_figure(self) a.set_transform(self.transFigure) def get_width_height(self): 'return the figure width and height in pixels' w = self.bbox.width() h = self.bbox.height() return w, h
def __init__(self, parent, handles, labels, loc, isaxes=True, numpoints = 4, # the number of points in the legend line prop = FontProperties(size='smaller'), pad = 0.2, # the fractional whitespace inside the legend border markerscale = 0.6, # the relative size of legend markers vs. original # the following dimensions are in axes coords labelsep = 0.005, # the vertical space between the legend entries handlelen = 0.05, # the length of the legend lines handletextsep = 0.02, # the space between the legend line and legend text axespad = 0.02, # the border between the axes and legend edge shadow=False, ): """ parent # the artist that contains the legend handles # a list of artists (lines, patches) to add to the legend labels # a list of strings to label the legend loc # a location code isaxes=True # whether this is an axes legend numpoints = 4 # the number of points in the legend line fontprop = FontProperties('smaller') # the font property pad = 0.2 # the fractional whitespace inside the legend border markerscale = 0.6 # the relative size of legend markers vs. original shadow # if True, draw a shadow behind legend The following dimensions are in axes coords labelsep = 0.005 # the vertical space between the legend entries handlelen = 0.05 # the length of the legend lines handletextsep = 0.02 # the space between the legend line and legend text axespad = 0.02 # the border between the axes and legend edge """ Artist.__init__(self) if is_string_like(loc) and not self.codes.has_key(loc): verbose.report_error('Unrecognized location %s. Falling back on upper right; valid locations are\n%s\t' %(loc, '\n\t'.join(self.codes.keys()))) if is_string_like(loc): loc = self.codes.get(loc, 1) self.numpoints = numpoints self.prop = prop self.fontsize = prop.get_size_in_points() self.pad = pad self.markerscale = markerscale self.labelsep = labelsep self.handlelen = handlelen self.handletextsep = handletextsep self.axespad = axespad self.shadow = shadow if isaxes: # parent is an Axes self.set_figure(parent.figure) else: # parent is a Figure self.set_figure(parent) self.parent = parent self.set_transform( get_bbox_transform( unit_bbox(), parent.bbox) ) self._loc = loc # make a trial box in the middle of the axes. relocate it # based on it's bbox left, upper = 0.5, 0.5 if self.numpoints == 1: self._xdata = array([left + self.handlelen*0.5]) else: self._xdata = linspace(left, left + self.handlelen, self.numpoints) textleft = left+ self.handlelen+self.handletextsep self.texts = self._get_texts(labels, textleft, upper) self.handles = self._get_handles(handles, self.texts) left, top = self.texts[-1].get_position() HEIGHT = self._approx_text_height() bottom = top-HEIGHT left -= self.handlelen + self.handletextsep + self.pad self.legendPatch = Rectangle( xy=(left, bottom), width=0.5, height=HEIGHT*len(self.texts), facecolor='w', edgecolor='k', ) self._set_artist_props(self.legendPatch) self._drawFrame = True
def set_transform(self, trans): Rectangle.set_transform(self, trans)
class SpanSelector: """ Select a min/max range of the x or y axes for a matplotlib Axes Example usage: ax = subplot(111) ax.plot(x,y) def onselect(vmin, vmax): print vmin, vmax span = SpanSelector(ax, onselect, 'horizontal') onmove_callback is an optional callback that will be called on mouse move with the span range """ def __init__(self, ax, onselect, direction, minspan=None, useblit=False, rectprops=None, onmove_callback=None): """ Create a span selector in ax. When a selection is made, clear the span and call onselect with onselect(vmin, vmax) and clear the span. direction must be 'horizontal' or 'vertical' If minspan is not None, ignore events smaller than minspan The span rect is drawn with rectprops; default rectprops = dict(facecolor='red', alpha=0.5) set the visible attribute to False if you want to turn off the functionality of the span selector """ if rectprops is None: rectprops = dict(facecolor='red', alpha=0.5) assert direction in [ 'horizontal', 'vertical' ], 'Must choose horizontal or vertical for direction' self.direction = direction self.ax = ax self.visible = True 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.rect = None self.background = None self.rectprops = rectprops self.onselect = onselect self.onmove_callback = onmove_callback self.useblit = useblit self.minspan = minspan # Needed when dragging out of axes self.buttonDown = False self.prev = (0, 0) if self.direction == 'horizontal': trans = blended_transform_factory(self.ax.transData, self.ax.transAxes) w, h = 0, 1 else: trans = blended_transform_factory(self.ax.transAxes, self.ax.transData) w, h = 1, 0 self.rect = Rectangle((0, 0), w, h, transform=trans, visible=False, **self.rectprops) if not self.useblit: self.ax.add_patch(self.rect) self.pressv = None 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' return event.inaxes != self.ax or not self.visible or event.button != 1 def press(self, event): 'on button press event' if self.ignore(event): return self.buttonDown = True self.rect.set_visible(self.visible) if self.direction == 'horizontal': self.pressv = event.xdata else: self.pressv = event.ydata return False def release(self, event): 'on button release event' if self.pressv is None or (self.ignore(event) and not self.buttonDown): return self.buttonDown = False self.rect.set_visible(False) self.canvas.draw() vmin = self.pressv if self.direction == 'horizontal': vmax = event.xdata or self.prev[0] else: vmax = event.ydata or self.prev[1] if vmin > vmax: vmin, vmax = vmax, vmin span = vmax - vmin if self.minspan is not None and span < self.minspan: return self.onselect(vmin, vmax) self.pressv = None return False 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.rect) self.canvas.blit(self.ax.bbox) else: self.canvas.draw_idle() return False def onmove(self, event): 'on motion notify event' if self.pressv is None or self.ignore(event): return x, y = event.xdata, event.ydata self.prev = x, y if self.direction == 'horizontal': v = x else: v = y minv, maxv = v, self.pressv if minv > maxv: minv, maxv = maxv, minv if self.direction == 'horizontal': self.rect.xy[0] = minv self.rect.set_width(maxv - minv) else: self.rect.xy[1] = minv self.rect.set_height(maxv - minv) if self.onmove_callback is not None: vmin = self.pressv if self.direction == 'horizontal': vmax = event.xdata or self.prev[0] else: vmax = event.ydata or self.prev[1] if vmin > vmax: vmin, vmax = vmax, vmin self.onmove_callback(vmin, vmax) self.update() return False
class Legend(Artist): """ Place a legend on the axes at location loc. Labels are a sequence of strings and loc can be a string or an integer specifying the legend location The location codes are 'best' : 0, (only implemented for axis legends) 'upper right' : 1, 'upper left' : 2, 'lower left' : 3, 'lower right' : 4, 'right' : 5, 'center left' : 6, 'center right' : 7, 'lower center' : 8, 'upper center' : 9, 'center' : 10, Return value is a sequence of text, line instances that make up the legend """ codes = {'best' : 0, # only implemented for axis legends 'upper right' : 1, 'upper left' : 2, 'lower left' : 3, 'lower right' : 4, 'right' : 5, 'center left' : 6, 'center right' : 7, 'lower center' : 8, 'upper center' : 9, 'center' : 10, } zorder = 5 def __str__(self): return "Legend" def __init__(self, parent, handles, labels, loc = None, numpoints = None, # the number of points in the legend line prop = None, pad = None, # the fractional whitespace inside the legend border markerscale = None, # the relative size of legend markers vs. original # the following dimensions are in axes coords labelsep = None, # the vertical space between the legend entries handlelen = None, # the length of the legend lines handletextsep = None, # the space between the legend line and legend text axespad = None, # the border between the axes and legend edge shadow = None ): """ parent # the artist that contains the legend handles # a list of artists (lines, patches) to add to the legend labels # a list of strings to label the legend loc # a location code numpoints = 4 # the number of points in the legend line prop = FontProperties(size='smaller') # the font property pad = 0.2 # the fractional whitespace inside the legend border markerscale = 0.6 # the relative size of legend markers vs. original shadow # if True, draw a shadow behind legend The following dimensions are in axes coords labelsep = 0.005 # the vertical space between the legend entries handlelen = 0.05 # the length of the legend lines handletextsep = 0.02 # the space between the legend line and legend text axespad = 0.02 # the border between the axes and legend edge """ from axes import Axes # local import only to avoid circularity from figure import Figure # local import only to avoid circularity Artist.__init__(self) proplist=[numpoints, pad, markerscale, labelsep, handlelen, handletextsep, axespad, shadow] propnames=['numpoints', 'pad', 'markerscale', 'labelsep', 'handlelen', 'handletextsep', 'axespad', 'shadow'] for name, value in safezip(propnames,proplist): if value is None: value=rcParams["legend."+name] setattr(self,name,value) if self.numpoints <= 0: raise ValueError("numpoints must be >= 0; it was %d"% numpoints) if prop is None: self.prop=FontProperties(size=rcParams["legend.fontsize"]) else: self.prop=prop self.fontsize = self.prop.get_size_in_points() if isinstance(parent,Axes): self.isaxes = True self.set_figure(parent.figure) elif isinstance(parent,Figure): self.isaxes = False self.set_figure(parent) else: raise TypeError("Legend needs either Axes or Figure as parent") self.parent = parent self._offsetTransform = Affine2D() self._parentTransform = BboxTransformTo(parent.bbox) Artist.set_transform(self, self._offsetTransform + self._parentTransform) if loc is None: loc = rcParams["legend.loc"] if not self.isaxes and loc in [0,'best']: loc = 'upper right' if is_string_like(loc): if not self.codes.has_key(loc): if self.isaxes: warnings.warn('Unrecognized location "%s". Falling back on "best"; ' 'valid locations are\n\t%s\n' % (loc, '\n\t'.join(self.codes.keys()))) loc = 0 else: warnings.warn('Unrecognized location "%s". Falling back on "upper right"; ' 'valid locations are\n\t%s\n' % (loc, '\n\t'.join(self.codes.keys()))) loc = 1 else: loc = self.codes[loc] if not self.isaxes and loc == 0: warnings.warn('Automatic legend placement (loc="best") not implemented for figure legend. ' 'Falling back on "upper right".') loc = 1 self._loc = loc self.legendPatch = Rectangle( xy=(0.0, 0.0), width=0.5, height=0.5, facecolor='w', edgecolor='k', ) self._set_artist_props(self.legendPatch) # make a trial box in the middle of the axes. relocate it # based on it's bbox left, top = 0.5, 0.5 textleft = left+ self.handlelen+self.handletextsep self.texts = self._get_texts(labels, textleft, top) self.legendHandles = self._get_handles(handles, self.texts) self._drawFrame = True def _set_artist_props(self, a): a.set_figure(self.figure) a.set_transform(self.get_transform()) def _approx_text_height(self): return self.fontsize/72.0*self.figure.dpi/self.parent.bbox.height def draw(self, renderer): if not self.get_visible(): return renderer.open_group('legend') self._update_positions(renderer) if self._drawFrame: if self.shadow: shadow = Shadow(self.legendPatch, -0.005, -0.005) shadow.draw(renderer) self.legendPatch.draw(renderer) if not len(self.legendHandles) and not len(self.texts): return for h in self.legendHandles: if h is not None: h.draw(renderer) if hasattr(h, '_legmarker'): h._legmarker.draw(renderer) if 0: bbox_artist(h, renderer) for t in self.texts: if 0: bbox_artist(t, renderer) t.draw(renderer) renderer.close_group('legend') #draw_bbox(self.save, renderer, 'g') #draw_bbox(self.ibox, renderer, 'r', self.get_transform()) def _get_handle_text_bbox(self, renderer): 'Get a bbox for the text and lines in axes coords' bboxesText = [t.get_window_extent(renderer) for t in self.texts] bboxesHandles = [h.get_window_extent(renderer) for h in self.legendHandles if h is not None] bboxesAll = bboxesText bboxesAll.extend(bboxesHandles) bbox = Bbox.union(bboxesAll) self.save = bbox ibox = bbox.inverse_transformed(self.get_transform()) self.ibox = ibox return ibox def _get_handles(self, handles, texts): handles = list(handles) texts = list(texts) HEIGHT = self._approx_text_height() left = 0.5 ret = [] # the returned legend lines # we need to pad the text with empties for the numpoints=1 # centered marker proxy for handle, label in safezip(handles, texts): if self.numpoints > 1: xdata = np.linspace(left, left + self.handlelen, self.numpoints) xdata_marker = xdata elif self.numpoints == 1: xdata = np.linspace(left, left + self.handlelen, 2) xdata_marker = [left + 0.5*self.handlelen] x, y = label.get_position() x -= self.handlelen + self.handletextsep if isinstance(handle, Line2D): ydata = (y-HEIGHT/2)*np.ones(xdata.shape, float) legline = Line2D(xdata, ydata) legline.update_from(handle) self._set_artist_props(legline) # after update legline.set_clip_box(None) legline.set_clip_path(None) ret.append(legline) legline.set_marker('None') legline_marker = Line2D(xdata_marker, ydata[:len(xdata_marker)]) legline_marker.update_from(handle) legline_marker.set_linestyle('None') self._set_artist_props(legline_marker) # we don't want to add this to the return list because # the texts and handles are assumed to be in one-to-one # correpondence. legline._legmarker = legline_marker elif isinstance(handle, Patch): p = Rectangle(xy=(min(xdata), y-3/4*HEIGHT), width = self.handlelen, height=HEIGHT/2, ) p.update_from(handle) self._set_artist_props(p) p.set_clip_box(None) p.set_clip_path(None) ret.append(p) elif isinstance(handle, LineCollection): ydata = (y-HEIGHT/2)*np.ones(xdata.shape, float) legline = Line2D(xdata, ydata) self._set_artist_props(legline) legline.set_clip_box(None) legline.set_clip_path(None) lw = handle.get_linewidth()[0] dashes = handle.get_dashes()[0] color = handle.get_colors()[0] legline.set_color(color) legline.set_linewidth(lw) legline.set_dashes(dashes) ret.append(legline) elif isinstance(handle, RegularPolyCollection): if self.numpoints == 1: xdata = np.array([left]) p = Rectangle(xy=(min(xdata), y-3/4*HEIGHT), width = self.handlelen, height=HEIGHT/2, ) p.set_facecolor(handle._facecolors[0]) if handle._edgecolors != 'none' and len(handle._edgecolors): p.set_edgecolor(handle._edgecolors[0]) self._set_artist_props(p) p.set_clip_box(None) p.set_clip_path(None) ret.append(p) else: ret.append(None) return ret def _auto_legend_data(self): """ Returns list of vertices and extents covered by the plot. Returns a two long list. First element is a list of (x, y) vertices (in axes-coordinates) covered by all the lines and line collections, in the legend's handles. Second element is a list of bounding boxes for all the patches in the legend's handles. """ assert self.isaxes # should always hold because function is only called internally ax = self.parent vertices = [] bboxes = [] lines = [] inverse_transform = ax.transAxes.inverted() for handle in ax.lines: assert isinstance(handle, Line2D) path = handle.get_path() trans = handle.get_transform() tpath = trans.transform_path(path) apath = inverse_transform.transform_path(tpath) lines.append(apath) for handle in ax.patches: assert isinstance(handle, Patch) if isinstance(handle, Rectangle): transform = handle.get_data_transform() + inverse_transform bboxes.append(handle.get_bbox().transformed(transform)) else: transform = handle.get_transform() + inverse_transform bboxes.append(handle.get_path().get_extents(transform)) return [vertices, bboxes, lines] def draw_frame(self, b): 'b is a boolean. Set draw frame to b' self._drawFrame = b def get_frame(self): 'return the Rectangle instance used to frame the legend' return self.legendPatch def get_lines(self): 'return a list of lines.Line2D instances in the legend' return [h for h in self.legendHandles if isinstance(h, Line2D)] def get_patches(self): 'return a list of patch instances in the legend' return silent_list('Patch', [h for h in self.legendHandles if isinstance(h, Patch)]) def get_texts(self): 'return a list of text.Text instance in the legend' return silent_list('Text', self.texts) def _get_texts(self, labels, left, upper): # height in axes coords HEIGHT = self._approx_text_height() pos = upper x = left ret = [] # the returned list of text instances for l in labels: text = Text( x=x, y=pos, text=l, fontproperties=self.prop, verticalalignment='top', horizontalalignment='left' ) self._set_artist_props(text) ret.append(text) pos -= HEIGHT return ret def get_window_extent(self): return self.legendPatch.get_window_extent() def _offset(self, ox, oy): 'Move all the artists by ox,oy (axes coords)' self._offsetTransform.clear().translate(ox, oy) def _find_best_position(self, width, height, consider=None): """Determine the best location to place the legend. `consider` is a list of (x, y) pairs to consider as a potential lower-left corner of the legend. All are axes coords. """ assert self.isaxes # should always hold because function is only called internally verts, bboxes, lines = self._auto_legend_data() consider = [self._loc_to_axes_coords(x, width, height) for x in range(1, len(self.codes))] tx, ty = self.legendPatch.get_x(), self.legendPatch.get_y() candidates = [] for l, b in consider: legendBox = Bbox.from_bounds(l, b, width, height) badness = 0 badness = legendBox.count_contains(verts) badness += legendBox.count_overlaps(bboxes) for line in lines: if line.intersects_bbox(legendBox): badness += 1 ox, oy = l-tx, b-ty if badness == 0: return ox, oy candidates.append((badness, (ox, oy))) # rather than use min() or list.sort(), do this so that we are assured # that in the case of two equal badnesses, the one first considered is # returned. minCandidate = candidates[0] for candidate in candidates: if candidate[0] < minCandidate[0]: minCandidate = candidate ox, oy = minCandidate[1] return ox, oy def _loc_to_axes_coords(self, loc, width, height): """Convert a location code to axes coordinates. - loc: a location code in range(1, 11). This corresponds to the possible values for self._loc, excluding "best". - width, height: the final size of the legend, axes units. """ assert loc in range(1,11) # called only internally BEST, UR, UL, LL, LR, R, CL, CR, LC, UC, C = range(11) if loc in (UL, LL, CL): # left x = self.axespad elif loc in (UR, LR, CR, R): # right x = 1.0 - (width + self.axespad) elif loc in (LC, UC, C): # center x x = (0.5 - width/2.0) if loc in (UR, UL, UC): # upper y = 1.0 - (height + self.axespad) elif loc in (LL, LR, LC): # lower y = self.axespad elif loc in (CL, CR, C, R): # center y y = (0.5 - height/2.0) return x,y def _update_positions(self, renderer): # called from renderer to allow more precise estimates of # widths and heights with get_window_extent if not len(self.legendHandles) and not len(self.texts): return def get_tbounds(text): #get text bounds in axes coords bbox = text.get_window_extent(renderer) bboxa = bbox.inverse_transformed(self.get_transform()) return bboxa.bounds hpos = [] for t, tabove in safezip(self.texts[1:], self.texts[:-1]): x,y = t.get_position() l,b,w,h = get_tbounds(tabove) b -= self.labelsep h += 2*self.labelsep hpos.append( (b,h) ) t.set_position( (x, b-0.1*h) ) # now do the same for last line l,b,w,h = get_tbounds(self.texts[-1]) b -= self.labelsep h += 2*self.labelsep hpos.append( (b,h) ) for handle, tup in safezip(self.legendHandles, hpos): y,h = tup if isinstance(handle, Line2D): ydata = y*np.ones(handle.get_xdata().shape, float) handle.set_ydata(ydata+h/2.) handle._legmarker.set_ydata(ydata+h/2.) elif isinstance(handle, Rectangle): handle.set_y(y+1/4*h) handle.set_height(h/2) # Set the data for the legend patch bbox = self._get_handle_text_bbox(renderer) bbox = bbox.expanded(1 + self.pad, 1 + self.pad) l, b, w, h = bbox.bounds self.legendPatch.set_bounds(l, b, w, h) ox, oy = 0, 0 # center if iterable(self._loc) and len(self._loc)==2: xo = self.legendPatch.get_x() yo = self.legendPatch.get_y() x, y = self._loc ox, oy = x-xo, y-yo elif self._loc == 0: # "best" ox, oy = self._find_best_position(w, h) else: x, y = self._loc_to_axes_coords(self._loc, w, h) ox, oy = x-l, y-b self._offset(ox, oy)
def _get_handles(self, handles, texts): handles = list(handles) texts = list(texts) HEIGHT = self._approx_text_height() left = 0.5 ret = [] # the returned legend lines # we need to pad the text with empties for the numpoints=1 # centered marker proxy for handle, label in safezip(handles, texts): if self.numpoints > 1: xdata = np.linspace(left, left + self.handlelen, self.numpoints) xdata_marker = xdata elif self.numpoints == 1: xdata = np.linspace(left, left + self.handlelen, 2) xdata_marker = [left + 0.5*self.handlelen] x, y = label.get_position() x -= self.handlelen + self.handletextsep if isinstance(handle, Line2D): ydata = (y-HEIGHT/2)*np.ones(xdata.shape, float) legline = Line2D(xdata, ydata) legline.update_from(handle) self._set_artist_props(legline) # after update legline.set_clip_box(None) legline.set_clip_path(None) ret.append(legline) legline.set_marker('None') legline_marker = Line2D(xdata_marker, ydata[:len(xdata_marker)]) legline_marker.update_from(handle) legline_marker.set_linestyle('None') self._set_artist_props(legline_marker) # we don't want to add this to the return list because # the texts and handles are assumed to be in one-to-one # correpondence. legline._legmarker = legline_marker elif isinstance(handle, Patch): p = Rectangle(xy=(min(xdata), y-3/4*HEIGHT), width = self.handlelen, height=HEIGHT/2, ) p.update_from(handle) self._set_artist_props(p) p.set_clip_box(None) p.set_clip_path(None) ret.append(p) elif isinstance(handle, LineCollection): ydata = (y-HEIGHT/2)*np.ones(xdata.shape, float) legline = Line2D(xdata, ydata) self._set_artist_props(legline) legline.set_clip_box(None) legline.set_clip_path(None) lw = handle.get_linewidth()[0] dashes = handle.get_dashes()[0] color = handle.get_colors()[0] legline.set_color(color) legline.set_linewidth(lw) legline.set_dashes(dashes) ret.append(legline) elif isinstance(handle, RegularPolyCollection): if self.numpoints == 1: xdata = np.array([left]) p = Rectangle(xy=(min(xdata), y-3/4*HEIGHT), width = self.handlelen, height=HEIGHT/2, ) p.set_facecolor(handle._facecolors[0]) if handle._edgecolors != 'none' and len(handle._edgecolors): p.set_edgecolor(handle._edgecolors[0]) self._set_artist_props(p) p.set_clip_box(None) p.set_clip_path(None) ret.append(p) else: ret.append(None) return ret
class Legend(Artist): """ Place a legend on the axes at location loc. Labels are a sequence of strings and loc can be a string or an integer specifying the legend location The location codes are 'best' : 0, 'upper right' : 1, (default) 'upper left' : 2, 'lower left' : 3, 'lower right' : 4, 'right' : 5, 'center left' : 6, 'center right' : 7, 'lower center' : 8, 'upper center' : 9, 'center' : 10, Return value is a sequence of text, line instances that make up the legend """ codes = {'best' : 0, 'upper right' : 1, # default 'upper left' : 2, 'lower left' : 3, 'lower right' : 4, 'right' : 5, 'center left' : 6, 'center right' : 7, 'lower center' : 8, 'upper center' : 9, 'center' : 10, } def __init__(self, parent, handles, labels, loc, isaxes=True, numpoints = 4, # the number of points in the legend line prop = FontProperties(size='smaller'), pad = 0.2, # the fractional whitespace inside the legend border markerscale = 0.6, # the relative size of legend markers vs. original # the following dimensions are in axes coords labelsep = 0.005, # the vertical space between the legend entries handlelen = 0.05, # the length of the legend lines handletextsep = 0.02, # the space between the legend line and legend text axespad = 0.02, # the border between the axes and legend edge shadow=False, ): """ parent # the artist that contains the legend handles # a list of artists (lines, patches) to add to the legend labels # a list of strings to label the legend loc # a location code isaxes=True # whether this is an axes legend numpoints = 4 # the number of points in the legend line fontprop = FontProperties(size='smaller') # the font property pad = 0.2 # the fractional whitespace inside the legend border markerscale = 0.6 # the relative size of legend markers vs. original shadow # if True, draw a shadow behind legend The following dimensions are in axes coords labelsep = 0.005 # the vertical space between the legend entries handlelen = 0.05 # the length of the legend lines handletextsep = 0.02 # the space between the legend line and legend text axespad = 0.02 # the border between the axes and legend edge """ Artist.__init__(self) if is_string_like(loc) and not self.codes.has_key(loc): warnings.warn('Unrecognized location %s. Falling back on upper right; valid locations are\n%s\t' %(loc, '\n\t'.join(self.codes.keys()))) if is_string_like(loc): loc = self.codes.get(loc, 1) self.numpoints = numpoints self.prop = prop self.fontsize = prop.get_size_in_points() self.pad = pad self.markerscale = markerscale self.labelsep = labelsep self.handlelen = handlelen self.handletextsep = handletextsep self.axespad = axespad self.shadow = shadow self.isaxes = isaxes if isaxes: # parent is an Axes self.set_figure(parent.figure) else: # parent is a Figure self.set_figure(parent) self.parent = parent self.set_transform( get_bbox_transform( unit_bbox(), parent.bbox) ) self._loc = loc # make a trial box in the middle of the axes. relocate it # based on it's bbox left, upper = 0.5, 0.5 if self.numpoints == 1: self._xdata = array([left + self.handlelen*0.5]) else: self._xdata = linspace(left, left + self.handlelen, self.numpoints) textleft = left+ self.handlelen+self.handletextsep self.texts = self._get_texts(labels, textleft, upper) self.legendHandles = self._get_handles(handles, self.texts) left, top = self.texts[-1].get_position() HEIGHT = self._approx_text_height() bottom = top-HEIGHT left -= self.handlelen + self.handletextsep + self.pad self.legendPatch = Rectangle( xy=(left, bottom), width=0.5, height=HEIGHT*len(self.texts), facecolor='w', edgecolor='k', ) self._set_artist_props(self.legendPatch) self._drawFrame = True def _set_artist_props(self, a): a.set_figure(self.figure) a.set_transform(self._transform) def _approx_text_height(self): return self.fontsize/72.0*self.figure.dpi.get()/self.parent.bbox.height() def draw(self, renderer): if not self.get_visible(): return renderer.open_group('legend') self._update_positions(renderer) if self._drawFrame: if self.shadow: shadow = Shadow(self.legendPatch, -0.005, -0.005) shadow.draw(renderer) self.legendPatch.draw(renderer) for h in self.legendHandles: if h is not None: h.draw(renderer) if 0: bbox_artist(h, renderer) for t in self.texts: if 0: bbox_artist(t, renderer) t.draw(renderer) renderer.close_group('legend') #draw_bbox(self.save, renderer, 'g') #draw_bbox(self.ibox, renderer, 'r', self._transform) def _get_handle_text_bbox(self, renderer): 'Get a bbox for the text and lines in axes coords' bboxesText = [t.get_window_extent(renderer) for t in self.texts] bboxesHandles = [h.get_window_extent(renderer) for h in self.legendHandles if h is not None] bboxesAll = bboxesText bboxesAll.extend(bboxesHandles) bbox = bbox_all(bboxesAll) self.save = bbox ibox = inverse_transform_bbox(self._transform, bbox) self.ibox = ibox return ibox def _get_handles(self, handles, texts): HEIGHT = self._approx_text_height() ret = [] # the returned legend lines for handle, label in zip(handles, texts): x, y = label.get_position() x -= self.handlelen + self.handletextsep if isinstance(handle, Line2D): ydata = (y-HEIGHT/2)*ones(self._xdata.shape, Float) legline = Line2D(self._xdata, ydata) legline.update_from(handle) self._set_artist_props(legline) # after update legline.set_clip_box(None) legline.set_markersize(self.markerscale*legline.get_markersize()) legline.set_data_clipping(False) ret.append(legline) elif isinstance(handle, Patch): p = Rectangle(xy=(min(self._xdata), y-3/4*HEIGHT), width = self.handlelen, height=HEIGHT/2, ) p.update_from(handle) self._set_artist_props(p) p.set_clip_box(None) ret.append(p) elif isinstance(handle, LineCollection): ydata = (y-HEIGHT/2)*ones(self._xdata.shape, Float) legline = Line2D(self._xdata, ydata) self._set_artist_props(legline) legline.set_clip_box(None) lw = handle.get_linewidths()[0] dashes = handle.get_dashes() color = handle.get_colors()[0] legline.set_color(color) legline.set_linewidth(lw) legline.set_dashes(dashes) ret.append(legline) else: ret.append(None) return ret def _auto_legend_data(self): """ Returns list of vertices and extents covered by the plot. Returns a two long list. First element is a list of (x, y) vertices (in axes-coordinates) covered by all the lines and line collections, in the legend's handles. Second element is a list of bounding boxes for all the patches in the legend's handles. """ if not self.isaxes: raise Exception, 'Auto legends not available for figure legends.' def get_handles(ax): handles = ax.lines handles.extend(ax.patches) handles.extend([c for c in ax.collections if isinstance(c, LineCollection)]) return handles ax = self.parent handles = get_handles(ax) vertices = [] bboxes = [] lines = [] inv = ax.transAxes.inverse_xy_tup for handle in handles: if isinstance(handle, Line2D): xdata = handle.get_xdata(valid_only = True) ydata = handle.get_ydata(valid_only = True) trans = handle.get_transform() xt, yt = trans.numerix_x_y(xdata, ydata) # XXX need a special method in transform to do a list of verts averts = [inv(v) for v in zip(xt, yt)] lines.append(averts) elif isinstance(handle, Patch): verts = handle.get_verts() trans = handle.get_transform() tverts = trans.seq_xy_tups(verts) averts = [inv(v) for v in tverts] bbox = unit_bbox() bbox.update(averts, True) bboxes.append(bbox) elif isinstance(handle, LineCollection): hlines = handle.get_lines() trans = handle.get_transform() for line in hlines: tline = trans.seq_xy_tups(line) aline = [inv(v) for v in tline] lines.extend(line) return [vertices, bboxes, lines] def draw_frame(self, b): 'b is a boolean. Set draw frame to b' self._drawFrame = b def get_frame(self): 'return the Rectangle instance used to frame the legend' return self.legendPatch def get_lines(self): 'return a list of lines.Line2D instances in the legend' return [h for h in self.legendHandles if isinstance(h, Line2D)] def get_patches(self): 'return a list of patch instances in the legend' return silent_list('Patch', [h for h in self.legendHandles if isinstance(h, Patch)]) def get_texts(self): 'return a list of text.Text instance in the legend' return silent_list('Text', self.texts) def _get_texts(self, labels, left, upper): # height in axes coords HEIGHT = self._approx_text_height() pos = upper x = left ret = [] # the returned list of text instances for l in labels: text = Text( x=x, y=pos, text=l, fontproperties=self.prop, verticalalignment='top', horizontalalignment='left', ) self._set_artist_props(text) ret.append(text) pos -= HEIGHT return ret def get_window_extent(self): return self.legendPatch.get_window_extent() def _offset(self, ox, oy): 'Move all the artists by ox,oy (axes coords)' for t in self.texts: x,y = t.get_position() t.set_position( (x+ox, y+oy) ) for h in self.legendHandles: if isinstance(h, Line2D): x,y = h.get_xdata(valid_only = True), h.get_ydata(valid_only = True) h.set_data( x+ox, y+oy) elif isinstance(h, Rectangle): h.xy[0] = h.xy[0] + ox h.xy[1] = h.xy[1] + oy x, y = self.legendPatch.get_x(), self.legendPatch.get_y() self.legendPatch.set_x(x+ox) self.legendPatch.set_y(y+oy) def _find_best_position(self, width, height, consider=None): """Determine the best location to place the legend. `consider` is a list of (x, y) pairs to consider as a potential lower-left corner of the legend. All are axes coords. """ verts, bboxes, lines = self._auto_legend_data() consider = [self._loc_to_axes_coords(x, width, height) for x in range(1, len(self.codes))] tx, ty = self.legendPatch.xy candidates = [] for l, b in consider: legendBox = lbwh_to_bbox(l, b, width, height) badness = 0 badness = legendBox.count_contains(verts) ox, oy = l-tx, b-ty for bbox in bboxes: if legendBox.overlaps(bbox): badness += 1 for line in lines: if line_cuts_bbox(line, legendBox): badness += 1 if badness == 0: return ox, oy candidates.append((badness, (ox, oy))) # rather than use min() or list.sort(), do this so that we are assured # that in the case of two equal badnesses, the one first considered is # returned. minCandidate = candidates[0] for candidate in candidates: if candidate[0] < minCandidate[0]: minCandidate = candidate ox, oy = minCandidate[1] return ox, oy def _loc_to_axes_coords(self, loc, width, height): """Convert a location code to axes coordinates. - loc: a location code, which may be a pair of literal axes coords, or in range(1, 11). This coresponds to the possible values for self._loc, excluding "best". - width, height: the final size of the legend, axes units. """ BEST, UR, UL, LL, LR, R, CL, CR, LC, UC, C = range(11) left = self.axespad right = 1.0 - (self.axespad + width) upper = 1.0 - (self.axespad + height) lower = self.axespad centerx = 0.5 - (width/2.0) centery = 0.5 - (height/2.0) if loc == UR: return right, upper if loc == UL: return left, upper if loc == LL: return left, lower if loc == LR: return right, lower if loc == CL: return left, centery if loc in (CR, R): return right, centery if loc == LC: return centerx, lower if loc == UC: return centerx, upper if loc == C: return centerx, centery raise TypeError, "%r isn't an understood type code." % (loc,) def _update_positions(self, renderer): # called from renderer to allow more precise estimates of # widths and heights with get_window_extent def get_tbounds(text): #get text bounds in axes coords bbox = text.get_window_extent(renderer) bboxa = inverse_transform_bbox(self._transform, bbox) return bboxa.get_bounds() hpos = [] for t, tabove in zip(self.texts[1:], self.texts[:-1]): x,y = t.get_position() l,b,w,h = get_tbounds(tabove) b -= self.labelsep h += 2*self.labelsep hpos.append( (b,h) ) t.set_position( (x, b-0.1*h) ) # now do the same for last line l,b,w,h = get_tbounds(self.texts[-1]) b -= self.labelsep h += 2*self.labelsep hpos.append( (b,h) ) for handle, tup in zip(self.legendHandles, hpos): y,h = tup if isinstance(handle, Line2D): ydata = y*ones(self._xdata.shape, Float) handle.set_ydata(ydata+h/2) elif isinstance(handle, Rectangle): handle.set_y(y+1/4*h) handle.set_height(h/2) # Set the data for the legend patch bbox = self._get_handle_text_bbox(renderer).deepcopy() bbox.scale(1 + self.pad, 1 + self.pad) l,b,w,h = bbox.get_bounds() self.legendPatch.set_bounds(l,b,w,h) BEST, UR, UL, LL, LR, R, CL, CR, LC, UC, C = range(11) ox, oy = 0, 0 # center if iterable(self._loc) and len(self._loc)==2: xo = self.legendPatch.get_x() yo = self.legendPatch.get_y() x, y = self._loc ox = x-xo oy = y-yo self._offset(ox, oy) else: if self._loc in (BEST,): ox, oy = self._find_best_position(w, h) if self._loc in (UL, LL, CL): # left ox = self.axespad - l if self._loc in (UR, LR, R, CR): # right ox = 1 - (l + w + self.axespad) if self._loc in (UR, UL, UC): # upper oy = 1 - (b + h + self.axespad) if self._loc in (LL, LR, LC): # lower oy = self.axespad - b if self._loc in (LC, UC, C): # center x ox = (0.5-w/2)-l if self._loc in (CL, CR, C): # center y oy = (0.5-h/2)-b self._offset(ox, oy)
class Figure(Artist): def __init__( self, figsize=None, # defaults to rc figure.figsize dpi=None, # defaults to rc figure.dpi facecolor=None, # defaults to rc figure.facecolor edgecolor=None, # defaults to rc figure.edgecolor linewidth=1.0, # the default linewidth of the frame frameon=True, # whether or not to draw the figure frame subplotpars=None, # default to rc ): """ figsize is a w,h tuple in inches dpi is dots per inch subplotpars is a SubplotParams instance, defaults to rc """ Artist.__init__(self) #self.set_figure(self) self._axstack = Stack() # maintain the current axes self._axobservers = [] self._seen = {} # axes args we've seen if figsize is None: figsize = rcParams['figure.figsize'] if dpi is None: dpi = rcParams['figure.dpi'] if facecolor is None: facecolor = rcParams['figure.facecolor'] if edgecolor is None: edgecolor = rcParams['figure.edgecolor'] self._unit_conversions = {} self.dpi = Value(dpi) self.figwidth = Value(figsize[0]) self.figheight = Value(figsize[1]) self.ll = Point(Value(0), Value(0)) self.ur = Point(self.figwidth * self.dpi, self.figheight * self.dpi) self.bbox = Bbox(self.ll, self.ur) self.frameon = frameon self.transFigure = get_bbox_transform(unit_bbox(), self.bbox) self.figurePatch = Rectangle( xy=(0, 0), width=1, height=1, facecolor=facecolor, edgecolor=edgecolor, linewidth=linewidth, ) self._set_artist_props(self.figurePatch) self._hold = rcParams['axes.hold'] self.canvas = None if subplotpars is None: subplotpars = SubplotParams() self.subplotpars = subplotpars self.clf() self._cachedRenderer = None def get_window_extent(self, *args, **kwargs): 'get the figure bounding box in display space' return self.bbox def set_canvas(self, canvas): """ Set the canvas the contains the figure ACCEPTS: a FigureCanvas instance """ self.canvas = canvas def _get_unit_conversion(self, python_type): """ Get a unit conversion corresponding to a python type """ maps = [self._unit_conversions, Figure._default_unit_conversions] for m in maps: classes = [python_type] for current in classes: if (current in m): # found it! #print 'Found unit conversion for %s!' % (`python_type`) return m[current] return None def register_unit_conversion(self, python_type, conversion): """ Register a unit conversion class ACCEPTS: a Unit instance """ self._unit_conversions[python_type] = conversion def unregister_unit_conversion(self, python_type): """ Unregister a unit conversion class ACCEPTS: any Python type """ self._unit_conversions.remove(python_type) def _register_default_unit_conversion(python_type, conversion): """ Register a unit conversion class ACCEPTS: a Unit instance """ Figure._default_unit_conversions[python_type] = conversion _default_unit_conversions = {} register_default_unit_conversion = \ staticmethod(_register_default_unit_conversion) def _unregister_default_unit_conversion(python_type): """ Unregister a unit conversion class ACCEPTS: any Python type """ Figure._default_unit_conversions.remove(python_type) unregister_default_unit_conversion = \ staticmethod(_unregister_default_unit_conversion) def hold(self, b=None): """ Set the hold state. If hold is None (default), toggle the hold state. Else set the hold state to boolean value b. Eg hold() # toggle hold hold(True) # hold is on hold(False) # hold is off """ if b is None: self._hold = not self._hold else: self._hold = b def figimage(self, X, xo=0, yo=0, alpha=1.0, norm=None, cmap=None, vmin=None, vmax=None, origin=None): """ FIGIMAGE(X) # add non-resampled array to figure FIGIMAGE(X, xo, yo) # with pixel offsets FIGIMAGE(X, **kwargs) # control interpolation ,scaling, etc Add a nonresampled figure to the figure from array X. xo and yo are offsets in pixels X must be a float array If X is MxN, assume luminance (grayscale) If X is MxNx3, assume RGB If X is MxNx4, assume RGBA The following kwargs are allowed: * cmap is a cm colormap instance, eg cm.jet. If None, default to the rc image.cmap valuex * norm is a matplotlib.colors.normalize instance; default is normalization(). This scales luminance -> 0-1 * vmin and vmax are used to scale a luminance image to 0-1. If either is None, the min and max of the luminance values will be used. Note if you pass a norm instance, the settings for vmin and vmax will be ignored. * alpha = 1.0 : the alpha blending value * origin is either 'upper' or 'lower', which indicates where the [0,0] index of the array is in the upper left or lower left corner of the axes. Defaults to the rc image.origin value This complements the axes image (Axes.imshow) which will be resampled to fit the current axes. If you want a resampled image to fill the entire figure, you can define an Axes with size [0,1,0,1]. A image.FigureImage instance is returned. """ if not self._hold: self.clf() im = FigureImage(self, cmap, norm, xo, yo, origin) im.set_array(X) im.set_alpha(alpha) if norm is None: im.set_clim(vmin, vmax) self.images.append(im) return im def set_figsize_inches(self, *args, **kwargs): import warnings warnings.warn('Use set_size_inches instead!', DeprecationWarning) self.set_size_inches(*args, **kwargs) def set_size_inches(self, *args, **kwargs): """ set_size_inches(w,h, forward=False) Set the figure size in inches Usage: set_size_inches(self, w,h) OR set_size_inches(self, (w,h) ) optional kwarg forward=True will cause the canvas size to be automatically updated; eg you can resize the figure window from the shell WARNING: forward=True is broken on all backends except GTK* ACCEPTS: a w,h tuple with w,h in inches """ forward = kwargs.get('forward', False) if len(args) == 1: w, h = args[0] else: w, h = args self.figwidth.set(w) self.figheight.set(h) if forward: dpival = self.dpi.get() canvasw = w * dpival canvash = h * dpival manager = getattr(self.canvas, 'manager', None) if manager is not None: manager.resize(int(canvasw), int(canvash)) def get_size_inches(self): return self.figwidth.get(), self.figheight.get() def get_edgecolor(self): 'Get the edge color of the Figure rectangle' return self.figurePatch.get_edgecolor() def get_facecolor(self): 'Get the face color of the Figure rectangle' return self.figurePatch.get_facecolor() def get_figwidth(self): 'Return the figwidth as a float' return self.figwidth.get() def get_figheight(self): 'Return the figheight as a float' return self.figheight.get() def get_dpi(self): 'Return the dpi as a float' return self.dpi.get() def get_frameon(self): 'get the boolean indicating frameon' return self.frameon def set_edgecolor(self, color): """ Set the edge color of the Figure rectangle ACCEPTS: any matplotlib color - see help(colors) """ self.figurePatch.set_edgecolor(color) def set_facecolor(self, color): """ Set the face color of the Figure rectangle ACCEPTS: any matplotlib color - see help(colors) """ self.figurePatch.set_facecolor(color) def set_dpi(self, val): """ Set the dots-per-inch of the figure ACCEPTS: float """ self.dpi.set(val) def set_figwidth(self, val): """ Set the width of the figure in inches ACCEPTS: float """ self.figwidth.set(val) def set_figheight(self, val): """ Set the height of the figure in inches ACCEPTS: float """ self.figheight.set(val) def set_frameon(self, b): """ Set whether the figure frame (background) is displayed or invisible ACCEPTS: boolean """ self.frameon = b def delaxes(self, a): 'remove a from the figure and update the current axes' self.axes.remove(a) self._axstack.remove(a) keys = [] for key, thisax in self._seen.items(): if a == thisax: del self._seen[key] for func in self._axobservers: func(self) def _make_key(self, *args, **kwargs): 'make a hashable key out of args and kwargs' def fixitems(items): #items may have arrays and lists in them, so convert them # to tuples for the key ret = [] for k, v in items: if iterable(v): v = tuple(v) ret.append((k, v)) return tuple(ret) def fixlist(args): ret = [] for a in args: if iterable(a): a = tuple(a) ret.append(a) return tuple(ret) key = fixlist(args), fixitems(kwargs.items()) return key def add_axes(self, *args, **kwargs): """ Add an a axes with axes rect [left, bottom, width, height] where all quantities are in fractions of figure width and height. kwargs are legal Axes kwargs plus "polar" which sets whether to create a polar axes rect = l,b,w,h add_axes(rect) add_axes(rect, frameon=False, axisbg='g') add_axes(rect, polar=True) add_axes(ax) # add an Axes instance If the figure already has an axes with key *args, *kwargs then it will simply make that axes current and return it. If you do not want this behavior, eg you want to force the creation of a new axes, you must use a unique set of args and kwargs. The artist "label" attribute has been exposed for this purpose. Eg, if you want two axes that are otherwise identical to be added to the figure, make sure you give them unique labels: add_axes(rect, label='axes1') add_axes(rect, label='axes2') The Axes instance will be returned """ key = self._make_key(*args, **kwargs) if self._seen.has_key(key): ax = self._seen[key] self.sca(ax) return ax if not len(args): return if isinstance(args[0], Axes): a = args[0] assert (a.get_figure() is self) else: rect = args[0] ispolar = popd(kwargs, 'polar', False) if ispolar: a = PolarAxes(self, rect, **kwargs) else: a = Axes(self, rect, **kwargs) self.axes.append(a) self._axstack.push(a) self.sca(a) self._seen[key] = a return a def add_subplot(self, *args, **kwargs): """ Add a subplot. Examples add_subplot(111) add_subplot(212, axisbg='r') # add subplot with red background add_subplot(111, polar=True) # add a polar subplot add_subplot(sub) # add Subplot instance sub kwargs are legal Axes kwargs plus"polar" which sets whether to create a polar axes. The Axes instance will be returned. If the figure already has a subplot with key *args, *kwargs then it will simply make that subplot current and return it """ key = self._make_key(*args, **kwargs) if self._seen.has_key(key): ax = self._seen[key] self.sca(ax) return ax if not len(args): return if isinstance(args[0], Subplot) or isinstance(args[0], PolarSubplot): a = args[0] assert (a.get_figure() is self) else: ispolar = popd(kwargs, 'polar', False) if ispolar: a = PolarSubplot(self, *args, **kwargs) else: a = Subplot(self, *args, **kwargs) self.axes.append(a) self._axstack.push(a) self.sca(a) self._seen[key] = a return a def clf(self): """ Clear the figure """ self.axes = [] self._axstack.clear() self._seen = {} self.lines = [] self.patches = [] self.texts = [] self.images = [] self.legends = [] def clear(self): """ Clear the figure """ self.clf() def draw(self, renderer): """ Render the figure using Renderer instance renderer """ # draw the figure bounding box, perhaps none for white figure #print 'figure draw' if not self.get_visible(): return renderer.open_group('figure') self.transFigure.freeze() # eval the lazy objects if self.frameon: self.figurePatch.draw(renderer) for p in self.patches: p.draw(renderer) for l in self.lines: l.draw(renderer) if len(self.images) == 1: im = self.images[0] im.draw(renderer) elif len(self.images) > 1: # make a composite image blending alpha # list of (_image.Image, ox, oy) if not allequal([im.origin for im in self.images]): raise ValueError( 'Composite images with different origins not supported') ims = [(im.make_image(), im.ox, im.oy) for im in self.images] im = _image.from_images(self.bbox.height(), self.bbox.width(), ims) im.is_grayscale = False l, b, w, h = self.bbox.get_bounds() renderer.draw_image(0, 0, im, self.bbox) # render the axes for a in self.axes: a.draw(renderer) # render the figure text for t in self.texts: t.draw(renderer) for legend in self.legends: legend.draw(renderer) self.transFigure.thaw() # release the lazy objects renderer.close_group('figure') self._cachedRenderer = renderer self.canvas.draw_event(renderer) def draw_artist(self, a): 'draw artist only -- this is available only after the figure is drawn' assert self._cachedRenderer is not None a.draw(self._cachedRenderer) def get_axes(self): return self.axes def legend(self, handles, labels, loc, **kwargs): """ Place a legend in the figure. Labels are a sequence of strings, handles is a sequence of line or patch instances, and loc can be a string or an integer specifying the legend location USAGE: legend( (line1, line2, line3), ('label1', 'label2', 'label3'), 'upper right') The LOC location codes are 'best' : 0, (currently not supported, defaults to upper right) 'upper right' : 1, (default) 'upper left' : 2, 'lower left' : 3, 'lower right' : 4, 'right' : 5, 'center left' : 6, 'center right' : 7, 'lower center' : 8, 'upper center' : 9, 'center' : 10, loc can also be an (x,y) tuple in figure coords, which specifies the lower left of the legend box. figure coords are (0,0) is the left, bottom of the figure and 1,1 is the right, top. The legend instance is returned """ handles = flatten(handles) l = Legend(self, handles, labels, loc, isaxes=False, **kwargs) self._set_artist_props(l) self.legends.append(l) return l def text(self, x, y, s, *args, **kwargs): """ Add text to figure at location x,y (relative 0-1 coords) See the help for Axis text for the meaning of the other arguments """ override = _process_text_args({}, *args, **kwargs) t = Text( x=x, y=y, text=s, ) t.update(override) self._set_artist_props(t) self.texts.append(t) return t def _set_artist_props(self, a): if a != self: a.set_figure(self) a.set_transform(self.transFigure) def gca(self, **kwargs): """ Return the current axes, creating one if necessary """ ax = self._axstack() if ax is not None: return ax return self.add_subplot(111, **kwargs) def sca(self, a): 'Set the current axes to be a and return a' self._axstack.bubble(a) for func in self._axobservers: func(self) return a def add_axobserver(self, func): 'whenever the axes state change, func(self) will be called' self._axobservers.append(func) def savefig(self, *args, **kwargs): """ SAVEFIG(fname, dpi=None, facecolor='w', edgecolor='w', orientation='portrait', papertype=None, format=None): Save the current figure. fname - the filename to save the current figure to. The output formats supported depend on the backend being used. and are deduced by the extension to fname. Possibilities are eps, jpeg, pdf, png, ps, svg. fname can also be a file or file-like object - cairo backend only. dpi - is the resolution in dots per inch. If None it will default to the value savefig.dpi in the matplotlibrc file facecolor and edgecolor are the colors of the figure rectangle orientation is either 'landscape' or 'portrait' - not supported on all backends; currently only on postscript output papertype is is one of 'letter', 'legal', 'executive', 'ledger', 'a0' through 'a10', or 'b0' through 'b10' - only supported for postscript output format - one of 'pdf', 'png', 'ps', 'svg'. It is used to specify the output when fname is a file or file-like object - cairo backend only. """ for key in ('dpi', 'facecolor', 'edgecolor'): if not kwargs.has_key(key): kwargs[key] = rcParams['savefig.%s' % key] self.canvas.print_figure(*args, **kwargs) def colorbar(self, mappable, cax=None, **kw): # Temporary compatibility code: old = ('tickfmt', 'cspacing', 'clabels', 'edgewidth', 'edgecolor') oldkw = [k for k in old if kw.has_key(k)] if oldkw: msg = 'Old colorbar kwargs (%s) found; using colorbar_classic.' % ( ','.join(oldkw), ) warnings.warn(msg, DeprecationWarning) self.colorbar_classic(mappable, cax, **kw) return cax # End of compatibility code block. orientation = kw.get('orientation', 'vertical') ax = self.gca() if cax is None: cax, kw = cbar.make_axes(ax, **kw) cb = cbar.Colorbar(cax, mappable, **kw) mappable.add_observer(cb) mappable.set_colorbar(cb, cax) self.sca(ax) return cb colorbar.__doc__ = ''' Create a colorbar for a ScalarMappable instance. Documentation for the pylab thin wrapper: %s ''' % cbar.colorbar_doc def colorbar_classic(self, mappable, cax=None, orientation='vertical', tickfmt='%1.1f', cspacing='proportional', clabels=None, drawedges=False, edgewidth=0.5, edgecolor='k'): """ Create a colorbar for mappable image mappable is the cm.ScalarMappable instance that you want the colorbar to apply to, e.g. an Image as returned by imshow or a PatchCollection as returned by scatter or pcolor. tickfmt is a format string to format the colorbar ticks cax is a colorbar axes instance in which the colorbar will be placed. If None, as default axesd will be created resizing the current aqxes to make room for it. If not None, the supplied axes will be used and the other axes positions will be unchanged. orientation is the colorbar orientation: one of 'vertical' | 'horizontal' cspacing controls how colors are distributed on the colorbar. if cspacing == 'linear', each color occupies an equal area on the colorbar, regardless of the contour spacing. if cspacing == 'proportional' (Default), the area each color occupies on the the colorbar is proportional to the contour interval. Only relevant for a Contour image. clabels can be a sequence containing the contour levels to be labelled on the colorbar, or None (Default). If clabels is None, labels for all contour intervals are displayed. Only relevant for a Contour image. if drawedges == True, lines are drawn at the edges between each color on the colorbar. Default False. edgecolor is the line color delimiting the edges of the colors on the colorbar (if drawedges == True). Default black ('k') edgewidth is the width of the lines delimiting the edges of the colors on the colorbar (if drawedges == True). Default 0.5 return value is the colorbar axes instance """ if orientation not in ('horizontal', 'vertical'): raise ValueError('Orientation must be horizontal or vertical') if isinstance(mappable, FigureImage) and cax is None: raise TypeError( 'Colorbars for figure images currently not supported unless you provide a colorbar axes in cax' ) ax = self.gca() cmap = mappable.cmap if cax is None: l, b, w, h = ax.get_position() if orientation == 'vertical': neww = 0.8 * w ax.set_position((l, b, neww, h), 'both') cax = self.add_axes([l + 0.9 * w, b, 0.1 * w, h]) else: newh = 0.8 * h ax.set_position((l, b + 0.2 * h, w, newh), 'both') cax = self.add_axes([l, b, w, 0.1 * h]) else: if not isinstance(cax, Axes): raise TypeError('Expected an Axes instance for cax') norm = mappable.norm if norm.vmin is None or norm.vmax is None: mappable.autoscale() cmin = norm.vmin cmax = norm.vmax if isinstance(mappable, ContourSet): # mappable image is from contour or contourf clevs = mappable.levels clevs = minimum(clevs, cmax) clevs = maximum(clevs, cmin) isContourSet = True elif isinstance(mappable, ScalarMappable): # from imshow or pcolor. isContourSet = False clevs = linspace(cmin, cmax, cmap.N + 1) # boundaries, hence N+1 else: raise TypeError("don't know how to handle type %s" % type(mappable)) N = len(clevs) C = array([clevs, clevs]) if cspacing == 'linear': X, Y = meshgrid(clevs, [0, 1]) elif cspacing == 'proportional': X, Y = meshgrid(linspace(cmin, cmax, N), [0, 1]) else: raise ValueError("cspacing must be 'linear' or 'proportional'") if orientation == 'vertical': args = (transpose(Y), transpose(C), transpose(X), clevs) else: args = (C, Y, X, clevs) #If colors were listed in the original mappable, then # let contour handle them the same way. colors = getattr(mappable, 'colors', None) if colors is not None: kw = {'colors': colors} else: kw = {'cmap': cmap, 'norm': norm} if isContourSet and not mappable.filled: CS = cax.contour(*args, **kw) colls = mappable.collections for ii in range(len(colls)): CS.collections[ii].set_linewidth(colls[ii].get_linewidth()) else: kw['antialiased'] = False CS = cax.contourf(*args, **kw) if drawedges: for col in CS.collections: col.set_edgecolor(edgecolor) col.set_linewidth(edgewidth) mappable.add_observer(CS) mappable.set_colorbar(CS, cax) if isContourSet: if cspacing == 'linear': ticks = linspace(cmin, cmax, N) else: ticks = clevs if cmin == mappable.levels[0]: ticklevs = clevs else: # We are not showing the full ends of the range. ticks = ticks[1:-1] ticklevs = clevs[1:-1] labs = [tickfmt % lev for lev in ticklevs] if clabels is not None: for i, lev in enumerate(ticklevs): if lev not in clabels: labs[i] = '' if orientation == 'vertical': cax.set_xticks([]) cax.yaxis.tick_right() cax.yaxis.set_label_position('right') if isContourSet: cax.set_yticks(ticks) cax.set_yticklabels(labs) else: cax.yaxis.set_major_formatter(FormatStrFormatter(tickfmt)) else: cax.set_yticks([]) if isContourSet: cax.set_xticks(ticks) cax.set_xticklabels(labs) else: cax.xaxis.set_major_formatter(FormatStrFormatter(tickfmt)) self.sca(ax) return cax def subplots_adjust(self, *args, **kwargs): """ fig.subplots_adjust(left=None, bottom=None, right=None, wspace=None, hspace=None): Update the SubplotParams with kwargs (defaulting to rc where None) and update the subplot locations """ self.subplotpars.update(*args, **kwargs) import matplotlib.axes for ax in self.axes: if not isinstance(ax, matplotlib.axes.Subplot): # Check if sharing a subplots axis if ax._sharex is not None and isinstance( ax._sharex, matplotlib.axes.Subplot): ax._sharex.update_params() ax.set_position([ ax._sharex.figLeft, ax._sharex.figBottom, ax._sharex.figW, ax._sharex.figH ]) elif ax._sharey is not None and isinstance( ax._sharey, matplotlib.axes.Subplot): ax._sharey.update_params() ax.set_position([ ax._sharey.figLeft, ax._sharey.figBottom, ax._sharey.figW, ax._sharey.figH ]) else: ax.update_params() ax.set_position([ax.figLeft, ax.figBottom, ax.figW, ax.figH])
def candlestick(ax, quotes, width=0.2, colorup='k', colordown='r', alpha=1.0): """ quotes is a list of (time, open, close, high, low, ...) tuples. As long as the first 5 elements of the tuples are these values, the tuple can be as long as you want (eg it may store volume). time must be in float days format - see date2num Plot the time, open, close, high, low as a vertical line ranging from low to high. Use a rectangular bar to represent the open-close span. If close >= open, use colorup to color the bar, otherwise use colordown ax : an Axes instance to plot to width : fraction of a day for the rectangle width colorup : the color of the rectangle where close >= open colordown : the color of the rectangle where close < open alpha : the rectangle alpha level return value is lines, patches where lines is a list of lines added and patches is a list of the rectangle patches added """ OFFSET = width/2.0 lines = [] patches = [] for q in quotes: t, open, close, high, low = q[:5] if close>=open : color = colorup lower = open height = close-open else : color = colordown lower = close height = open-close vline = Line2D( xdata=(t, t), ydata=(low, high), color='k', linewidth=0.5, antialiased=True, ) rect = Rectangle( xy = (t-OFFSET, lower), width = width, height = height, facecolor = color, edgecolor = color, ) rect.set_alpha(alpha) lines.append(vline) patches.append(rect) ax.add_line(vline) ax.add_patch(rect) ax.autoscale_view() return lines, patches
def __init__(self, parent, handles, labels, loc, isaxes= None, numpoints = None, # the number of points in the legend line prop = None, pad = None, # the fractional whitespace inside the legend border markerscale = None, # the relative size of legend markers vs. original # the following dimensions are in axes coords labelsep = None, # the vertical space between the legend entries handlelen = None, # the length of the legend lines handletextsep = None, # the space between the legend line and legend text axespad = None, # the border between the axes and legend edge shadow= None, ): """ parent # the artist that contains the legend handles # a list of artists (lines, patches) to add to the legend labels # a list of strings to label the legend loc # a location code isaxes=True # whether this is an axes legend numpoints = 4 # the number of points in the legend line fontprop = FontProperties(size='smaller') # the font property pad = 0.2 # the fractional whitespace inside the legend border markerscale = 0.6 # the relative size of legend markers vs. original shadow # if True, draw a shadow behind legend The following dimensions are in axes coords labelsep = 0.005 # the vertical space between the legend entries handlelen = 0.05 # the length of the legend lines handletextsep = 0.02 # the space between the legend line and legend text axespad = 0.02 # the border between the axes and legend edge """ Artist.__init__(self) if is_string_like(loc) and not self.codes.has_key(loc): warnings.warn('Unrecognized location %s. Falling back on upper right; valid locations are\n%s\t' %(loc, '\n\t'.join(self.codes.keys()))) if is_string_like(loc): loc = self.codes.get(loc, 1) proplist=[numpoints, pad, markerscale, labelsep, handlelen, handletextsep, axespad, shadow, isaxes] propnames=['numpoints', 'pad', 'markerscale', 'labelsep', 'handlelen', 'handletextsep', 'axespad', 'shadow', 'isaxes'] for name, value in zip(propnames,proplist): if value is None: value=rcParams["legend."+name] setattr(self,name,value) if prop is None: self.prop=FontProperties(size=rcParams["legend.fontsize"]) else: self.prop=prop self.fontsize = self.prop.get_size_in_points() if self.isaxes: # parent is an Axes self.set_figure(parent.figure) else: # parent is a Figure self.set_figure(parent) self.parent = parent self.set_transform( get_bbox_transform( unit_bbox(), parent.bbox) ) self._loc = loc # make a trial box in the middle of the axes. relocate it # based on it's bbox left, top = 0.5, 0.5 if self.numpoints == 1: self._xdata = array([left + self.handlelen*0.5]) else: self._xdata = linspace(left, left + self.handlelen, self.numpoints) textleft = left+ self.handlelen+self.handletextsep self.texts = self._get_texts(labels, textleft, top) self.legendHandles = self._get_handles(handles, self.texts) if len(self.texts): left, top = self.texts[-1].get_position() HEIGHT = self._approx_text_height()*len(self.texts) else: HEIGHT = 0.2 bottom = top-HEIGHT left -= self.handlelen + self.handletextsep + self.pad self.legendPatch = Rectangle( xy=(left, bottom), width=0.5, height=HEIGHT, facecolor='w', edgecolor='k', ) self._set_artist_props(self.legendPatch) self._drawFrame = True
def __init__(self, ax, onselect, drawtype='box', minspanx=None, minspany=None, useblit=False, lineprops=None, rectprops=None): """ Create a selector in ax. When a selection is made, clear the span and call onselect with onselect(pos_1, pos_2) and clear the drawn box/line. There pos_i are arrays of length 2 containing the x- and y-coordinate. If minspanx is not None then events smaller than minspanx in x direction are ignored(it's the same for y). The rect is drawn with rectprops; default rectprops = dict(facecolor='red', edgecolor = 'black', alpha=0.5, fill=False) The line is drawn with lineprops; default lineprops = dict(color='black', linestyle='-', linewidth = 2, alpha=0.5) Use type if you want the mouse to draw a line, a box or nothing between click and actual position ny setting drawtype = 'line', drawtype='box' or drawtype = 'none'. """ self.ax = ax self.visible = True 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.active = True # for activation / deactivation self.to_draw = None self.background = None if drawtype == 'none': drawtype = 'line' # draw a line but make it self.visible = False # invisible if drawtype == 'box': if rectprops is None: rectprops = dict(facecolor='white', edgecolor='black', alpha=0.5, fill=False) self.rectprops = rectprops self.to_draw = Rectangle((0, 0), 0, 1, visible=False, **self.rectprops) self.ax.add_patch(self.to_draw) if drawtype == 'line': if lineprops is None: lineprops = dict(color='black', linestyle='-', linewidth=2, alpha=0.5) self.lineprops = lineprops self.to_draw = Line2D([0, 0], [0, 0], visible=False, **self.lineprops) self.ax.add_line(self.to_draw) self.onselect = onselect self.useblit = useblit self.minspanx = minspanx self.minspany = minspany self.drawtype = drawtype # will save the data (position at mouseclick) self.eventpress = None # will save the data (pos. at mouserelease) self.eventrelease = None
def __init__(self, ax, labels, actives): """ Add check buttons to axes.Axes instance ax labels is a len(buttons) list of labels as strings actives is a len(buttons) list of booleans indicating whether the button is active """ ax.set_xticks([]) ax.set_yticks([]) ax.set_navigate(False) if len(labels) > 1: dy = 1. / (len(labels) + 1) ys = npy.linspace(1 - dy, dy, len(labels)) else: dy = 0.25 ys = [0.5] cnt = 0 axcolor = ax.get_axis_bgcolor() self.labels = [] self.lines = [] self.rectangles = [] lineparams = { 'color': 'k', 'linewidth': 1.25, 'transform': ax.transAxes, 'solid_capstyle': 'butt' } for y, label in zip(ys, labels): t = ax.text(0.25, y, label, transform=ax.transAxes, horizontalalignment='left', verticalalignment='center') w, h = dy / 2., dy / 2. x, y = 0.05, y - h / 2. p = Rectangle(xy=(x, y), width=w, height=h, facecolor=axcolor, transform=ax.transAxes) l1 = Line2D([x, x + w], [y + h, y], **lineparams) l2 = Line2D([x, x + w], [y, y + h], **lineparams) l1.set_visible(actives[cnt]) l2.set_visible(actives[cnt]) self.labels.append(t) self.rectangles.append(p) self.lines.append((l1, l2)) ax.add_patch(p) ax.add_line(l1) ax.add_line(l2) cnt += 1 ax.figure.canvas.mpl_connect('button_press_event', self._clicked) self.ax = ax self.cnt = 0 self.observers = {}
def __init__(self, parent, handles, labels, loc = None, numpoints = None, # the number of points in the legend line prop = None, pad = None, # the fractional whitespace inside the legend border markerscale = None, # the relative size of legend markers vs. original # the following dimensions are in axes coords labelsep = None, # the vertical space between the legend entries handlelen = None, # the length of the legend lines handletextsep = None, # the space between the legend line and legend text axespad = None, # the border between the axes and legend edge shadow = None ): """ parent # the artist that contains the legend handles # a list of artists (lines, patches) to add to the legend labels # a list of strings to label the legend loc # a location code numpoints = 4 # the number of points in the legend line prop = FontProperties(size='smaller') # the font property pad = 0.2 # the fractional whitespace inside the legend border markerscale = 0.6 # the relative size of legend markers vs. original shadow # if True, draw a shadow behind legend The following dimensions are in axes coords labelsep = 0.005 # the vertical space between the legend entries handlelen = 0.05 # the length of the legend lines handletextsep = 0.02 # the space between the legend line and legend text axespad = 0.02 # the border between the axes and legend edge """ from axes import Axes # local import only to avoid circularity from figure import Figure # local import only to avoid circularity Artist.__init__(self) proplist=[numpoints, pad, markerscale, labelsep, handlelen, handletextsep, axespad, shadow] propnames=['numpoints', 'pad', 'markerscale', 'labelsep', 'handlelen', 'handletextsep', 'axespad', 'shadow'] for name, value in safezip(propnames,proplist): if value is None: value=rcParams["legend."+name] setattr(self,name,value) if self.numpoints <= 0: raise ValueError("numpoints must be >= 0; it was %d"% numpoints) if prop is None: self.prop=FontProperties(size=rcParams["legend.fontsize"]) else: self.prop=prop self.fontsize = self.prop.get_size_in_points() if isinstance(parent,Axes): self.isaxes = True self.set_figure(parent.figure) elif isinstance(parent,Figure): self.isaxes = False self.set_figure(parent) else: raise TypeError("Legend needs either Axes or Figure as parent") self.parent = parent self._offsetTransform = Affine2D() self._parentTransform = BboxTransformTo(parent.bbox) Artist.set_transform(self, self._offsetTransform + self._parentTransform) if loc is None: loc = rcParams["legend.loc"] if not self.isaxes and loc in [0,'best']: loc = 'upper right' if is_string_like(loc): if not self.codes.has_key(loc): if self.isaxes: warnings.warn('Unrecognized location "%s". Falling back on "best"; ' 'valid locations are\n\t%s\n' % (loc, '\n\t'.join(self.codes.keys()))) loc = 0 else: warnings.warn('Unrecognized location "%s". Falling back on "upper right"; ' 'valid locations are\n\t%s\n' % (loc, '\n\t'.join(self.codes.keys()))) loc = 1 else: loc = self.codes[loc] if not self.isaxes and loc == 0: warnings.warn('Automatic legend placement (loc="best") not implemented for figure legend. ' 'Falling back on "upper right".') loc = 1 self._loc = loc self.legendPatch = Rectangle( xy=(0.0, 0.0), width=0.5, height=0.5, facecolor='w', edgecolor='k', ) self._set_artist_props(self.legendPatch) # make a trial box in the middle of the axes. relocate it # based on it's bbox left, top = 0.5, 0.5 textleft = left+ self.handlelen+self.handletextsep self.texts = self._get_texts(labels, textleft, top) self.legendHandles = self._get_handles(handles, self.texts) self._drawFrame = True
def __init__(self, ax, onselect, direction, minspan=None, useblit=False, rectprops=None, onmove_callback=None): """ Create a span selector in ax. When a selection is made, clear the span and call onselect with onselect(vmin, vmax) and clear the span. direction must be 'horizontal' or 'vertical' If minspan is not None, ignore events smaller than minspan The span rect is drawn with rectprops; default rectprops = dict(facecolor='red', alpha=0.5) set the visible attribute to False if you want to turn off the functionality of the span selector """ if rectprops is None: rectprops = dict(facecolor='red', alpha=0.5) assert direction in [ 'horizontal', 'vertical' ], 'Must choose horizontal or vertical for direction' self.direction = direction self.ax = ax self.visible = True 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.rect = None self.background = None self.rectprops = rectprops self.onselect = onselect self.onmove_callback = onmove_callback self.useblit = useblit self.minspan = minspan # Needed when dragging out of axes self.buttonDown = False self.prev = (0, 0) if self.direction == 'horizontal': trans = blended_transform_factory(self.ax.transData, self.ax.transAxes) w, h = 0, 1 else: trans = blended_transform_factory(self.ax.transAxes, self.ax.transData) w, h = 1, 0 self.rect = Rectangle((0, 0), w, h, transform=trans, visible=False, **self.rectprops) if not self.useblit: self.ax.add_patch(self.rect) self.pressv = None
class SpanSelector(AxesWidget): """ Select a min/max range of the x or y axes for a matplotlib Axes Example usage:: ax = subplot(111) ax.plot(x,y) def onselect(vmin, vmax): print vmin, vmax span = SpanSelector(ax, onselect, 'horizontal') *onmove_callback* is an optional callback that is called on mouse move within the span range """ def __init__(self, ax, onselect, direction, minspan=None, useblit=False, rectprops=None, onmove_callback=None): """ Create a span selector in *ax*. When a selection is made, clear the span and call *onselect* with:: onselect(vmin, vmax) and clear the span. *direction* must be 'horizontal' or 'vertical' If *minspan* is not *None*, ignore events smaller than *minspan* The span rectangle is drawn with *rectprops*; default:: rectprops = dict(facecolor='red', alpha=0.5) Set the visible attribute to *False* if you want to turn off the functionality of the span selector """ AxesWidget.__init__(self, ax) if rectprops is None: rectprops = dict(facecolor='red', alpha=0.5) assert direction in ['horizontal', 'vertical'], 'Must choose horizontal or vertical for direction' self.direction = direction self.visible = True self.rect = None self.background = None self.pressv = None self.rectprops = rectprops self.onselect = onselect self.onmove_callback = onmove_callback self.useblit = useblit self.minspan = minspan # Needed when dragging out of axes self.buttonDown = False self.prev = (0, 0) # Reset canvas so that `new_axes` connects events. self.canvas = None self.new_axes(ax) def new_axes(self,ax): self.ax = ax if self.canvas is not ax.figure.canvas: self.disconnect_events() self.canvas = ax.figure.canvas self.connect_event('motion_notify_event', self.onmove) self.connect_event('button_press_event', self.press) self.connect_event('button_release_event', self.release) self.connect_event('draw_event', self.update_background) if self.direction == 'horizontal': trans = blended_transform_factory(self.ax.transData, self.ax.transAxes) w,h = 0,1 else: trans = blended_transform_factory(self.ax.transAxes, self.ax.transData) w,h = 1,0 self.rect = Rectangle( (0,0), w, h, transform=trans, visible=False, **self.rectprops ) if not self.useblit: self.ax.add_patch(self.rect) def update_background(self, event): 'force an update of the background' # If you add a call to `ignore` here, you'll want to check edge case: # `release` can call a draw event even when `ignore` is True. if self.useblit: self.background = self.canvas.copy_from_bbox(self.ax.bbox) def ignore(self, event): 'return *True* if *event* should be ignored' widget_off = not self.visible or not self.active non_event = event.inaxes!=self.ax or event.button !=1 return widget_off or non_event def press(self, event): 'on button press event' if self.ignore(event): return self.buttonDown = True self.rect.set_visible(self.visible) if self.direction == 'horizontal': self.pressv = event.xdata else: self.pressv = event.ydata return False def release(self, event): 'on button release event' if self.ignore(event) and not self.buttonDown: return if self.pressv is None: return self.buttonDown = False self.rect.set_visible(False) self.canvas.draw() vmin = self.pressv if self.direction == 'horizontal': vmax = event.xdata or self.prev[0] else: vmax = event.ydata or self.prev[1] if vmin>vmax: vmin, vmax = vmax, vmin span = vmax - vmin if self.minspan is not None and span<self.minspan: return self.onselect(vmin, vmax) self.pressv = None return False 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.rect) self.canvas.blit(self.ax.bbox) else: self.canvas.draw_idle() return False def onmove(self, event): 'on motion notify event' if self.pressv is None or self.ignore(event): return x, y = event.xdata, event.ydata self.prev = x, y if self.direction == 'horizontal': v = x else: v = y minv, maxv = v, self.pressv if minv>maxv: minv, maxv = maxv, minv if self.direction == 'horizontal': self.rect.set_x(minv) self.rect.set_width(maxv-minv) else: self.rect.set_y(minv) self.rect.set_height(maxv-minv) if self.onmove_callback is not None: vmin = self.pressv if self.direction == 'horizontal': vmax = event.xdata or self.prev[0] else: vmax = event.ydata or self.prev[1] if vmin>vmax: vmin, vmax = vmax, vmin self.onmove_callback(vmin, vmax) self.update() return False
def set_figure(self, fig): Rectangle.set_figure(self, fig) self._text.set_figure(fig)
class RectangleSelector: """ Select a min/max range of the x axes for a matplotlib Axes Example usage:: from matplotlib.widgets import RectangleSelector from pylab import * def onselect(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 def toggle_selector(event): print ' Key pressed.' if event.key in ['Q', 'q'] and toggle_selector.RS.active: print ' RectangleSelector deactivated.' toggle_selector.RS.set_active(False) if event.key in ['A', 'a'] and not toggle_selector.RS.active: print ' RectangleSelector activated.' toggle_selector.RS.set_active(True) x = arange(100)/(99.0) y = sin(x) fig = figure ax = subplot(111) ax.plot(x,y) toggle_selector.RS = RectangleSelector(ax, onselect, drawtype='line') connect('key_press_event', toggle_selector) show() """ def __init__(self, ax, onselect, drawtype='box', minspanx=None, minspany=None, useblit=False, lineprops=None, rectprops=None, spancoords='data', button=None): """ Create a selector in ax. When a selection is made, clear the span and call onselect with onselect(pos_1, pos_2) and clear the drawn box/line. There pos_i are arrays of length 2 containing the x- and y-coordinate. If minspanx is not None then events smaller than minspanx in x direction are ignored(it's the same for y). The rect is drawn with rectprops; default rectprops = dict(facecolor='red', edgecolor = 'black', alpha=0.5, fill=False) The line is drawn with lineprops; default lineprops = dict(color='black', linestyle='-', linewidth = 2, alpha=0.5) Use type if you want the mouse to draw a line, a box or nothing between click and actual position ny setting drawtype = 'line', drawtype='box' or drawtype = 'none'. spancoords is one of 'data' or 'pixels'. If 'data', minspanx and minspanx will be interpreted in the same coordinates as the x and ya axis, if 'pixels', they are in pixels button is a list of integers indicating which mouse buttons should be used for rectangle selection. You can also specify a single integer if only a single button is desired. Default is None, which does not limit which button can be used. Note, typically: 1 = left mouse button 2 = center mouse button (scroll wheel) 3 = right mouse button """ self.ax = ax self.visible = True 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.active = True # for activation / deactivation self.to_draw = None self.background = None if drawtype == 'none': drawtype = 'line' # draw a line but make it self.visible = False # invisible if drawtype == 'box': if rectprops is None: rectprops = dict(facecolor='white', edgecolor = 'black', alpha=0.5, fill=False) self.rectprops = rectprops self.to_draw = Rectangle((0,0), 0, 1,visible=False,**self.rectprops) self.ax.add_patch(self.to_draw) if drawtype == 'line': if lineprops is None: lineprops = dict(color='black', linestyle='-', linewidth = 2, alpha=0.5) self.lineprops = lineprops self.to_draw = Line2D([0,0],[0,0],visible=False,**self.lineprops) self.ax.add_line(self.to_draw) self.onselect = onselect self.useblit = useblit self.minspanx = minspanx self.minspany = minspany if button is None or isinstance(button, list): self.validButtons = button elif isinstance(button, int): self.validButtons = [button] assert(spancoords in ('data', 'pixels')) self.spancoords = spancoords self.drawtype = drawtype # will save the data (position at mouseclick) self.eventpress = None # will save the data (pos. at mouserelease) self.eventrelease = None 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 RectangleSelector is not active : if not self.active: return True # If canvas was locked if not self.canvas.widgetlock.available(self): return True # Only do rectangle selection if event was triggered # with a desired button if self.validButtons is not None: if not event.button in self.validButtons: return True # 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.to_draw.set_visible(self.visible) self.eventpress = event return False def release(self, event): 'on button release event' if self.eventpress is None or self.ignore(event): return # make the box/line invisible again self.to_draw.set_visible(False) self.canvas.draw() # release coordinates, button, ... self.eventrelease = event if self.spancoords=='data': xmin, ymin = self.eventpress.xdata, self.eventpress.ydata xmax, ymax = self.eventrelease.xdata, self.eventrelease.ydata # calculate dimensions of box or line get values in the right # order elif self.spancoords=='pixels': xmin, ymin = self.eventpress.x, self.eventpress.y xmax, ymax = self.eventrelease.x, self.eventrelease.y else: raise ValueError('spancoords must be "data" or "pixels"') 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 if (self.drawtype=='box') and (xproblems or yproblems): """Box to small""" # check if drawed distance (if it exists) is return # not to small in neither x nor y-direction if (self.drawtype=='line') and (xproblems and yproblems): """Line to small""" # check if drawed distance (if it exists) is return # not to small in neither x nor y-direction self.onselect(self.eventpress, self.eventrelease) # call desired function self.eventpress = None # reset the variables to their self.eventrelease = None # inital values return False 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() return False def onmove(self, event): 'on motion notify event if box/line is wanted' if self.eventpress is None or self.ignore(event): return x,y = event.xdata, event.ydata # actual position (with # (button still pressed) if self.drawtype == 'box': 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() return False if self.drawtype == 'line': self.to_draw.set_data([self.eventpress.xdata, x], [self.eventpress.ydata, y]) self.update() return False def set_active(self, active): """ Use this to activate / deactivate the RectangleSelector from your program with an boolean variable 'active'. """ self.active = active def get_active(self): """ to get status of active mode (boolean variable)""" return self.active
class Legend(Artist): """ Place a legend on the axes at location loc. Labels are a sequence of strings and loc can be a string or an integer specifying the legend location The location codes are 'best' : 0, (currently not supported, defaults to upper right) 'upper right' : 1, (default) 'upper left' : 2, 'lower left' : 3, 'lower right' : 4, 'right' : 5, 'center left' : 6, 'center right' : 7, 'lower center' : 8, 'upper center' : 9, 'center' : 10, Return value is a sequence of text, line instances that make up the legend """ codes = {'best' : 0, 'upper right' : 1, # default 'upper left' : 2, 'lower left' : 3, 'lower right' : 4, 'right' : 5, 'center left' : 6, 'center right' : 7, 'lower center' : 8, 'upper center' : 9, 'center' : 10, } def __init__(self, parent, handles, labels, loc, isaxes=True, numpoints = 4, # the number of points in the legend line prop = FontProperties(size='smaller'), pad = 0.2, # the fractional whitespace inside the legend border markerscale = 0.6, # the relative size of legend markers vs. original # the following dimensions are in axes coords labelsep = 0.005, # the vertical space between the legend entries handlelen = 0.05, # the length of the legend lines handletextsep = 0.02, # the space between the legend line and legend text axespad = 0.02, # the border between the axes and legend edge shadow=False, ): """ parent # the artist that contains the legend handles # a list of artists (lines, patches) to add to the legend labels # a list of strings to label the legend loc # a location code isaxes=True # whether this is an axes legend numpoints = 4 # the number of points in the legend line fontprop = FontProperties('smaller') # the font property pad = 0.2 # the fractional whitespace inside the legend border markerscale = 0.6 # the relative size of legend markers vs. original shadow # if True, draw a shadow behind legend The following dimensions are in axes coords labelsep = 0.005 # the vertical space between the legend entries handlelen = 0.05 # the length of the legend lines handletextsep = 0.02 # the space between the legend line and legend text axespad = 0.02 # the border between the axes and legend edge """ Artist.__init__(self) if is_string_like(loc) and not self.codes.has_key(loc): verbose.report_error('Unrecognized location %s. Falling back on upper right; valid locations are\n%s\t' %(loc, '\n\t'.join(self.codes.keys()))) if is_string_like(loc): loc = self.codes.get(loc, 1) self.numpoints = numpoints self.prop = prop self.fontsize = prop.get_size_in_points() self.pad = pad self.markerscale = markerscale self.labelsep = labelsep self.handlelen = handlelen self.handletextsep = handletextsep self.axespad = axespad self.shadow = shadow if isaxes: # parent is an Axes self.set_figure(parent.figure) else: # parent is a Figure self.set_figure(parent) self.parent = parent self.set_transform( get_bbox_transform( unit_bbox(), parent.bbox) ) self._loc = loc # make a trial box in the middle of the axes. relocate it # based on it's bbox left, upper = 0.5, 0.5 if self.numpoints == 1: self._xdata = array([left + self.handlelen*0.5]) else: self._xdata = linspace(left, left + self.handlelen, self.numpoints) textleft = left+ self.handlelen+self.handletextsep self.texts = self._get_texts(labels, textleft, upper) self.handles = self._get_handles(handles, self.texts) left, top = self.texts[-1].get_position() HEIGHT = self._approx_text_height() bottom = top-HEIGHT left -= self.handlelen + self.handletextsep + self.pad self.legendPatch = Rectangle( xy=(left, bottom), width=0.5, height=HEIGHT*len(self.texts), facecolor='w', edgecolor='k', ) self._set_artist_props(self.legendPatch) self._drawFrame = True def _set_artist_props(self, a): a.set_figure(self.figure) a.set_transform(self._transform) def _approx_text_height(self): return self.fontsize/72.0*self.figure.dpi.get()/self.parent.bbox.height() def draw(self, renderer): if not self.get_visible(): return renderer.open_group('legend') self._update_positions(renderer) if self._drawFrame: if self.shadow: shadow = Shadow(self.legendPatch, -0.005, -0.005) shadow.draw(renderer) self.legendPatch.draw(renderer) for h in self.handles: if h is not None: h.draw(renderer) if 0: bbox_artist(h, renderer) for t in self.texts: if 0: bbox_artist(t, renderer) t.draw(renderer) renderer.close_group('legend') #draw_bbox(self.save, renderer, 'g') #draw_bbox(self.ibox, renderer, 'r', self._transform) def _get_handle_text_bbox(self, renderer): 'Get a bbox for the text and lines in axes coords' bboxesText = [t.get_window_extent(renderer) for t in self.texts] bboxesHandles = [h.get_window_extent(renderer) for h in self.handles if h is not None] bboxesAll = bboxesText bboxesAll.extend(bboxesHandles) bbox = bbox_all(bboxesAll) self.save = bbox ibox = inverse_transform_bbox(self._transform, bbox) self.ibox = ibox return ibox def _get_handles(self, handles, texts): HEIGHT = self._approx_text_height() ret = [] # the returned legend lines for handle, label in zip(handles, texts): x, y = label.get_position() x -= self.handlelen + self.handletextsep if isinstance(handle, Line2D): ydata = (y-HEIGHT/2)*ones(self._xdata.shape, Float) legline = Line2D(self._xdata, ydata) self._set_artist_props(legline) legline.copy_properties(handle) legline.set_markersize(self.markerscale*legline.get_markersize()) legline.set_data_clipping(False) ret.append(legline) elif isinstance(handle, Patch): p = Rectangle(xy=(min(self._xdata), y-3/4*HEIGHT), width = self.handlelen, height=HEIGHT/2, ) p.copy_properties(handle) self._set_artist_props(p) ret.append(p) elif isinstance(handle, LineCollection): ydata = (y-HEIGHT/2)*ones(self._xdata.shape, Float) legline = Line2D(self._xdata, ydata) self._set_artist_props(legline) lw = handle.get_linewidths()[0] color = handle.get_colors()[0] legline.set_color(color) legline.set_linewidth(lw) ret.append(legline) else: ret.append(None) return ret def draw_frame(self, b): 'b is a boolean. Set draw frame to b' self._drawFrame = b def get_frame(self): 'return the Rectangle instance used to frame the legend' return self.legendPatch def get_lines(self): 'return a list of lines.Line2D instances in the legend' return [h for h in self.handles if isinstance(h, Line2D)] def get_patches(self): 'return a list of patch instances in the legend' return silent_list('Patch', [h for h in self.handles if isinstance(h, Patch)]) def get_texts(self): 'return a list of text.Text instance in the legend' return silent_list('Text', self.texts) def _get_texts(self, labels, left, upper): # height in axes coords HEIGHT = self._approx_text_height() pos = upper x = left ret = [] # the returned list of text instances for l in labels: text = Text( x=x, y=pos, text=l, fontproperties=self.prop, verticalalignment='top', horizontalalignment='left', ) self._set_artist_props(text) ret.append(text) pos -= HEIGHT return ret def get_window_extent(self): return self.legendPatch.get_window_extent() def _offset(self, ox, oy): 'Move all the artists by ox,oy (axes coords)' for t in self.texts: x,y = t.get_position() t.set_position( (x+ox, y+oy) ) for h in self.handles: if isinstance(h, Line2D): x,y = h.get_xdata(), h.get_ydata() h.set_data( x+ox, y+oy) elif isinstance(h, Rectangle): h.xy[0] = h.xy[0] + ox h.xy[1] = h.xy[1] + oy x, y = self.legendPatch.get_x(), self.legendPatch.get_y() self.legendPatch.set_x(x+ox) self.legendPatch.set_y(y+oy) def _update_positions(self, renderer): # called from renderer to allow more precise estimates of # widths and heights with get_window_extent def get_tbounds(text): #get text bounds in axes coords bbox = text.get_window_extent(renderer) bboxa = inverse_transform_bbox(self._transform, bbox) return bboxa.get_bounds() hpos = [] for t, tabove in zip(self.texts[1:], self.texts[:-1]): x,y = t.get_position() l,b,w,h = get_tbounds(tabove) hpos.append( (b,h) ) t.set_position( (x, b-0.1*h) ) # now do the same for last line l,b,w,h = get_tbounds(self.texts[-1]) hpos.append( (b,h) ) for handle, tup in zip(self.handles, hpos): y,h = tup if isinstance(handle, Line2D): ydata = y*ones(self._xdata.shape, Float) handle.set_ydata(ydata+h/2) elif isinstance(handle, Rectangle): handle.set_y(y+1/4*h) handle.set_height(h/2) # Set the data for the legend patch bbox = self._get_handle_text_bbox(renderer).deepcopy() bbox.scale(1 + self.pad, 1 + self.pad) l,b,w,h = bbox.get_bounds() self.legendPatch.set_bounds(l,b,w,h) BEST, UR, UL, LL, LR, R, CL, CR, LC, UC, C = range(11) ox, oy = 0, 0 # center if iterable(self._loc) and len(self._loc)==2: xo = self.legendPatch.get_x() yo = self.legendPatch.get_y() x, y = self._loc ox = x-xo oy = y-yo self._offset(ox, oy) else: if self._loc in (UL, LL, CL): # left ox = self.axespad - l if self._loc in (BEST, UR, LR, R, CR): # right ox = 1 - (l + w + self.axespad) if self._loc in (BEST, UR, UL, UC): # upper oy = 1 - (b + h + self.axespad) if self._loc in (LL, LR, LC): # lower oy = self.axespad - b if self._loc in (LC, UC, C): # center x ox = (0.5-w/2)-l if self._loc in (CL, CR, C): # center y oy = (0.5-h/2)-b self._offset(ox, oy)
def __init__(self, ax, onselect, drawtype='box', minspanx=None, minspany=None, useblit=False, lineprops=None, rectprops=None, spancoords='data', button=None): """ Create a selector in ax. When a selection is made, clear the span and call onselect with onselect(pos_1, pos_2) and clear the drawn box/line. There pos_i are arrays of length 2 containing the x- and y-coordinate. If minspanx is not None then events smaller than minspanx in x direction are ignored(it's the same for y). The rect is drawn with rectprops; default rectprops = dict(facecolor='red', edgecolor = 'black', alpha=0.5, fill=False) The line is drawn with lineprops; default lineprops = dict(color='black', linestyle='-', linewidth = 2, alpha=0.5) Use type if you want the mouse to draw a line, a box or nothing between click and actual position ny setting drawtype = 'line', drawtype='box' or drawtype = 'none'. spancoords is one of 'data' or 'pixels'. If 'data', minspanx and minspanx will be interpreted in the same coordinates as the x and ya axis, if 'pixels', they are in pixels button is a list of integers indicating which mouse buttons should be used for rectangle selection. You can also specify a single integer if only a single button is desired. Default is None, which does not limit which button can be used. Note, typically: 1 = left mouse button 2 = center mouse button (scroll wheel) 3 = right mouse button """ self.ax = ax self.visible = True 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.active = True # for activation / deactivation self.to_draw = None self.background = None if drawtype == 'none': drawtype = 'line' # draw a line but make it self.visible = False # invisible if drawtype == 'box': if rectprops is None: rectprops = dict(facecolor='white', edgecolor = 'black', alpha=0.5, fill=False) self.rectprops = rectprops self.to_draw = Rectangle((0,0), 0, 1,visible=False,**self.rectprops) self.ax.add_patch(self.to_draw) if drawtype == 'line': if lineprops is None: lineprops = dict(color='black', linestyle='-', linewidth = 2, alpha=0.5) self.lineprops = lineprops self.to_draw = Line2D([0,0],[0,0],visible=False,**self.lineprops) self.ax.add_line(self.to_draw) self.onselect = onselect self.useblit = useblit self.minspanx = minspanx self.minspany = minspany if button is None or isinstance(button, list): self.validButtons = button elif isinstance(button, int): self.validButtons = [button] assert(spancoords in ('data', 'pixels')) self.spancoords = spancoords self.drawtype = drawtype # will save the data (position at mouseclick) self.eventpress = None # will save the data (pos. at mouserelease) self.eventrelease = None
def __init__( self, figsize=None, # defaults to rc figure.figsize dpi=None, # defaults to rc figure.dpi facecolor=None, # defaults to rc figure.facecolor edgecolor=None, # defaults to rc figure.edgecolor linewidth=0.0, # the default linewidth of the frame frameon=True, # whether or not to draw the figure frame subplotpars=None, # default to rc ): """ *figsize* w,h tuple in inches *dpi* dots per inch *facecolor* the figure patch facecolor; defaults to rc ``figure.facecolor`` *edgecolor* the figure patch edge color; defaults to rc ``figure.edgecolor`` *linewidth* the figure patch edge linewidth; the default linewidth of the frame *frameon* if ``False``, suppress drawing the figure frame *subplotpars* a :class:`SubplotParams` instance, defaults to rc """ Artist.__init__(self) self.callbacks = cbook.CallbackRegistry() if figsize is None: figsize = rcParams['figure.figsize'] if dpi is None: dpi = rcParams['figure.dpi'] if facecolor is None: facecolor = rcParams['figure.facecolor'] if edgecolor is None: edgecolor = rcParams['figure.edgecolor'] self.dpi_scale_trans = Affine2D() self.dpi = dpi self.bbox_inches = Bbox.from_bounds(0, 0, *figsize) self.bbox = TransformedBbox(self.bbox_inches, self.dpi_scale_trans) self.frameon = frameon self.transFigure = BboxTransformTo(self.bbox) # the figurePatch name is deprecated self.patch = self.figurePatch = Rectangle( xy=(0, 0), width=1, height=1, facecolor=facecolor, edgecolor=edgecolor, linewidth=linewidth, ) self._set_artist_props(self.patch) self.patch.set_aa(False) self._hold = rcParams['axes.hold'] self.canvas = None if subplotpars is None: subplotpars = SubplotParams() self.subplotpars = subplotpars self._axstack = AxesStack() # track all figure axes and current axes self.clf() self._cachedRenderer = None
class SpanSelector: """ Select a min/max range of the x or y axes for a matplotlib Axes Example usage: ax = subplot(111) ax.plot(x,y) def onselect(vmin, vmax): print vmin, vmax span = SpanSelector(ax, onselect, 'horizontal') onmove_callback is an optional callback that will be called on mouse move with the span range """ def __init__(self, ax, onselect, direction, minspan=None, useblit=False, rectprops=None, onmove_callback=None): """ Create a span selector in ax. When a selection is made, clear the span and call onselect with onselect(vmin, vmax) and clear the span. direction must be 'horizontal' or 'vertical' If minspan is not None, ignore events smaller than minspan The span rect is drawn with rectprops; default rectprops = dict(facecolor='red', alpha=0.5) set the visible attribute to False if you want to turn off the functionality of the span selector """ if rectprops is None: rectprops = dict(facecolor='red', alpha=0.5) assert direction in ['horizontal', 'vertical'], 'Must choose horizontal or vertical for direction' self.direction = direction self.ax = None self.canvas = None self.visible = True self.cids=[] self.rect = None self.background = None self.pressv = None self.rectprops = rectprops self.onselect = onselect self.onmove_callback = onmove_callback self.useblit = useblit self.minspan = minspan # Needed when dragging out of axes self.buttonDown = False self.prev = (0, 0) self.new_axes(ax) def new_axes(self,ax): self.ax = ax if self.canvas is not ax.figure.canvas: for cid in self.cids: self.canvas.mpl_disconnect(cid) self.canvas = ax.figure.canvas self.cids.append(self.canvas.mpl_connect('motion_notify_event', self.onmove)) self.cids.append(self.canvas.mpl_connect('button_press_event', self.press)) self.cids.append(self.canvas.mpl_connect('button_release_event', self.release)) self.cids.append(self.canvas.mpl_connect('draw_event', self.update_background)) if self.direction == 'horizontal': trans = blended_transform_factory(self.ax.transData, self.ax.transAxes) w,h = 0,1 else: trans = blended_transform_factory(self.ax.transAxes, self.ax.transData) w,h = 1,0 self.rect = Rectangle( (0,0), w, h, transform=trans, visible=False, **self.rectprops ) if not self.useblit: self.ax.add_patch(self.rect) 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' return event.inaxes!=self.ax or not self.visible or event.button !=1 def press(self, event): 'on button press event' if self.ignore(event): return self.buttonDown = True self.rect.set_visible(self.visible) if self.direction == 'horizontal': self.pressv = event.xdata else: self.pressv = event.ydata return False def release(self, event): 'on button release event' if self.pressv is None or (self.ignore(event) and not self.buttonDown): return self.buttonDown = False self.rect.set_visible(False) self.canvas.draw() vmin = self.pressv if self.direction == 'horizontal': vmax = event.xdata or self.prev[0] else: vmax = event.ydata or self.prev[1] if vmin>vmax: vmin, vmax = vmax, vmin span = vmax - vmin if self.minspan is not None and span<self.minspan: return self.onselect(vmin, vmax) self.pressv = None return False 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.rect) self.canvas.blit(self.ax.bbox) else: self.canvas.draw_idle() return False def onmove(self, event): 'on motion notify event' if self.pressv is None or self.ignore(event): return x, y = event.xdata, event.ydata self.prev = x, y if self.direction == 'horizontal': v = x else: v = y minv, maxv = v, self.pressv if minv>maxv: minv, maxv = maxv, minv if self.direction == 'horizontal': self.rect.set_x(minv) self.rect.set_width(maxv-minv) else: self.rect.set_y(minv) self.rect.set_height(maxv-minv) if self.onmove_callback is not None: vmin = self.pressv if self.direction == 'horizontal': vmax = event.xdata or self.prev[0] else: vmax = event.ydata or self.prev[1] if vmin>vmax: vmin, vmax = vmax, vmin self.onmove_callback(vmin, vmax) self.update() return False
class Legend(Artist): """ Place a legend on the axes at location loc. Labels are a sequence of strings and loc can be a string or an integer specifying the legend location The location codes are 'best' : 0, 'upper right' : 1, (default) 'upper left' : 2, 'lower left' : 3, 'lower right' : 4, 'right' : 5, 'center left' : 6, 'center right' : 7, 'lower center' : 8, 'upper center' : 9, 'center' : 10, Return value is a sequence of text, line instances that make up the legend """ codes = {'best' : 0, 'upper right' : 1, # default 'upper left' : 2, 'lower left' : 3, 'lower right' : 4, 'right' : 5, 'center left' : 6, 'center right' : 7, 'lower center' : 8, 'upper center' : 9, 'center' : 10, } def __init__(self, parent, handles, labels, loc, isaxes= None, numpoints = None, # the number of points in the legend line prop = None, pad = None, # the fractional whitespace inside the legend border markerscale = None, # the relative size of legend markers vs. original # the following dimensions are in axes coords labelsep = None, # the vertical space between the legend entries handlelen = None, # the length of the legend lines handletextsep = None, # the space between the legend line and legend text axespad = None, # the border between the axes and legend edge shadow= None, ): """ parent # the artist that contains the legend handles # a list of artists (lines, patches) to add to the legend labels # a list of strings to label the legend loc # a location code isaxes=True # whether this is an axes legend numpoints = 4 # the number of points in the legend line fontprop = FontProperties(size='smaller') # the font property pad = 0.2 # the fractional whitespace inside the legend border markerscale = 0.6 # the relative size of legend markers vs. original shadow # if True, draw a shadow behind legend The following dimensions are in axes coords labelsep = 0.005 # the vertical space between the legend entries handlelen = 0.05 # the length of the legend lines handletextsep = 0.02 # the space between the legend line and legend text axespad = 0.02 # the border between the axes and legend edge """ Artist.__init__(self) if is_string_like(loc) and not self.codes.has_key(loc): warnings.warn('Unrecognized location %s. Falling back on upper right; valid locations are\n%s\t' %(loc, '\n\t'.join(self.codes.keys()))) if is_string_like(loc): loc = self.codes.get(loc, 1) proplist=[numpoints, pad, markerscale, labelsep, handlelen, handletextsep, axespad, shadow, isaxes] propnames=['numpoints', 'pad', 'markerscale', 'labelsep', 'handlelen', 'handletextsep', 'axespad', 'shadow', 'isaxes'] for name, value in zip(propnames,proplist): if value is None: value=rcParams["legend."+name] setattr(self,name,value) if prop is None: self.prop=FontProperties(size=rcParams["legend.fontsize"]) else: self.prop=prop self.fontsize = self.prop.get_size_in_points() if self.isaxes: # parent is an Axes self.set_figure(parent.figure) else: # parent is a Figure self.set_figure(parent) self.parent = parent self.set_transform( get_bbox_transform( unit_bbox(), parent.bbox) ) self._loc = loc # make a trial box in the middle of the axes. relocate it # based on it's bbox left, top = 0.5, 0.5 if self.numpoints == 1: self._xdata = array([left + self.handlelen*0.5]) else: self._xdata = linspace(left, left + self.handlelen, self.numpoints) textleft = left+ self.handlelen+self.handletextsep self.texts = self._get_texts(labels, textleft, top) self.legendHandles = self._get_handles(handles, self.texts) if len(self.texts): left, top = self.texts[-1].get_position() HEIGHT = self._approx_text_height()*len(self.texts) else: HEIGHT = 0.2 bottom = top-HEIGHT left -= self.handlelen + self.handletextsep + self.pad self.legendPatch = Rectangle( xy=(left, bottom), width=0.5, height=HEIGHT, facecolor='w', edgecolor='k', ) self._set_artist_props(self.legendPatch) self._drawFrame = True def _set_artist_props(self, a): a.set_figure(self.figure) a.set_transform(self._transform) def _approx_text_height(self): return self.fontsize/72.0*self.figure.dpi.get()/self.parent.bbox.height() def draw(self, renderer): if not self.get_visible(): return renderer.open_group('legend') self._update_positions(renderer) if self._drawFrame: if self.shadow: shadow = Shadow(self.legendPatch, -0.005, -0.005) shadow.draw(renderer) self.legendPatch.draw(renderer) if not len(self.legendHandles) and not len(self.texts): return for h in self.legendHandles: if h is not None: h.draw(renderer) if 0: bbox_artist(h, renderer) for t in self.texts: if 0: bbox_artist(t, renderer) t.draw(renderer) renderer.close_group('legend') #draw_bbox(self.save, renderer, 'g') #draw_bbox(self.ibox, renderer, 'r', self._transform) def _get_handle_text_bbox(self, renderer): 'Get a bbox for the text and lines in axes coords' bboxesText = [t.get_window_extent(renderer) for t in self.texts] bboxesHandles = [h.get_window_extent(renderer) for h in self.legendHandles if h is not None] bboxesAll = bboxesText bboxesAll.extend(bboxesHandles) bbox = bbox_all(bboxesAll) self.save = bbox ibox = inverse_transform_bbox(self._transform, bbox) self.ibox = ibox return ibox def _get_handles(self, handles, texts): HEIGHT = self._approx_text_height() ret = [] # the returned legend lines for handle, label in zip(handles, texts): x, y = label.get_position() x -= self.handlelen + self.handletextsep if isinstance(handle, Line2D): ydata = (y-HEIGHT/2)*ones(self._xdata.shape, Float) legline = Line2D(self._xdata, ydata) legline.update_from(handle) self._set_artist_props(legline) # after update legline.set_clip_box(None) legline.set_markersize(self.markerscale*legline.get_markersize()) ret.append(legline) elif isinstance(handle, Patch): p = Rectangle(xy=(min(self._xdata), y-3/4*HEIGHT), width = self.handlelen, height=HEIGHT/2, ) p.update_from(handle) self._set_artist_props(p) p.set_clip_box(None) ret.append(p) elif isinstance(handle, LineCollection): ydata = (y-HEIGHT/2)*ones(self._xdata.shape, Float) legline = Line2D(self._xdata, ydata) self._set_artist_props(legline) legline.set_clip_box(None) lw = handle.get_linewidth()[0] dashes = handle.get_dashes() color = handle.get_colors()[0] legline.set_color(color) legline.set_linewidth(lw) legline.set_dashes(dashes) ret.append(legline) elif isinstance(handle, RegularPolyCollection): p = Rectangle(xy=(min(self._xdata), y-3/4*HEIGHT), width = self.handlelen, height=HEIGHT/2, ) p.set_facecolor(handle._facecolors[0]) if handle._edgecolors != 'None': p.set_edgecolor(handle._edgecolors[0]) self._set_artist_props(p) p.set_clip_box(None) ret.append(p) else: ret.append(None) return ret def _auto_legend_data(self): """ Returns list of vertices and extents covered by the plot. Returns a two long list. First element is a list of (x, y) vertices (in axes-coordinates) covered by all the lines and line collections, in the legend's handles. Second element is a list of bounding boxes for all the patches in the legend's handles. """ if not self.isaxes: raise Exception, 'Auto legends not available for figure legends.' def get_handles(ax): handles = ax.lines handles.extend(ax.patches) handles.extend([c for c in ax.collections if isinstance(c, LineCollection)]) return handles ax = self.parent handles = get_handles(ax) vertices = [] bboxes = [] lines = [] inv = ax.transAxes.inverse_xy_tup for handle in handles: if isinstance(handle, Line2D): xdata = handle.get_xdata(valid_only = True) ydata = handle.get_ydata(valid_only = True) trans = handle.get_transform() xt, yt = trans.numerix_x_y(xdata, ydata) # XXX need a special method in transform to do a list of verts averts = [inv(v) for v in zip(xt, yt)] lines.append(averts) elif isinstance(handle, Patch): verts = handle.get_verts() trans = handle.get_transform() tverts = trans.seq_xy_tups(verts) averts = [inv(v) for v in tverts] bbox = unit_bbox() bbox.update(averts, True) bboxes.append(bbox) elif isinstance(handle, LineCollection): hlines = handle.get_lines() trans = handle.get_transform() for line in hlines: tline = trans.seq_xy_tups(line) aline = [inv(v) for v in tline] lines.extend(line) return [vertices, bboxes, lines] def draw_frame(self, b): 'b is a boolean. Set draw frame to b' self._drawFrame = b def get_frame(self): 'return the Rectangle instance used to frame the legend' return self.legendPatch def get_lines(self): 'return a list of lines.Line2D instances in the legend' return [h for h in self.legendHandles if isinstance(h, Line2D)] def get_patches(self): 'return a list of patch instances in the legend' return silent_list('Patch', [h for h in self.legendHandles if isinstance(h, Patch)]) def get_texts(self): 'return a list of text.Text instance in the legend' return silent_list('Text', self.texts) def _get_texts(self, labels, left, upper): # height in axes coords HEIGHT = self._approx_text_height() pos = upper x = left ret = [] # the returned list of text instances for l in labels: text = Text( x=x, y=pos, text=l, fontproperties=self.prop, verticalalignment='top', horizontalalignment='left', ) self._set_artist_props(text) ret.append(text) pos -= HEIGHT return ret def get_window_extent(self): return self.legendPatch.get_window_extent() def _offset(self, ox, oy): 'Move all the artists by ox,oy (axes coords)' for t in self.texts: x,y = t.get_position() t.set_position( (x+ox, y+oy) ) for h in self.legendHandles: if isinstance(h, Line2D): x,y = h.get_xdata(valid_only = True), h.get_ydata(valid_only = True) h.set_data( x+ox, y+oy) elif isinstance(h, Rectangle): h.xy[0] = h.xy[0] + ox h.xy[1] = h.xy[1] + oy elif isinstance(h, RegularPolygon): h.verts = [(x + ox, y + oy) for x, y in h.verts] x, y = self.legendPatch.get_x(), self.legendPatch.get_y() self.legendPatch.set_x(x+ox) self.legendPatch.set_y(y+oy) def _find_best_position(self, width, height, consider=None): """Determine the best location to place the legend. `consider` is a list of (x, y) pairs to consider as a potential lower-left corner of the legend. All are axes coords. """ verts, bboxes, lines = self._auto_legend_data() consider = [self._loc_to_axes_coords(x, width, height) for x in range(1, len(self.codes))] tx, ty = self.legendPatch.xy candidates = [] for l, b in consider: legendBox = lbwh_to_bbox(l, b, width, height) badness = 0 badness = legendBox.count_contains(verts) ox, oy = l-tx, b-ty for bbox in bboxes: if legendBox.overlaps(bbox): badness += 1 for line in lines: if line_cuts_bbox(line, legendBox): badness += 1 if badness == 0: return ox, oy candidates.append((badness, (ox, oy))) # rather than use min() or list.sort(), do this so that we are assured # that in the case of two equal badnesses, the one first considered is # returned. minCandidate = candidates[0] for candidate in candidates: if candidate[0] < minCandidate[0]: minCandidate = candidate ox, oy = minCandidate[1] return ox, oy def _loc_to_axes_coords(self, loc, width, height): """Convert a location code to axes coordinates. - loc: a location code, which may be a pair of literal axes coords, or in range(1, 11). This coresponds to the possible values for self._loc, excluding "best". - width, height: the final size of the legend, axes units. """ BEST, UR, UL, LL, LR, R, CL, CR, LC, UC, C = range(11) left = self.axespad right = 1.0 - (self.axespad + width) upper = 1.0 - (self.axespad + height) lower = self.axespad centerx = 0.5 - (width/2.0) centery = 0.5 - (height/2.0) if loc == UR: return right, upper if loc == UL: return left, upper if loc == LL: return left, lower if loc == LR: return right, lower if loc == CL: return left, centery if loc in (CR, R): return right, centery if loc == LC: return centerx, lower if loc == UC: return centerx, upper if loc == C: return centerx, centery raise TypeError, "%r isn't an understood type code." % (loc,) def _update_positions(self, renderer): # called from renderer to allow more precise estimates of # widths and heights with get_window_extent if not len(self.legendHandles) and not len(self.texts): return def get_tbounds(text): #get text bounds in axes coords bbox = text.get_window_extent(renderer) bboxa = inverse_transform_bbox(self._transform, bbox) return bboxa.get_bounds() hpos = [] for t, tabove in zip(self.texts[1:], self.texts[:-1]): x,y = t.get_position() l,b,w,h = get_tbounds(tabove) b -= self.labelsep h += 2*self.labelsep hpos.append( (b,h) ) t.set_position( (x, b-0.1*h) ) # now do the same for last line l,b,w,h = get_tbounds(self.texts[-1]) b -= self.labelsep h += 2*self.labelsep hpos.append( (b,h) ) for handle, tup in zip(self.legendHandles, hpos): y,h = tup if isinstance(handle, Line2D): ydata = y*ones(self._xdata.shape, Float) handle.set_ydata(ydata+h/2) elif isinstance(handle, Rectangle): handle.set_y(y+1/4*h) handle.set_height(h/2) # Set the data for the legend patch bbox = self._get_handle_text_bbox(renderer).deepcopy() bbox.scale(1 + self.pad, 1 + self.pad) l,b,w,h = bbox.get_bounds() self.legendPatch.set_bounds(l,b,w,h) BEST, UR, UL, LL, LR, R, CL, CR, LC, UC, C = range(11) ox, oy = 0, 0 # center if iterable(self._loc) and len(self._loc)==2: xo = self.legendPatch.get_x() yo = self.legendPatch.get_y() x, y = self._loc ox = x-xo oy = y-yo self._offset(ox, oy) else: if self._loc in (BEST,): ox, oy = self._find_best_position(w, h) if self._loc in (UL, LL, CL): # left ox = self.axespad - l if self._loc in (UR, LR, R, CR): # right ox = 1 - (l + w + self.axespad) if self._loc in (UR, UL, UC): # upper oy = 1 - (b + h + self.axespad) if self._loc in (LL, LR, LC): # lower oy = self.axespad - b if self._loc in (LC, UC, C): # center x ox = (0.5-w/2)-l if self._loc in (CL, CR, C): # center y oy = (0.5-h/2)-b self._offset(ox, oy)