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 _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, 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 __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, 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 _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, 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 __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, 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, 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 _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 _get_handles(self, handles, texts): HEIGHT = self._approx_text_height() left = 0.5 ret = [] # the returned legend lines for handle, label in zip(handles, texts): if self.numpoints > 1: xdata = np.linspace(left, left + self.handlelen, self.numpoints) elif self.numpoints == 1: xdata = np.linspace(left, left + self.handlelen, 2) x, y = label.get_position() x -= self.handlelen + self.handletextsep if isinstance(handle, Line2D): if self.numpoints == 1 and handle._marker != 'None': xdata = np.array([left + self.handlelen*0.5]) 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) legline.set_markersize(self.markerscale*legline.get_markersize()) ret.append(legline) 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 __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, 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 __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
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