def hbar(plot, p, values, colors=None, height=16, xoff=0, yoff=0, halign=1, valign=0.5, xycoords='data', boxcoords=('offset points')): x, y = _xy(plot, p) h = height w = sum(values) * height #; yoff=h*0.5 da = DrawingArea(w, h) x0 = -sum(values) if not colors: c = _colors.tango() colors = [c.next() for v in values] for i, v in enumerate(values): if v: da.add_artist(Rectangle((x0, 0), v * h, h, fc=colors[i], ec='none')) x0 += v * h box = AnnotationBbox(da, (x, y), pad=0, frameon=False, xybox=(xoff, yoff), xycoords=xycoords, box_alignment=(halign, valign), boxcoords=boxcoords) plot.add_artist(box) plot.figure.canvas.draw_idle()
def add_offsetboxes(ax, size=10, margin=.1, color='black'): """ Surround ax with OffsetBoxes """ m, mp = margin, 1+margin anchor_points = [(-m, -m), (-m, .5), (-m, mp), (mp, .5), (.5, mp), (mp, mp), (.5, -m), (mp, -m), (.5, -m)] for point in anchor_points: da = DrawingArea(size, size) background = Rectangle((0, 0), width=size, height=size, facecolor=color, edgecolor='None', linewidth=0, antialiased=False) da.add_artist(background) anchored_box = AnchoredOffsetbox( loc='center', child=da, pad=0., frameon=False, bbox_to_anchor=point, bbox_transform=ax.transAxes, borderpad=0.) ax.add_artist(anchored_box) return anchored_box
def add_offsetboxes(ax, size=10, margin=.1, color='black'): """ Surround ax with OffsetBoxes """ m, mp = margin, 1 + margin anchor_points = [(-m, -m), (-m, .5), (-m, mp), (mp, .5), (.5, mp), (mp, mp), (.5, -m), (mp, -m), (.5, -m)] for point in anchor_points: da = DrawingArea(size, size) background = Rectangle((0, 0), width=size, height=size, facecolor=color, edgecolor='None', linewidth=0, antialiased=False) da.add_artist(background) anchored_box = AnchoredOffsetbox(loc=10, child=da, pad=0., frameon=False, bbox_to_anchor=point, bbox_transform=ax.transAxes, borderpad=0.) ax.add_artist(anchored_box) return anchored_box
def test_offsetbox_clipping(): # - create a plot # - put an AnchoredOffsetbox with a child DrawingArea # at the center of the axes # - give the DrawingArea a gray background # - put a black line across the bounds of the DrawingArea # - see that the black line is clipped to the edges of # the DrawingArea. fig, ax = plt.subplots() size = 100 da = DrawingArea(size, size, clip=True) bg = mpatches.Rectangle((0, 0), size, size, facecolor='#CCCCCC', edgecolor='None', linewidth=0) line = mlines.Line2D([-size*.5, size*1.5], [size/2, size/2], color='black', linewidth=10) anchored_box = AnchoredOffsetbox( loc=10, child=da, pad=0., frameon=False, bbox_to_anchor=(.5, .5), bbox_transform=ax.transAxes, borderpad=0.) da.add_artist(bg) da.add_artist(line) ax.add_artist(anchored_box) ax.set_xlim((0, 1)) ax.set_ylim((0, 1))
def pie( plot, p, values, colors=None, size=16, norm=True, xoff=0, yoff=0, halign=0.5, valign=0.5, xycoords="data", boxcoords=("offset points"), ): """ Draw a pie chart Args: plot (Tree): A Tree plot instance p (Node): A Node object values (list): A list of floats. colors (list): A list of strings to pull colors from. Optional. size (float): Diameter of the pie chart norm (bool): Whether or not to normalize the values so they add up to 360 xoff, yoff (float): X and Y offset. Optional, defaults to 0 halign, valign (float): Horizontal and vertical alignment within box. Optional, defaults to 0.5 """ x, y = _xy(plot, p) da = DrawingArea(size, size) r = size * 0.5 center = (r, r) x0 = 0 S = 360.0 if norm: S = 360.0 / sum(values) if not colors: c = _colors.tango() colors = [c.next() for v in values] for i, v in enumerate(values): theta = v * S if v: da.add_artist(Wedge(center, r, x0, x0 + theta, fc=colors[i], ec="none")) x0 += theta box = AnnotationBbox( da, (x, y), pad=0, frameon=False, xybox=(xoff, yoff), xycoords=xycoords, box_alignment=(halign, valign), boxcoords=boxcoords, ) plot.add_artist(box) plot.figure.canvas.draw_idle() return box
def make_gui(img, dataset_name, **kwargs): global alphabet fig = plt.figure(figsize=kwargs["figsize"]) from matplotlib import rcParams rcParams['axes.linewidth'] = 2 rcParams['axes.edgecolor'] = 'k' plt.imshow(img) label_category = cv_label_category if dataset_name == "camvid" else voc_label_category alphabet = alphabet_cv if dataset_name == "camvid" else alphabet_voc vpacker_children = [TextArea("{} - {}".format(alphabet[l], cat), textprops={"weight": 'bold', "size": 10}) for l, cat in sorted(label_category.items(), key=lambda x: x[1])] box = VPacker(children=vpacker_children, align="left", pad=5, sep=5) # display the texts on the right side of image anchored_box = AnchoredOffsetbox(loc="center left", child=box, pad=0., frameon=True, bbox_to_anchor=(1.04, 0.5), bbox_transform=plt.gca().transAxes, borderpad=0.) anchored_box.patch.set_linewidth(2) anchored_box.patch.set_facecolor('gray') anchored_box.patch.set_alpha(0.2) anchored_box.patch.set_boxstyle("round,pad=0.5, rounding_size=0.2") plt.gca().add_artist(anchored_box) # create texts for "Enter a label for the current marker" box1 = TextArea("Enter a label for the current marker", textprops={"weight": 'bold', "size": 12}) box2 = DrawingArea(5, 10, 0, 0) box2.add_artist(mpatches.Circle((5, 5), radius=5, fc=np.array((1, 0, 0)), edgecolor="k", lw=1.5)) box = HPacker(children=[box1, box2], align="center", pad=5, sep=5) # anchored_box creates the text box outside of the plot anchored_box = AnchoredOffsetbox(loc="lower center", child=box, pad=0., frameon=False, bbox_to_anchor=(0.5, -0.1), # ( 0.5, -0.1) bbox_transform=plt.gca().transAxes, borderpad=0.) plt.gca().add_artist(anchored_box) plt.xticks([]) plt.yticks([]) plt.tight_layout(pad=2) buf = io.BytesIO() fig.savefig(buf, format="jpg", dpi=80) buf.seek(0) img_arr = np.frombuffer(buf.getvalue(), dtype=np.uint8) buf.close() im = cv2.imdecode(img_arr, 1) plt.close() return im
def __init__(self, width, height, xdescent, ydescent): self.area = DrawingArea(width, height, xdescent, ydescent) super().__init__(loc="upper right", pad=0.4, borderpad=0.5, child=self.area, prop=None, frameon=True)
def make_shape(color, shape, size, alpha, y_offset = 10, height = 20): color = color if color != None else "k" # Default value if None shape = shape if shape != None else "o" size = size*0.6+45 if size != None else 75 viz = DrawingArea(30, height, 8, 1) key = mlines.Line2D([0], [y_offset], marker=shape, markersize=size/12.0, mec=color, c=color, alpha=alpha) viz.add_artist(key) return viz
def make_line_key(label, color): label = str(label) idx = len(label) pad = 20 - idx lab = label[:max(idx, 20)] pad = " "*pad label = TextArea(" %s" % lab, textprops=dict(color="k")) viz = DrawingArea(20, 20, 0, 0) viz.add_artist(Rectangle((0, 5), width=16, height=5, fc=color)) return HPacker(children=[viz, label], height=25, align="center", pad=5, sep=0)
def pie(plot, p, values, colors=None, size=16, norm=True, xoff=0, yoff=0, halign=0.5, valign=0.5, xycoords='data', boxcoords=('offset points')): """ Draw a pie chart Args: plot (Tree): A Tree plot instance p (Node): A Node object values (list): A list of floats. colors (list): A list of strings to pull colors from. Optional. size (float): Diameter of the pie chart norm (bool): Whether or not to normalize the values so they add up to 360 xoff, yoff (float): X and Y offset. Optional, defaults to 0 halign, valign (float): Horizontal and vertical alignment within box. Optional, defaults to 0.5 """ x, y = _xy(plot, p) da = DrawingArea(size, size) r = size * 0.5 center = (r, r) x0 = 0 S = 360.0 if norm: S = 360.0 / sum(values) if not colors: c = _colors.tango() colors = [c.next() for v in values] for i, v in enumerate(values): theta = v * S if v: da.add_artist( Wedge(center, r, x0, x0 + theta, fc=colors[i], ec='none')) x0 += theta box = AnnotationBbox(da, (x, y), pad=0, frameon=False, xybox=(xoff, yoff), xycoords=xycoords, box_alignment=(halign, valign), boxcoords=boxcoords) plot.add_artist(box) plot.figure.canvas.draw_idle() return box
def make_line(color, style, alpha, width = 20, y_offset = 10, height = 20, linewidth = 3): color = color if color != None else "k" # Default value if None style = style if style != None else "-" viz = DrawingArea(30, 10, 0, -5) x = np.arange(0.0, width, width/7.0) y = np.repeat(y_offset, x.size) key = mlines.Line2D(x, y, linestyle=style, linewidth=linewidth, alpha=alpha, c=color) viz.add_artist(key) return viz
def make_marker_key(label, marker): idx = len(label) pad = 20 - idx lab = label[:max(idx, 20)] pad = " "*pad label = TextArea(" %s" % lab, textprops=dict(color="k")) viz = DrawingArea(15, 20, 0, 0) fontsize = 10 key = mlines.Line2D([0.5*fontsize], [0.75*fontsize], marker=marker, markersize=(0.5*fontsize), c="k") viz.add_artist(key) return HPacker(children=[viz, label], align="center", pad=5, sep=0)
def add_faces_to_scatterplot(ax, X, filenames, dataset, img_size, C=None, border_size=3): nx, ny = (16, 10) x = np.linspace(X[:, 0].min(), X[:, 0].max(), nx) y = np.linspace(X[:, 1].min(), X[:, 1].max(), ny) xx,yy = np.meshgrid(x, y) coords = np.hstack([xx.reshape(-1,1), yy.reshape(-1,1)]) from sklearn.neighbors import NearestNeighbors nn = NearestNeighbors().fit(X) max_dist = np.abs(X[:, 0].min() - X[:, 0].max()) / nx faces_to_draw = [] for coord in coords: dists, nbs = nn.kneighbors(np.atleast_2d(coord)) if dists[0][0] < max_dist/2: faces_to_draw.append(nbs[0][0]) # for nImg, img_file in enumerate(filenames): # if (nImg % every_n_img) != 0: # continue for nImg, img_file in enumerate(filenames): if nImg not in faces_to_draw: continue arr_img = dataset.get_face(img_file, size=(img_size,img_size))[0] if C is not None: print(nImg, affectnet.AffectNet.classes[C[nImg]]) da = DrawingArea(img_size+2*border_size, img_size+2*border_size, 0, 0) p = Rectangle((0, 0), img_size + 2 * border_size, img_size + 2 * border_size, color=AffectNet.colors[C[nImg]]) da.add_artist(p) border = AnnotationBbox(da, X[nImg][::], #xybox=(120., -80.), xybox=(0., 0.), xycoords='data', boxcoords="offset points", pad=0.0, arrowprops=dict(arrowstyle="->", connectionstyle="angle,angleA=0,angleB=90,rad=3") ) ax.add_artist(border) im = OffsetImage(arr_img, interpolation='gaussian') ab = AnnotationBbox(im, X[nImg][::], #xybox=(120., -80.), xybox=(0., 0.), xycoords='data', boxcoords="offset points", pad=0.0, arrowprops=dict(arrowstyle="->", connectionstyle="angle,angleA=0,angleB=90,rad=3"), ) ax.add_artist(ab)
def make_shape(color, shape, size, alpha, y_offset=10, height=20): color = color if color != None else "k" # Default value if None shape = shape if shape != None else "o" size = size * 0.6 + 45 if size != None else 75 viz = DrawingArea(30, height, 8, 1) key = mlines.Line2D([0], [y_offset], marker=shape, markersize=size / 12.0, mec=color, c=color, alpha=alpha) viz.add_artist(key) return viz
def make_linestyle_key(label, style): idx = len(label) pad = 20 - idx lab = label[:max(idx, 20)] pad = " "*pad label = TextArea(" %s" % lab, textprops=dict(color="k")) viz = DrawingArea(30, 20, 0, 0) fontsize = 10 x = np.arange(0.5, 2.25, 0.25) * fontsize y = np.repeat(0.75, 7) * fontsize key = mlines.Line2D(x, y, linestyle=style, c="k") viz.add_artist(key) return HPacker(children=[viz, label], align="center", pad=5, sep=0)
def make_marker_key(label, marker): idx = len(label) pad = 20 - idx lab = label[:max(idx, 20)] pad = " " * pad label = TextArea(": %s" % lab, textprops=dict(color="k")) viz = DrawingArea(15, 20, 0, 0) fontsize = 10 key = mlines.Line2D([0.5 * fontsize], [0.75 * fontsize], marker=marker, markersize=(0.5 * fontsize), c="k") viz.add_artist(key) return HPacker(children=[viz, label], align="center", pad=5, sep=0)
def make_line_key(label, color): label = str(label) idx = len(label) pad = 20 - idx lab = label[:max(idx, 20)] pad = " " * pad label = TextArea(": %s" % lab, textprops=dict(color="k")) viz = DrawingArea(20, 20, 0, 0) viz.add_artist(Rectangle((0, 5), width=16, height=5, fc=color)) return HPacker(children=[viz, label], height=25, align="center", pad=5, sep=0)
def make_linestyle_key(label, style): idx = len(label) pad = 20 - idx lab = label[:max(idx, 20)] pad = " " * pad label = TextArea(": %s" % lab, textprops=dict(color="k")) viz = DrawingArea(30, 20, 0, 0) fontsize = 10 x = np.arange(0.5, 2.25, 0.25) * fontsize y = np.repeat(0.75, 7) * fontsize key = mlines.Line2D(x, y, linestyle=style, c="k") viz.add_artist(key) return HPacker(children=[viz, label], align="center", pad=5, sep=0)
def make_size_key(label, size): label = round(label, 2) label = str(label) idx = len(label) pad = 20 - idx lab = label[:max(idx, 20)] pad = " "*pad label = TextArea(": %s" % lab, textprops=dict(color="k")) viz = DrawingArea(15, 20, 0, 0) fontsize = 10 key = mlines.Line2D([0.5*fontsize], [0.75*fontsize], marker="o", markersize=size / 20., c="k") viz.add_artist(key) return HPacker(children=[viz, label], align="center", pad=5, sep=0)
def make_title(title): title = title.title() area = TextArea(" %s " % title, textprops=dict(color="k", fontweight="bold")) viz = DrawingArea(20, 10, 0, 0) packed = VPacker(children=[area, viz], align="center", pad=0, sep=0) return packed
def __init__(self, width, height, xdescent, ydescent, loc, pad=0.4, borderpad=0.5, prop=None, frameon=True, **kwargs): """ *width*, *height*, *xdescent*, *ydescent* : the dimensions of the DrawingArea. *prop* : font property. This is only used for scaling the paddings. """ self.da = DrawingArea(width, height, xdescent, ydescent, clip=True) self.drawing_area = self.da super(AnchoredDrawingArea, self).__init__(loc, pad=pad, borderpad=borderpad, child=self.da, prop=None, frameon=frameon, **kwargs)
def make_size_key(label, size): if not isinstance(label, six.string_types): label = round(label, 2) label = str(label) idx = len(label) pad = 20 - idx lab = label[:max(idx, 20)] pad = " " * pad label = TextArea(" %s" % lab, textprops=dict(color="k")) viz = DrawingArea(15, 20, 0, 0) fontsize = 10 key = mlines.Line2D([0.5 * fontsize], [0.75 * fontsize], marker="o", markersize=size / 20., c="k") viz.add_artist(key) return HPacker(children=[viz, label], align="center", pad=5, sep=0)
def test_offsetbox_clip_children(): # - create a plot # - put an AnchoredOffsetbox with a child DrawingArea # at the center of the axes # - give the DrawingArea a gray background # - put a black line across the bounds of the DrawingArea # - see that the black line is clipped to the edges of # the DrawingArea. fig, ax = plt.subplots() size = 100 da = DrawingArea(size, size, clip=True) bg = mpatches.Rectangle((0, 0), size, size, facecolor='#CCCCCC', edgecolor='None', linewidth=0) line = mlines.Line2D([-size*.5, size*1.5], [size/2, size/2], color='black', linewidth=10) anchored_box = AnchoredOffsetbox( loc='center', child=da, pad=0., frameon=False, bbox_to_anchor=(.5, .5), bbox_transform=ax.transAxes, borderpad=0.) da.add_artist(bg) da.add_artist(line) ax.add_artist(anchored_box) fig.canvas.draw() assert not fig.stale da.clip_children = True assert fig.stale
def __init__(self, width, height, xdescent, ydescent, loc, pad=0.4, borderpad=0.5, prop=None, frameon=True): self.da = DrawingArea(width, height, xdescent, ydescent, clip=True) super(AnchoredDrawingArea, self).__init__(loc, pad=pad, borderpad=borderpad, child=self.da, prop=None, frameon=frameon)
def make_line(color, style, alpha, width=20, y_offset=10, height=20, linewidth=3): color = color if color != None else "k" # Default value if None style = style if style != None else "-" viz = DrawingArea(30, 10, 0, -5) x = np.arange(0.0, width, width / 7.0) y = np.repeat(y_offset, x.size) key = mlines.Line2D(x, y, linestyle=style, linewidth=linewidth, alpha=alpha, c=color) viz.add_artist(key) return viz
def test_arrowprops_copied(): da = DrawingArea(20, 20, 0, 0, clip=True) arrowprops = {"arrowstyle": "->", "relpos": (.3, .7)} ab = AnnotationBbox(da, [.5, .5], xybox=(-0.2, 0.5), xycoords='data', boxcoords="axes fraction", box_alignment=(0., .5), arrowprops=arrowprops) assert ab.arrowprops is not ab assert arrowprops["relpos"] == (.3, .7)
def createBall(self, colour): radius = 2 da = DrawingArea(radius, radius, 10, 10) circle = patches.Circle((0.0, 0.0), radius=radius, edgecolor='k', facecolor=colour, fill=True, ls='solid', clip_on=False) da.add_artist(circle) ab = AnnotationBbox(da, xy=(0, 0), xycoords=("data", "data"), boxcoords=("data", "data"), box_alignment=(5.0, 5.0), frameon=False) return ab
def hbar(plot, p, values, colors=None, height=16, xoff=0, yoff=0, halign=1, valign=0.5, xycoords='data', boxcoords=('offset points')): x, y = _xy(plot, p) h = height; w = sum(values) * height#; yoff=h*0.5 da = DrawingArea(w, h) x0 = -sum(values) if not colors: c = _colors.tango() colors = [ c.next() for v in values ] for i, v in enumerate(values): if v: da.add_artist(Rectangle((x0,0), v*h, h, fc=colors[i], ec='none')) x0 += v*h box = AnnotationBbox(da, (x,y), pad=0, frameon=False, xybox=(xoff, yoff), xycoords=xycoords, box_alignment=(halign,valign), boxcoords=boxcoords) plot.add_artist(box) plot.figure.canvas.draw_idle()
def tipsquares(plot, p, colors="r", size=15, pad=2, edgepad=10): """ RR: Bug with this function. If you attempt to call it with a list as an argument for p, it will not only not work (expected) but it will also make it so that you can't interact with the tree figure (gives errors when you try to add symbols, select nodes, etc.) -CZ Add square after tip label, anchored to the side of the plot Args: plot (Tree): A Tree plot instance. p (Node): A Node object (Should be a leaf node). colors (str): olor of drawn square. Optional, defaults to 'r' (red) size (float): Size of square. Optional, defaults to 15 pad: RR: I am unsure what this does. Does not seem to have visible effect when I change it. -CZ edgepad (float): Padding from square to edge of plot. Optional, defaults to 10. """ x, y = _xy(plot, p) # p is a single node or point in data coordinates n = len(colors) da = DrawingArea(size * n + pad * (n - 1), size, 0, 0) sx = 0 for c in colors: sq = Rectangle((sx, 0), size, size, color=c) da.add_artist(sq) sx += size + pad box = AnnotationBbox( da, (x, y), xybox=(-edgepad, y), frameon=False, pad=0.0, xycoords="data", box_alignment=(1, 0.5), boxcoords=("axes points", "data"), ) plot.add_artist(box) plot.figure.canvas.draw_idle()
def draw_circles(ax): """Draw circles in axes coordinates.""" area = DrawingArea(40, 20, 0, 0) area.add_artist(Circle((10, 10), 10, fc="tab:blue")) area.add_artist(Circle((30, 10), 5, fc="tab:red")) box = AnchoredOffsetbox( child=area, loc="upper right", pad=0, frameon=False) ax.add_artist(box)
def tipsquares(plot, p, colors='r', size=15, pad=2, edgepad=10): """ RR: Bug with this function. If you attempt to call it with a list as an argument for p, it will not only not work (expected) but it will also make it so that you can't interact with the tree figure (gives errors when you try to add symbols, select nodes, etc.) -CZ Add square after tip label, anchored to the side of the plot Args: plot (Tree): A Tree plot instance. p (Node): A Node object (Should be a leaf node). colors (str): color of drawn square. Optional, defaults to 'r' (red) size (float): Size of square. Optional, defaults to 15 pad: RR: I am unsure what this does. Does not seem to have visible effect when I change it. -CZ edgepad (float): Padding from square to edge of plot. Optional, defaults to 10. """ x, y = _xy(plot, p) # p is a single node or point in data coordinates n = len(colors) da = DrawingArea(size * n + pad * (n - 1), size, 0, 0) sx = 0 for c in colors: sq = Rectangle((sx, 0), size, size, color=c) da.add_artist(sq) sx += size + pad box = AnnotationBbox(da, (x, y), xybox=(-edgepad, y), frameon=False, pad=0.0, xycoords='data', box_alignment=(1, 0.5), boxcoords=('axes points', 'data')) plot.add_artist(box) plot.figure.canvas.draw_idle()
def test_offsetbox_loc_codes(): # Check that valid string location codes all work with an AnchoredOffsetbox codes = {'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, } fig, ax = plt.subplots() da = DrawingArea(100, 100) for code in codes: anchored_box = AnchoredOffsetbox(loc=code, child=da) ax.add_artist(anchored_box) fig.canvas.draw()
def draw_matching(match, nbMen, nbWomen): width, height = 25, 50 da = DrawingArea(width, height) coordM = [( width/4, height*(nbMen-i)/(nbMen+1)) for i in range(nbMen)] coordW = [(3*width/4, height*(nbWomen-i)/(nbWomen+1)) for i in range(nbWomen)] for idWoman in range(nbWomen): if match[idWoman] == -1: xdata = [coordW[idWoman][0]] ydata = [coordW[idWoman][1]] da.add_artist(Line2D(xdata, ydata, marker=".")) for idMan in range(nbMen): if idMan not in match: xdata = [coordM[idMan][0]] ydata = [coordM[idMan][1]] da.add_artist(Line2D(xdata, ydata, marker=".")) for idWoman,idMan in enumerate(match): if idMan != -1: xdata = [coordM[idMan][0], coordW[idWoman][0]] ydata = [coordM[idMan][1], coordW[idWoman][1]] da.add_artist(Line2D(xdata, ydata, marker=".")) return da
class AnchoredInterface(AnchoredOffsetbox): """ Fixed object holding drawing area. (Box in upper left corner) """ def __init__(self, width, height, xdescent, ydescent): self.area = DrawingArea(width, height, xdescent, ydescent) super().__init__(loc="upper right", pad=0.4, borderpad=0.5, child=self.area, prop=None, frameon=True) def contains(self, mouseevent): """ Check is mouse click is inside Returns: a: bool b: dict Is empty dict, can be changed for more info if needed """ for c in self.area.get_children(): a, b = c.contains(mouseevent) if a: if callable(c): c() return a, b return False, {} def copy(self): A = self.area new = AnchoredInterface(A.width, A.height, A.xdescent, A.ydescent) for child in A._children: new.area.add_artist(child) return new def set_text(self, childno, text): self.area._children[childno].set_text(text)
def test_picking(child_type, boxcoords): # These all take up approximately the same area. if child_type == 'draw': picking_child = DrawingArea(5, 5) picking_child.add_artist(mpatches.Rectangle((0, 0), 5, 5, linewidth=0)) elif child_type == 'image': im = np.ones((5, 5)) im[2, 2] = 0 picking_child = OffsetImage(im) elif child_type == 'text': picking_child = TextArea('\N{Black Square}', textprops={'fontsize': 5}) else: assert False, f'Unknown picking child type {child_type}' fig, ax = plt.subplots() ab = AnnotationBbox(picking_child, (0.5, 0.5), boxcoords=boxcoords) ab.set_picker(True) ax.add_artist(ab) calls = [] fig.canvas.mpl_connect('pick_event', lambda event: calls.append(event)) # Annotation should be picked by an event occurring at its center. if boxcoords == 'axes points': x, y = ax.transAxes.transform_point((0, 0)) x += 0.5 * fig.dpi / 72 y += 0.5 * fig.dpi / 72 elif boxcoords == 'axes pixels': x, y = ax.transAxes.transform_point((0, 0)) x += 0.5 y += 0.5 else: x, y = ax.transAxes.transform_point((0.5, 0.5)) fig.canvas.draw() calls.clear() fig.canvas.button_press_event(x, y, MouseButton.LEFT) assert len(calls) == 1 and calls[0].artist == ab # Annotation should *not* be picked by an event at its original center # point when the limits have changed enough to hide the *xy* point. ax.set_xlim(-1, 0) ax.set_ylim(-1, 0) fig.canvas.draw() calls.clear() fig.canvas.button_press_event(x, y, MouseButton.LEFT) assert len(calls) == 0
def plot_rectangle(self, figure, axis): ''' plots the legend rectangle above the left corner of the figure :param figure: figure on which to add the label :param axis: axis on which to add the label :return: - ''' box1 = TextArea(" True: \n False: \n NaN: ", textprops=dict(color="k", size=10)) # box2 = DrawingArea(20, 27.5, 0, 0) # el1 = Rectangle((5, 15), width=10, height=10, angle=0, fc="g") # el2 = Rectangle((5, 2.5), width=10, height=10, angle=0, fc="r") box2 = DrawingArea(20, 45, 0, 0) el1 = Rectangle((5, 30), width=10, height=10, angle=0, fc="g") el2 = Rectangle((5, 18.5), width=10, height=10, angle=0, fc="r") el3 = Rectangle((5, 7), width=10, height=10, angle=0, fc='#d3d3d3') box2.add_artist(el1) box2.add_artist(el2) box2.add_artist(el3) box = HPacker(children=[box1, box2], align="center", pad=0, sep=5) anchored_box = AnchoredOffsetbox( loc=3, child=box, pad=0., frameon=True, bbox_to_anchor=(0., 1.02), bbox_transform=axis.transAxes, borderpad=0., ) axis.add_artist(anchored_box) figure.subplots_adjust(top=0.8)
def __init__(self, width, height, xdescent, ydescent, loc, pad=0.4, borderpad=0.5, prop=None, frameon=True, **kwargs): """ An anchored container with a fixed size and fillable DrawingArea. Artists added to the *drawing_area* will have their coordinates interpreted as pixels. Any transformations set on the artists will be overridden. Parameters ---------- width, height : float width and height of the container, in pixels. xdescent, ydescent : float descent of the container in the x- and y- direction, in pixels. loc : int Location of this artist. Valid location codes are:: '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 pad : float, optional, default: 0.4 Padding around the child objects, in fraction of the font size. borderpad : float, optional, default: 0.5 Border padding, in fraction of the font size. prop : `matplotlib.font_manager.FontProperties`, optional Font property used as a reference for paddings. frameon : bool, optional, default: True If True, draw a box around this artists. **kwargs Keyworded arguments to pass to :class:`matplotlib.offsetbox.AnchoredOffsetbox`. Attributes ---------- drawing_area : `matplotlib.offsetbox.DrawingArea` A container for artists to display. Examples -------- To display blue and red circles of different sizes in the upper right of an axes *ax*: >>> ada = AnchoredDrawingArea(20, 20, 0, 0, ... loc='upper right', frameon=False) >>> ada.drawing_area.add_artist(Circle((10, 10), 10, fc="b")) >>> ada.drawing_area.add_artist(Circle((30, 10), 5, fc="r")) >>> ax.add_artist(ada) """ self.da = DrawingArea(width, height, xdescent, ydescent) self.drawing_area = self.da super().__init__(loc, pad=pad, borderpad=borderpad, child=self.da, prop=None, frameon=frameon, **kwargs)
def make_rect(color, alpha, size = (20,6), height = 20): color = color if color != None else "k" # Default value if None viz = DrawingArea(30, height, 0, 1) viz.add_artist(Rectangle((0, 6), width=size[0], height=size[1], alpha=alpha, fc=color)) return viz
arrowprops=dict(arrowstyle="->")) ax.add_artist(ab) offsetbox = TextArea("Test", minimumdescent=False) ab = AnnotationBbox(offsetbox, xy, xybox=(1.02, xy[1]), xycoords='data', boxcoords=("axes fraction", "data"), box_alignment=(0., 0.5), arrowprops=dict(arrowstyle="->")) ax.add_artist(ab) from matplotlib.patches import Circle da = DrawingArea(20, 20, 0, 0) p = Circle((10, 10), 10) da.add_artist(p) xy = [0.3, 0.55] ab = AnnotationBbox(da, xy, xybox=(1.02, xy[1]), xycoords='data', boxcoords=("axes fraction", "data"), box_alignment=(0., 0.5), arrowprops=dict(arrowstyle="->")) #arrowprops=None) ax.add_artist(ab)
def _init_legend_box(self, handles, labels): """ Initiallize the legend_box. The legend_box is an instance of the OffsetBox, which is packed with legend handles and texts. Once packed, their location is calculated during the drawing time. """ fontsize = self._fontsize text_list = [] # the list of text instances handle_list = [] # the list of text instances label_prop = dict(verticalalignment='baseline', horizontalalignment='left', fontproperties=self.prop, ) labelboxes = [] handleboxes = [] height = self._approx_text_height() * 0.7 descent = 0. for handle, lab in zip(handles, labels): if isinstance(handle, RegularPolyCollection) or \ isinstance(handle, CircleCollection): npoints = self.scatterpoints else: npoints = self.numpoints if npoints > 1: xdata = np.linspace(0.3*fontsize, (self.handlelength-0.3)*fontsize, npoints) xdata_marker = xdata elif npoints == 1: xdata = np.linspace(0, self.handlelength*fontsize, 2) xdata_marker = [0.5*self.handlelength*fontsize] if isinstance(handle, Line2D): ydata = ((height-descent)/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_drawstyle('default') legline.set_marker('None') handle_list.append(legline) legline_marker = Line2D(xdata_marker, ydata[:len(xdata_marker)]) legline_marker.update_from(handle) self._set_artist_props(legline_marker) legline_marker.set_clip_box(None) legline_marker.set_clip_path(None) legline_marker.set_linestyle('None') legline._legmarker = legline_marker elif isinstance(handle, Patch): p = Rectangle(xy=(0., 0.), width = self.handlelength*fontsize, height=(height-descent), ) p.update_from(handle) self._set_artist_props(p) p.set_clip_box(None) p.set_clip_path(None) handle_list.append(p) elif isinstance(handle, LineCollection): ydata = ((height-descent)/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) if dashes[0] is not None: # dashed line legline.set_dashes(dashes[1]) handle_list.append(legline) elif isinstance(handle, RegularPolyCollection): ydata = height*self._scatteryoffsets size_max, size_min = max(handle.get_sizes()),\ min(handle.get_sizes()) if self.scatterpoints < 4: sizes = [.5*(size_max+size_min), size_max, size_min] else: sizes = (size_max-size_min)*np.linspace(0,1,self.scatterpoints)+size_min p = type(handle)(handle.get_numsides(), rotation=handle.get_rotation(), sizes=sizes, offsets=zip(xdata_marker,ydata), transOffset=self.get_transform(), ) p.update_from(handle) p.set_figure(self.figure) p.set_clip_box(None) p.set_clip_path(None) handle_list.append(p) elif isinstance(handle, CircleCollection): ydata = height*self._scatteryoffsets size_max, size_min = max(handle.get_sizes()),\ min(handle.get_sizes()) if self.scatterpoints < 4: sizes = [.5*(size_max+size_min), size_max, size_min] else: sizes = (size_max-size_min)*np.linspace(0,1,self.scatterpoints)+size_min p = type(handle)(sizes, offsets=zip(xdata_marker,ydata), transOffset=self.get_transform(), ) p.update_from(handle) p.set_figure(self.figure) p.set_clip_box(None) p.set_clip_path(None) handle_list.append(p) else: handle_type = type(handle) warnings.warn("Legend does not support %s\nUse proxy artist instead.\n\nhttp://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist\n" % (str(handle_type),)) handle_list.append(None) handle = handle_list[-1] if handle is not None: # handle is None is the artist is not supproted textbox = TextArea(lab, textprops=label_prop, multilinebaseline=True, minimumdescent=True) text_list.append(textbox._text) labelboxes.append(textbox) handlebox = DrawingArea(width=self.handlelength*fontsize, height=height, xdescent=0., ydescent=descent) handlebox.add_artist(handle) if isinstance(handle, RegularPolyCollection) or \ isinstance(handle, CircleCollection): handle._transOffset = handlebox.get_transform() handle.set_transform(None) if hasattr(handle, "_legmarker"): handlebox.add_artist(handle._legmarker) handleboxes.append(handlebox) if len(handleboxes) > 0: ncol = min(self._ncol, len(handleboxes)) nrows, num_largecol = divmod(len(handleboxes), ncol) num_smallcol = ncol-num_largecol largecol = safezip(range(0, num_largecol*(nrows+1), (nrows+1)), [nrows+1] * num_largecol) smallcol = safezip(range(num_largecol*(nrows+1), len(handleboxes), nrows), [nrows] * num_smallcol) else: largecol, smallcol = [], [] handle_label = safezip(handleboxes, labelboxes) columnbox = [] for i0, di in largecol+smallcol: itemBoxes = [HPacker(pad=0, sep=self.handletextpad*fontsize, children=[h, t], align="baseline") for h, t in handle_label[i0:i0+di]] itemBoxes[-1].get_children()[1].set_minimumdescent(False) columnbox.append(VPacker(pad=0, sep=self.labelspacing*fontsize, align="baseline", children=itemBoxes)) if self._mode == "expand": mode = "expand" else: mode = "fixed" sep = self.columnspacing*fontsize self._legend_handle_box = HPacker(pad=0, sep=sep, align="baseline", mode=mode, children=columnbox) self._legend_title_box = TextArea("") self._legend_box = VPacker(pad=self.borderpad*fontsize, sep=self.labelspacing*fontsize, align="center", children=[self._legend_title_box, self._legend_handle_box]) self._legend_box.set_figure(self.figure) self.texts = text_list self.legendHandles = handle_list
def _init_legend_box(self, handles, labels): """ Initiallize the legend_box. The legend_box is an instance of the OffsetBox, which is packed with legend handles and texts. Once packed, their location is calculated during the drawing time. """ fontsize = self.fontsize # legend_box is a HPacker, horizontally packed with # columns. Each column is a VPacker, vertically packed with # legend items. Each legend item is HPacker packed with # legend handleBox and labelBox. handleBox is an instance of # offsetbox.DrawingArea which contains legend handle. labelBox # is an instance of offsetbox.TextArea which contains legend # text. text_list = [] # the list of text instances handle_list = [] # the list of text instances label_prop = dict( verticalalignment='baseline', horizontalalignment='left', fontproperties=self.prop, ) labelboxes = [] for l in labels: textbox = TextArea(l, textprops=label_prop, multilinebaseline=True, minimumdescent=True) text_list.append(textbox._text) labelboxes.append(textbox) handleboxes = [] # The approximate height and descent of text. These values are # only used for plotting the legend handle. height = self._approx_text_height() * 0.7 descent = 0. # each handle needs to be drawn inside a box of (x, y, w, h) = # (0, -descent, width, height). And their corrdinates should # be given in the display coordinates. # NOTE : the coordinates will be updated again in # _update_legend_box() method. # The transformation of each handle will be automatically set # to self.get_trasnform(). If the artist does not uses its # default trasnform (eg, Collections), you need to # manually set their transform to the self.get_transform(). for handle in handles: if isinstance(handle, RegularPolyCollection): npoints = self.scatterpoints else: npoints = self.numpoints if npoints > 1: # we put some pad here to compensate the size of the # marker xdata = np.linspace(0.3 * fontsize, (self.handlelength - 0.3) * fontsize, npoints) xdata_marker = xdata elif npoints == 1: xdata = np.linspace(0, self.handlelength * fontsize, 2) xdata_marker = [0.5 * self.handlelength * fontsize] if isinstance(handle, Line2D): ydata = ((height - descent) / 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_drawstyle('default') legline.set_marker('None') handle_list.append(legline) legline_marker = Line2D(xdata_marker, ydata[:len(xdata_marker)]) legline_marker.update_from(handle) self._set_artist_props(legline_marker) legline_marker.set_clip_box(None) legline_marker.set_clip_path(None) legline_marker.set_linestyle('None') # 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=(0., 0.), width=self.handlelength * fontsize, height=(height - descent), ) p.update_from(handle) self._set_artist_props(p) p.set_clip_box(None) p.set_clip_path(None) handle_list.append(p) elif isinstance(handle, LineCollection): ydata = ((height - descent) / 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) handle_list.append(legline) elif isinstance(handle, RegularPolyCollection): #ydata = self._scatteryoffsets ydata = height * self._scatteryoffsets size_max, size_min = max(handle.get_sizes()),\ min(handle.get_sizes()) # we may need to scale these sizes by "markerscale" # attribute. But other handle types does not seem # to care about this attribute and it is currently ignored. if self.scatterpoints < 4: sizes = [.5 * (size_max + size_min), size_max, size_min] else: sizes = (size_max - size_min) * np.linspace( 0, 1, self.scatterpoints) + size_min p = type(handle)( handle.get_numsides(), rotation=handle.get_rotation(), sizes=sizes, offsets=zip(xdata_marker, ydata), transOffset=self.get_transform(), ) p.update_from(handle) p.set_figure(self.figure) p.set_clip_box(None) p.set_clip_path(None) handle_list.append(p) else: handle_list.append(None) handlebox = DrawingArea(width=self.handlelength * fontsize, height=height, xdescent=0., ydescent=descent) handle = handle_list[-1] handlebox.add_artist(handle) if hasattr(handle, "_legmarker"): handlebox.add_artist(handle._legmarker) handleboxes.append(handlebox) # We calculate number of lows in each column. The first # (num_largecol) columns will have (nrows+1) rows, and remaing # (num_smallcol) columns will have (nrows) rows. nrows, num_largecol = divmod(len(handleboxes), self._ncol) num_smallcol = self._ncol - num_largecol # starting index of each column and number of rows in it. largecol = safezip(range(0, num_largecol * (nrows + 1), (nrows + 1)), [nrows + 1] * num_largecol) smallcol = safezip( range(num_largecol * (nrows + 1), len(handleboxes), nrows), [nrows] * num_smallcol) handle_label = safezip(handleboxes, labelboxes) columnbox = [] for i0, di in largecol + smallcol: # pack handleBox and labelBox into itemBox itemBoxes = [ HPacker(pad=0, sep=self.handletextpad * fontsize, children=[h, t], align="baseline") for h, t in handle_label[i0:i0 + di] ] # minimumdescent=False for the text of the last row of the column itemBoxes[-1].get_children()[1].set_minimumdescent(False) # pack columnBox columnbox.append( VPacker(pad=0, sep=self.labelspacing * fontsize, align="baseline", children=itemBoxes)) if self._mode == "expand": mode = "expand" else: mode = "fixed" sep = self.columnspacing * fontsize self._legend_box = HPacker(pad=self.borderpad * fontsize, sep=sep, align="baseline", mode=mode, children=columnbox) self._legend_box.set_figure(self.figure) self.texts = text_list self.legendHandles = handle_list
def draw(self): """ Draw guide Returns ------- out : matplotlib.offsetbox.Offsetbox A drawing of this legend """ obverse = slice(0, None) reverse = slice(None, None, -1) nbars = len(self.bar) direction = self.direction colors = self.bar['color'].tolist() labels = self.key['label'].tolist() themeable = self.theme.figure._themeable _d = self._default # 1.45 makes the default colourbar wider than the # legend entry boxes. width = (self.barwidth or _d('legend_key_width') or 16) * 1.45 height = (self.barheight or _d('legend_key_height') or 16) * 1.45 height *= 5 length = height # When there is more than one guide, we keep # record of all of them using lists if 'legend_title' not in themeable: themeable['legend_title'] = [] if 'legend_text_colorbar' not in themeable: themeable['legend_text_colorbar'] = [] # .5 puts the ticks in the middle of the bars when # raster=False. So when raster=True the ticks are # in between interpolation points and the matching is # close though not exactly right. _from = self.bar['value'].min(), self.bar['value'].max() tick_locations = rescale(self.key['value'], (.5, nbars - .5), _from) * length / nbars if direction == 'horizontal': width, height = height, width length = width if self.reverse: colors = colors[::-1] labels = labels[::-1] tick_locations = length - tick_locations[::-1] # title # title_box = TextArea(self.title, textprops=dict(color='black')) themeable['legend_title'].append(title_box) # colorbar and ticks # da = DrawingArea(width, height, 0, 0) if self.raster: add_interpolated_colorbar(da, colors, direction) else: add_segmented_colorbar(da, colors, direction) if self.ticks: _locations = tick_locations if not self.draw_ulim: _locations = _locations[:-1] if not self.draw_llim: _locations = _locations[1:] add_ticks(da, _locations, direction) # labels # if self.label: labels_da, legend_text = create_labels(da, labels, tick_locations, direction) themeable['legend_text_colorbar'].extend(legend_text) else: labels_da = DrawingArea(0, 0) # colorbar + labels # if direction == 'vertical': packer, align = HPacker, 'bottom' align = 'center' else: packer, align = VPacker, 'right' align = 'center' slc = obverse if self.label_position == 'right' else reverse if self.label_position in ('right', 'bottom'): slc = obverse else: slc = reverse main_box = packer(children=[da, labels_da][slc], sep=self._label_margin, align=align, pad=0) # title + colorbar(with labels) # lookup = { 'right': (HPacker, reverse), 'left': (HPacker, obverse), 'bottom': (VPacker, reverse), 'top': (VPacker, obverse) } packer, slc = lookup[self.title_position] children = [title_box, main_box][slc] box = packer(children=children, sep=self._title_margin, align=self._title_align, pad=0) return box
dx,dy = imagesize(temppath) w = min(W,dx) image(temppath,imgx,imgy,width=w) imgy = imgy + dy + 20 os.remove(temppath) size(W, HEIGHT+dy+40) else: def pltshow(mplpyplot): mplpyplot.show() # nodebox section end fig, ax = plt.subplots(figsize=(3, 3)) box1 = TextArea(" Test : ", textprops=dict(color="k")) box2 = DrawingArea(60, 20, 0, 0) el1 = Ellipse((10, 10), width=16, height=5, angle=30, fc="r") el2 = Ellipse((30, 10), width=16, height=5, angle=170, fc="g") el3 = Ellipse((50, 10), width=16, height=5, angle=230, fc="b") box2.add_artist(el1) box2.add_artist(el2) box2.add_artist(el3) box = HPacker(children=[box1, box2], align="center", pad=0, sep=5) anchored_box = AnchoredOffsetbox(loc=3, child=box, pad=0., frameon=True, bbox_to_anchor=(0., 1.02),
# Annotate the 1st position with another text box ('Test') offsetbox = TextArea("Test", minimumdescent=False) ab = AnnotationBbox(offsetbox, xy, xybox=(1.02, xy[1]), xycoords='data', boxcoords=("axes fraction", "data"), box_alignment=(0., 0.5), arrowprops=dict(arrowstyle="->")) ax.add_artist(ab) # Define a 2nd position to annotate (don't display with a marker this time) xy = [0.3, 0.55] # Annotate the 2nd position with a circle patch da = DrawingArea(20, 20, 0, 0) p = Circle((10, 10), 10) da.add_artist(p) ab = AnnotationBbox(da, xy, xybox=(1.02, xy[1]), xycoords='data', boxcoords=("axes fraction", "data"), box_alignment=(0., 0.5), arrowprops=dict(arrowstyle="->")) ax.add_artist(ab) # Annotate the 2nd position with an image (a generated array of pixels) arr = np.arange(100).reshape((10, 10)) im = OffsetImage(arr, zoom=2)
def plot_rst(xList, yList, fnameList): '''docstring for plot_rst()''' fig = plt.gcf() fig.clf() ax = plt.subplot2grid((5,1),(0, 0),rowspan = 4) #ax = plt.subplot(111) xy = (0.5, 0.7) offsetbox = TextArea("Test", minimumdescent=False) ab = AnnotationBbox(offsetbox, xy, xybox=(1.02, xy[1]), xycoords='data', boxcoords=("axes fraction", "data"), box_alignment=(0.,0.5), arrowprops=dict(arrowstyle="->")) ax.add_artist(ab) from matplotlib.patches import Circle da = DrawingArea(20, 20, 0, 0) p = Circle((10, 10), 10) da.add_artist(p) xy = [0.3, 0.55] ab = AnnotationBbox(da, xy, xybox=(1.02, xy[1]), xycoords='data', boxcoords=("axes fraction", "data"), box_alignment=(0.,0.5), arrowprops=dict(arrowstyle="->")) #arrowprops=None) ax.add_artist(ab) # another image from matplotlib._png import read_png #fn = get_sample_data("./61.png", asfileobj=False) arr_lena = read_png("./61.png") imagebox = OffsetImage(arr_lena, zoom=0.2) xy = (0.1, 0.1) print fnameList for i in range(0,len(fnameList)): ax.add_artist(AnnotationBbox(imagebox, xy, xybox=(0.1 + i*0.2, -0.15), xycoords='data', boxcoords=("axes fraction", "data"), #boxcoords="offset points", pad=0.1, arrowprops=dict(arrowstyle="->", connectionstyle="angle,angleA=0,angleB=90,rad=3") )) ax.set_xlim(0, 1) ax.set_ylim(0, 1) plt.draw() plt.show()
def _init_legend_box(self, handles, labels, markerfirst=True): """ Initialize the legend_box. The legend_box is an instance of the OffsetBox, which is packed with legend handles and texts. Once packed, their location is calculated during the drawing time. """ fontsize = self._fontsize # legend_box is a HPacker, horizontally packed with # columns. Each column is a VPacker, vertically packed with # legend items. Each legend item is HPacker packed with # legend handleBox and labelBox. handleBox is an instance of # offsetbox.DrawingArea which contains legend handle. labelBox # is an instance of offsetbox.TextArea which contains legend # text. text_list = [] # the list of text instances handle_list = [] # the list of text instances label_prop = dict( verticalalignment='baseline', horizontalalignment='left', fontproperties=self.prop, ) labelboxes = [] handleboxes = [] # The approximate height and descent of text. These values are # only used for plotting the legend handle. descent = 0.35 * self._approx_text_height() * (self.handleheight - 0.7) # 0.35 and 0.7 are just heuristic numbers and may need to be improved. height = self._approx_text_height() * self.handleheight - descent # each handle needs to be drawn inside a box of (x, y, w, h) = # (0, -descent, width, height). And their coordinates should # be given in the display coordinates. # The transformation of each handle will be automatically set # to self.get_trasnform(). If the artist does not use its # default transform (e.g., Collections), you need to # manually set their transform to the self.get_transform(). legend_handler_map = self.get_legend_handler_map() for orig_handle, lab in zip(handles, labels): handler = self.get_legend_handler(legend_handler_map, orig_handle) if handler is None: warnings.warn( "Legend does not support {!r} instances.\nA proxy artist " "may be used instead.\nSee: " "http://matplotlib.org/users/legend_guide.html" "#using-proxy-artist".format(orig_handle)) # We don't have a handle for this artist, so we just defer # to None. handle_list.append(None) else: textbox = TextArea(lab, textprops=label_prop, multilinebaseline=True, minimumdescent=True) text_list.append(textbox._text) labelboxes.append(textbox) handlebox = DrawingArea(width=self.handlelength * fontsize, height=height, xdescent=0., ydescent=descent) handleboxes.append(handlebox) # Create the artist for the legend which represents the # original artist/handle. handle_list.append( handler.legend_artist(self, orig_handle, fontsize, handlebox)) if len(handleboxes) > 0: # We calculate number of rows in each column. The first # (num_largecol) columns will have (nrows+1) rows, and remaining # (num_smallcol) columns will have (nrows) rows. ncol = min(self._ncol, len(handleboxes)) nrows, num_largecol = divmod(len(handleboxes), ncol) num_smallcol = ncol - num_largecol # starting index of each column and number of rows in it. largecol = safezip( list(xrange(0, num_largecol * (nrows + 1), (nrows + 1))), [nrows + 1] * num_largecol) smallcol = safezip( list( xrange(num_largecol * (nrows + 1), len(handleboxes), nrows)), [nrows] * num_smallcol) else: largecol, smallcol = [], [] handle_label = safezip(handleboxes, labelboxes) columnbox = [] for i0, di in largecol + smallcol: # pack handleBox and labelBox into itemBox itemBoxes = [ HPacker(pad=0, sep=self.handletextpad * fontsize, children=[h, t] if markerfirst else [t, h], align="baseline") for h, t in handle_label[i0:i0 + di] ] # minimumdescent=False for the text of the last row of the column if markerfirst: itemBoxes[-1].get_children()[1].set_minimumdescent(False) else: itemBoxes[-1].get_children()[0].set_minimumdescent(False) # pack columnBox if markerfirst: alignment = "baseline" else: alignment = "right" columnbox.append( VPacker(pad=0, sep=self.labelspacing * fontsize, align=alignment, children=itemBoxes)) if self._mode == "expand": mode = "expand" else: mode = "fixed" sep = self.columnspacing * fontsize self._legend_handle_box = HPacker(pad=0, sep=sep, align="baseline", mode=mode, children=columnbox) self._legend_title_box = TextArea("") self._legend_box = VPacker( pad=self.borderpad * fontsize, sep=self.labelspacing * fontsize, align="center", children=[self._legend_title_box, self._legend_handle_box]) self._legend_box.set_figure(self.figure) self.texts = text_list self.legendHandles = handle_list
def _init_legend_box(self, handles, labels): """ Initiallize the legend_box. The legend_box is an instance of the OffsetBox, which is packed with legend handles and texts. Once packed, their location is calculated during the drawing time. """ fontsize = self.fontsize # legend_box is a HPacker, horizontally packed with # columns. Each column is a VPacker, vertically packed with # legend items. Each legend item is HPacker packed with # legend handleBox and labelBox. handleBox is an instance of # offsetbox.DrawingArea which contains legend handle. labelBox # is an instance of offsetbox.TextArea which contains legend # text. text_list = [] # the list of text instances handle_list = [] # the list of text instances label_prop = dict(verticalalignment='baseline', horizontalalignment='left', fontproperties=self.prop, ) labelboxes = [] for l in labels: textbox = TextArea(l, textprops=label_prop, multilinebaseline=True, minimumdescent=True) text_list.append(textbox._text) labelboxes.append(textbox) handleboxes = [] # The approximate height and descent of text. These values are # only used for plotting the legend handle. height = self._approx_text_height() * 0.7 descent = 0. # each handle needs to be drawn inside a box of (x, y, w, h) = # (0, -descent, width, height). And their corrdinates should # be given in the display coordinates. # NOTE : the coordinates will be updated again in # _update_legend_box() method. # The transformation of each handle will be automatically set # to self.get_trasnform(). If the artist does not uses its # default trasnform (eg, Collections), you need to # manually set their transform to the self.get_transform(). for handle in handles: if isinstance(handle, RegularPolyCollection): npoints = self.scatterpoints else: npoints = self.numpoints if npoints > 1: # we put some pad here to compensate the size of the # marker xdata = np.linspace(0.3*fontsize, (self.handlelength-0.3)*fontsize, npoints) xdata_marker = xdata elif npoints == 1: xdata = np.linspace(0, self.handlelength*fontsize, 2) xdata_marker = [0.5*self.handlelength*fontsize] if isinstance(handle, Line2D): ydata = ((height-descent)/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_drawstyle('default') legline.set_marker('None') handle_list.append(legline) legline_marker = Line2D(xdata_marker, ydata[:len(xdata_marker)]) legline_marker.update_from(handle) self._set_artist_props(legline_marker) legline_marker.set_clip_box(None) legline_marker.set_clip_path(None) legline_marker.set_linestyle('None') # 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=(0., 0.), width = self.handlelength*fontsize, height=(height-descent), ) p.update_from(handle) self._set_artist_props(p) p.set_clip_box(None) p.set_clip_path(None) handle_list.append(p) elif isinstance(handle, LineCollection): ydata = ((height-descent)/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) handle_list.append(legline) elif isinstance(handle, RegularPolyCollection): #ydata = self._scatteryoffsets ydata = height*self._scatteryoffsets size_max, size_min = max(handle.get_sizes()),\ min(handle.get_sizes()) # we may need to scale these sizes by "markerscale" # attribute. But other handle types does not seem # to care about this attribute and it is currently ignored. if self.scatterpoints < 4: sizes = [.5*(size_max+size_min), size_max, size_min] else: sizes = (size_max-size_min)*np.linspace(0,1,self.scatterpoints)+size_min p = type(handle)(handle.get_numsides(), rotation=handle.get_rotation(), sizes=sizes, offsets=zip(xdata_marker,ydata), transOffset=self.get_transform(), ) p.update_from(handle) p.set_figure(self.figure) p.set_clip_box(None) p.set_clip_path(None) handle_list.append(p) else: handle_list.append(None) handlebox = DrawingArea(width=self.handlelength*fontsize, height=height, xdescent=0., ydescent=descent) handle = handle_list[-1] handlebox.add_artist(handle) if hasattr(handle, "_legmarker"): handlebox.add_artist(handle._legmarker) handleboxes.append(handlebox) # We calculate number of lows in each column. The first # (num_largecol) columns will have (nrows+1) rows, and remaing # (num_smallcol) columns will have (nrows) rows. nrows, num_largecol = divmod(len(handleboxes), self._ncol) num_smallcol = self._ncol-num_largecol # starting index of each column and number of rows in it. largecol = safezip(range(0, num_largecol*(nrows+1), (nrows+1)), [nrows+1] * num_largecol) smallcol = safezip(range(num_largecol*(nrows+1), len(handleboxes), nrows), [nrows] * num_smallcol) handle_label = safezip(handleboxes, labelboxes) columnbox = [] for i0, di in largecol+smallcol: # pack handleBox and labelBox into itemBox itemBoxes = [HPacker(pad=0, sep=self.handletextpad*fontsize, children=[h, t], align="baseline") for h, t in handle_label[i0:i0+di]] # minimumdescent=False for the text of the last row of the column itemBoxes[-1].get_children()[1].set_minimumdescent(False) # pack columnBox columnbox.append(VPacker(pad=0, sep=self.labelspacing*fontsize, align="baseline", children=itemBoxes)) if self._mode == "expand": mode = "expand" else: mode = "fixed" sep = self.columnspacing*fontsize self._legend_box = HPacker(pad=self.borderpad*fontsize, sep=sep, align="baseline", mode=mode, children=columnbox) self._legend_box.set_figure(self.figure) self.texts = text_list self.legendHandles = handle_list