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 plot_day_summary(ax, quotes, ticksize=3, colorup='k', colordown='r', ): """ quotes is a list of (time, open, close, high, low, ...) tuples Represent the time, open, close, high, low as a vertical line ranging from low to high. The left tick is the open and the right tick is the close. time must be in float date format - see date2num ax : an Axes instance to plot to ticksize : open/close tick marker in points colorup : the color of the lines where close >= open colordown : the color of the lines where close < open return value is a list of lines added """ lines = [] for q in quotes: t, open, close, high, low = q[:5] if close>=open : color = colorup else : color = colordown vline = Line2D( xdata=(t, t), ydata=(low, high), color=color, antialiased=False, # no need to antialias vert lines ) oline = Line2D( xdata=(t, t), ydata=(open, open), color=color, antialiased=False, marker=TICKLEFT, markersize=ticksize, ) cline = Line2D( xdata=(t, t), ydata=(close, close), color=color, antialiased=False, markersize=ticksize, marker=TICKRIGHT) lines.extend((vline, oline, cline)) ax.add_line(vline) ax.add_line(oline) ax.add_line(cline) ax.autoscale_view() return lines
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 _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 _get_tick2line(self, loc): 'Get the default line2D instance' # x in axes coords, y in data coords l = Line2D( (1, 1), (0, 0), color='k', antialiased=False, marker = TICKLEFT, markersize=self._size, ) l.set_transform( blend_xy_sep_transform( self.axes.transAxes, self.axes.transData) ) self._set_artist_props(l) return l
def _get_tick1line(self, loc): 'Get the default line2D instance' # x in axes coords, y in data coords l = Line2D( (0,), (loc,), color='k', antialiased=False, marker = self._ytickmarkers[0], linestyle = 'None', markersize=self._size, ) l.set_transform( blend_xy_sep_transform( self.axes.transAxes, self.axes.transData) ) self._set_artist_props(l) return l
def _get_gridline(self, loc): 'Get the default line2D instance' # x in data coords, y in axes coords l = Line2D( xdata=(loc, loc), ydata=(0, 1), color=rcParams['grid.color'], linestyle=rcParams['grid.linestyle'], linewidth=rcParams['grid.linewidth'], antialiased=False, ) l.set_transform( blend_xy_sep_transform( self.axes.transData, self.axes.transAxes) ) l.set_clip_box(self.axes.bbox) self._set_artist_props(l) return l
def _get_tick2line(self, loc): 'Get the default line2D instance' # x in data coords, y in axes coords l = Line2D( xdata=(loc, loc), ydata=(1,1), color='k', linestyle = 'None', antialiased=False, marker = TICKDOWN, markersize=self._size, ) l.set_transform( blend_xy_sep_transform( self.axes.transData, self.axes.transAxes) ) self._set_artist_props(l) return l
def __init__( self, x=0, y=0, text='', color=None, # defaults to rc params verticalalignment='center', horizontalalignment='center', multialignment=None, fontproperties=None, # defaults to FontProperties() rotation=None, linespacing=None, dashlength=0.0, dashdirection=0, dashrotation=None, dashpad=3, dashpush=0, xaxis=True, ): Text.__init__(self, x=x, y=y, text=text, color=color, verticalalignment=verticalalignment, horizontalalignment=horizontalalignment, multialignment=multialignment, fontproperties=fontproperties, rotation=rotation, linespacing=linespacing) # The position (x,y) values for text and dashline # are bogus as given in the instantiation; they will # be set correctly by update_coords() in draw() self.dashline = Line2D(xdata=(x, x), ydata=(y, y), color='k', linestyle='-') self._dashx = float(x) self._dashy = float(y) self._dashlength = dashlength self._dashdirection = dashdirection self._dashrotation = dashrotation self._dashpad = dashpad self._dashpush = dashpush
def __init__(self, ax, xy, callback=None, useblit=True): self.axes = ax self.figure = ax.figure self.canvas = self.figure.canvas self.useblit = useblit if useblit: self.background = self.canvas.copy_from_bbox(self.axes.bbox) x, y = xy self.verts = [(x,y)] self.line = Line2D([x], [y], linestyle='-', color='black', lw=2) self.axes.add_line(self.line) self.callback = callback self.cids = [] self.cids.append(self.canvas.mpl_connect('button_release_event', self.onrelease)) self.cids.append(self.canvas.mpl_connect('motion_notify_event', self.onmove))
def __init__(self, poly): if poly.figure is None: raise RuntimeError( 'You must first add the polygon to a figure or canvas before defining the interactor' ) canvas = poly.figure.canvas self.poly = poly self.poly.verts = list(self.poly.verts) x, y = zip(*self.poly.verts) self.line = Line2D(x, y, marker='o', markerfacecolor='r') #self._update_line(poly) cid = self.poly.add_callback(self.poly_changed) self._ind = None # the active vert canvas.mpl_connect('button_press_event', self.button_press_callback) canvas.mpl_connect('key_press_event', self.key_press_callback) canvas.mpl_connect('button_release_event', self.button_release_callback) canvas.mpl_connect('motion_notify_event', self.motion_notify_callback) self.canvas = canvas
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 _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 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', 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 _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