def test4(ax): # When the aspect ratio of the axes is not 1, the fancy box may # not be what you expected (green) p_fancy = FancyBboxPatch((bb.xmin, bb.ymin), abs(bb.width), abs(bb.height), boxstyle="round,pad=0.2", fc="none", ec=(0., .5, 0.), zorder=4) ax.add_patch(p_fancy) # You can compensate this by setting the mutation_aspect (pink). p_fancy = FancyBboxPatch((bb.xmin, bb.ymin), abs(bb.width), abs(bb.height), boxstyle="round,pad=0.3", mutation_aspect=.5, fc=(1., 0.8, 1.), ec=(1., 0.5, 1.)) ax.add_patch(p_fancy) ax.text(0.1, 0.8, ' boxstyle="round,pad=0.3"\n mutation\\_aspect=.5', size=10, transform=ax.transAxes) draw_bbox(ax, bb)
def drawBox(start, end, y, height, fc, ec, rlabel=None, clip_on=True): w = end - start + 1 rs = min(w * width * 0.00001, 500. * width * 0.00001) patch = FancyBboxPatch( (start, y), w, height, boxstyle="square", mutation_aspect=2. * max(setYB) / width, fc=fc, ec=ec, clip_on=clip_on) ax.add_patch(patch) if rlabel is not None: plt.text(end + width * 0.015, y + height * .5, rlabel, verticalalignment='center', horizontalalignment='left', color=ax.yaxis.label.get_color(), fontsize=10, clip_on=False) return patch
def test3(ax): # mutation_scale determine overall scale of the mutation, # i.e. both pad and rounding_size is scaled according to this # value. p_fancy = FancyBboxPatch((bb.xmin, bb.ymin), abs(bb.width), abs(bb.height), boxstyle="round,pad=0.1", mutation_scale=2., fc=(1., .8, 1.), ec=(1., 0.5, 1.)) ax.add_patch(p_fancy) ax.text(0.1, 0.8, ' boxstyle="round,pad=0.1"\n mutation\\_scale=2', size=10, transform=ax.transAxes) # draws control points for the fancy box. #l = p_fancy.get_path().vertices #ax.plot(l[:,0], l[:,1], ".") draw_bbox(ax, bb)
def __init__(self, child, pad=None, draw_frame=False, patch_attrs=None): """ *pad* : boundary pad .. note:: *pad* need to given in points and will be scale with the renderer dpi, while *width* and *hight* need to be in pixels. """ super(PaddedBox, self).__init__() self.pad = pad self._children = [child] self.patch = FancyBboxPatch( xy=(0.0, 0.0), width=1., height=1., facecolor='w', edgecolor='k', mutation_scale=1, #self.prop.get_size_in_points(), snap=True) self.patch.set_boxstyle("square", pad=0) if patch_attrs is not None: self.patch.update(patch_attrs) self._drawFrame = draw_frame
def draw_rectangle_around_text(scene: Axes, origin: tuple, width: int, height: int, fill_color: tuple, line_color: tuple, line_width: int, rounded: int, text: str, font_size: int, font_family: str): if rounded > 0: box_style = 'round' else: box_style = 'square' scene.add_patch( FancyBboxPatch( origin, width, height, facecolor='#{0:02x}{1:02x}{2:02x}'.format(*fill_color), edgecolor='#{0:02x}{1:02x}{2:02x}'.format(*line_color), linewidth=line_width, boxstyle=box_style)) # write label in the middle under labelx = origin[0] + width // 2 labely = origin[ 1] + height // 2 + 4 # TODO: Should be drawn in the vertical center, so + 4 not needed! scene.text(labelx, labely, s=text, fontsize=font_size, color='#{0:02x}{1:02x}{2:02x}'.format(*line_color), fontname=font_family) return origin[0], origin[1], width, height
def test2(ax): # bbox=round has two optional argument. pad and rounding_size. # They can be set during the initialization. p_fancy = FancyBboxPatch((bb.xmin, bb.ymin), abs(bb.width), abs(bb.height), boxstyle="round,pad=0.1", fc=(1., .8, 1.), ec=(1., 0.5, 1.)) ax.add_patch(p_fancy) # boxstyle and its argument can be later modified with # set_boxstyle method. Note that the old attributes are simply # forgotten even if the boxstyle name is same. p_fancy.set_boxstyle("round,pad=0.1, rounding_size=0.2") # or #p_fancy.set_boxstyle("round", pad=0.1, rounding_size=0.2) ax.text(0.1, 0.8, ' boxstyle="round,pad=0.1\n rounding\\_size=0.2"', size=10, transform=ax.transAxes) # draws control points for the fancy box. #l = p_fancy.get_path().vertices #ax.plot(l[:,0], l[:,1], ".") draw_bbox(ax, bb)
def box1(ax): # a fancy box with round corners. pad=0.1 p_fancy = FancyBboxPatch( (bb.xmin, bb.ymin), abs(bb.width), abs(bb.height), boxstyle="round,pad=0.1", fc=(1.0, 0.8, 1.0), ec=(1.0, 0.5, 1.0), ) ax.add_patch(p_fancy) ax.text(0.1, 0.8, " boxstyle='round, pad=0.1'", size=10, transform=ax.transAxes) # # draws control points for the fancy box. # l = p_fancy.get_path().vertices # ax.plot(l[:,0], l[:,1], '.') # draw the original bbox in black draw_bbox(ax, bb) return
def drawSelectionRect(self): """Draw a selection box""" from matplotlib.patches import FancyBboxPatch if self.selectedrect != None: self.selectedrect.set_visible(False) fig = self.parent.fig ax = fig.axes[0] bb = self.selected.get_window_extent() bb = ax.transAxes.inverted().transform(bb) x, y = bb[0] x1, y1 = bb[1] print(x, y, x1, y1) pad = (x1 - x) / 10 self.selectedrect = FancyBboxPatch((x, y), abs(x1 - x), abs(y1 - y), boxstyle="round,pad=%s" % pad, lw=2, alpha=0.5, ec="red", fc="red", zorder=10., transform=ax.transAxes) ax.add_patch(self.selectedrect) fig.canvas.draw() return
def draw_event_box(box: EventBox, day_offset: int, label: str, color: str, ax): """Draws an event box on the plot using a day index (used internally to calculate the horizontal components of the box, and two start/end floats representing percentages through the day, used to calculate the vertical components.""" top = box.start_time_float bottom = box.end_time_float left = 0.5 + box.column_idx + day_offset # If this event would be drawn outside the view of the plot if left >= 7.0: return padding_between_days = 0.05 right = left + 1 - padding_between_days # Draw boxes and labels on top of everything else z = 2.0 box = FancyBboxPatch( (left, top), abs(right - left), abs(bottom - top), boxstyle="round,pad=-0.0040,rounding_size=0.02", ec="black", fc=color, lw=0.2, zorder=z, mutation_aspect=1) ax.add_patch(box) plt.text(left + 0.01, top + 0.01, label, va='top', fontsize=3, zorder=z)
def square_chart(fractions, defaultcolor='lightgrey'): if sum([f[0] for f in fractions]) > 1 or not all([f[0] >= 0 for f in fractions]): raise ValueError( 'Fractions must be positive and in sum between 0 and 1.') fractions, colors = zip(*fractions) percentages = [int(round(fraction * 100, 0)) for fraction in fractions] percentages = np.cumsum(percentages) percentages = np.append([0], percentages) color_counter = len(colors) - 1 matrix = np.full((10, 10), len(fractions), dtype=int) while True: square_counter = percentages[-1] - 1 if square_counter == -1: break percentages = percentages[:-1] while (square_counter >= percentages[-1]): matrix[9 - square_counter % 10][9 - square_counter // 10] = color_counter square_counter -= 1 color_counter -= 1 fig = plt.figure(figsize=(10, 10), dpi=300, edgecolor='white', facecolor='white', tight_layout=True) ax = plt.gca() ax.set_aspect('equal', 'box') for spine in ax.spines.values(): spine.set_edgecolor('white') ax.xaxis.set_major_locator(plt.NullLocator()) ax.yaxis.set_major_locator(plt.NullLocator()) for (x, y), color_index in np.ndenumerate(matrix): try: color = colors[color_index] except IndexError: color = defaultcolor size = 1 padding = 0.3 rect = FancyBboxPatch((x - size / 2, y - size / 2), size - 2 * padding, size - 2 * padding, boxstyle="round, pad=" + str(padding), linewidth=2, fc=color, ec='white') ax.add_patch(rect) ax.invert_yaxis() ax.autoscale(enable=True) fig.add_axes(ax) return fig, ax
def draw_compartments(compartments, fig, sf): """Create a list of FancyBbox Patches, one for each compartment. Args: compartments (iterable collection of Compartment): collection of compartments Returns: list of matplotlib.patches.FancyBboxPatch """ compartment_patches = [] for compartment in compartments: fbbp = FancyBboxPatch( # compartment.lower_left_point, [ sf * compartment.lower_left_point[0] / 72 + WIDTH_SHIFT, sf * compartment.lower_left_point[1] / 72 + HEIGHT_SHIFT ], sf * compartment.width / 72, sf * compartment.height / 72, edgecolor=compartment.edge_color, facecolor=compartment.fill_color, linewidth=compartment.line_width, boxstyle=BoxStyle("round", pad=0, rounding_size=.6), # mutation_scale=10, transform=fig.dpi_scale_trans) compartment_patches.append(fbbp) return compartment_patches
def draw_bbox(ax, bb): # boxstyle=square with pad=0, i.e. bbox itself. p_bbox = FancyBboxPatch((bb.xmin, bb.ymin), abs(bb.width), abs(bb.height), boxstyle="square,pad=0.", ec="k", fc="none", zorder=10., ) ax.add_patch(p_bbox)
def add_fancy_patch_around(ax, bb, **kwargs): fancy = FancyBboxPatch((bb.xmin, bb.ymin), bb.width, bb.height, fc=(1, 0.8, 1, 0.5), ec=(1, 0.5, 1, 0.5), **kwargs) ax.add_patch(fancy) return fancy
def draw_wire(self, x1, y1, x2, y2, color, linewidth): length = np.sqrt(((x2-x1)**2)+ ((y2-y1)**2)) degrees = math.degrees(math.atan2(y2-y1, x2-x1)) fancybox = FancyBboxPatch([x1, y1], linewidth, length, boxstyle=mpatches.BoxStyle("Round"), mutation_scale=0.2, mutation_aspect=1, color=color) t = mpl.transforms.Affine2D().rotate_deg(degrees) fancybox.set_transform(t) self.axes.add_patch(fancybox)
def obb(center_x, center_y, width, length, heading): centerxs.append(center_x) centerys.append(center_y) corners = [] dx1 = math.cos(heading) * length / 2 dy1 = math.sin(heading) * length / 2 dx2 = math.sin(heading) * width / 2 dy2 = -math.cos(heading) * width / 2 corners.append([center_x + dx1 + dx2, center_y + dy1 + dy2]) corners.append([center_x + dx1 - dx2, center_y + dy1 - dy2]) corners.append([center_x - dx1 - dx2, center_y - dy1 - dy2]) corners.append([center_x - dx1 + dx2, center_y - dy1 + dy2]) min_x = float("inf") max_x = -float("inf") min_y = float("inf") max_y = -float("inf") for corner in corners: max_x = max(corner[0], max_x) min_x = min(corner[0], min_x) max_y = max(corner[1], max_y) min_y = min(corner[1], min_y) corners.append(corners[0]) corners = np.array(corners) scat = ax.scatter(centerxs, centerys, s=100) obbx = ax.plot(corners[:, 0], corners[:, 1], '-') round_obb = FancyBboxPatch( (center_x - length / 2, center_y - width / 2), length, width, boxstyle="round,pad=1", fill=False, #fc=(1., .8, 1.), ec=(1., 0.5, 1.)) t2 = transforms.Affine2D().rotate_around(center_x, center_y, heading) + ax.transData round_obb.set_transform(t2) ax.add_patch(round_obb) arrow_length = length * 0.8 ax.arrow(center_x, center_y, arrow_length * math.cos(heading), arrow_length * math.sin(heading), head_width=0.5, head_length=1)
def make_box(self) -> FancyBboxPatch: # noinspection PyTypeChecker return FancyBboxPatch( (self.bbox.xmin, self.bbox.ymin), abs(self.bbox.width), abs(self.bbox.height), boxstyle="round, pad=%f" % self.pad_in, linewidth=1, facecolor=self._initial_color, alpha=0.3, )
def make_box(self) -> FancyBboxPatch: # noinspection PyTypeChecker return FancyBboxPatch( (self.bbox.xmin, self.bbox.ymin), abs(self.bbox.width), abs(self.bbox.height), boxstyle="round, pad=%f" % self.pad_in, linewidth=THERMAL_CHART_LINE_W_PX, facecolor='w', alpha=1.0, )
def draw_bbox(bb, facecolor): # boxstyle=square with pad=0, i.e. bbox itself. p_bbox = FancyBboxPatch( (bb.xmin, bb.ymin), abs(bb.width), abs(bb.height), boxstyle="round,pad=0.2", ec="k", fc=facecolor, ) ax.add_patch(p_bbox)
def draw_bbox(ax, bb): # boxstyle=square with pad=0, i.e. bbox itself. p_bbox = FancyBboxPatch( (bb.xmin, bb.ymin), abs(bb.width), abs(bb.height), boxstyle='square,pad=0.', ec='k', fc='none', zorder=10., ) ax.add_patch(p_bbox) return
def make_box(self) -> FancyBboxPatch: # noinspection PyTypeChecker return FancyBboxPatch( (self.bbox.xmin, self.bbox.ymin), abs(self.bbox.width), abs(self.bbox.height), boxstyle="round, pad=%f" % self.pad_in, fill=False, edgecolor=_make_string_color(self.current_param)[0], linewidth=1, facecolor=None, alpha=THERMAL_CHART_LINE_ALPHA, )
def plot_patch(self, fig): """ Plop the box for this Isotope on a figure. """ from matplotlib.patches import FancyBboxPatch fig.gca().add_patch( FancyBboxPatch(self._plot_nz + self._label_pad, self._box_size, self._box_size, ec='black', fc='none', boxstyle=('round,pad=%s' % self._label_pad), ls='solid'))
def null_box(x, y, width=.7, height=.9): ''' Grey null box for MeMO plots. ''' width = width - .2 height = height - .2 rect = FancyBboxPatch([x - width / 2, y - height / 2], width, height, facecolor='grey', edgecolor='black', alpha=.5, mutation_scale=.33) return rect
def make_info_box(corner: float = CORNER, pad_in: float = PAD_IN, **kwargs) -> FancyBboxPatch: box = Bbox([[corner, corner], [(1 - corner), (1 - corner)]]) # SUPPRESS-LINTER <definitely correct> # noinspection PyTypeChecker return FancyBboxPatch( (box.xmin, box.ymin), abs(box.width), abs(box.height), boxstyle="round, pad=%f" % pad_in, **kwargs, )
def create_rect_patch(ec="#000000", fc=None): _box = AuxTransformBox(transforms.IdentityTransform()) rect = FancyBboxPatch( xy=(0, 0), width=0.02, height=0.02, boxstyle='square', ec=ec, fc=fc, mutation_scale=14, # font size transform=trans, alpha=1.0 if (ec is not None or fc is not None) else 0.0) _box.add_artist(rect) return _box
def draw(self, context: dict) -> None: self.plus_feature.draw(dict()) axis = plt.gca() for (row, column), letter in self.setup.items(): axis.add_patch( plt.Circle((column + .5, row + .5), radius=.4, fill=True, color=self.CIRCLES[letter])) # noinspection PyTypeChecker axis.add_patch( FancyBboxPatch((2.3, 5.3), 6.4, 0.4, boxstyle='round, pad=0.2', fill=False))
def get_node_patch(node_center_x, node_center_y): width = get_length(12 * 5) height = get_length(12 * 1) node_patch = FancyBboxPatch( [node_center_x - width / 2, node_center_y - height / 2], width, height, edgecolor="blue", facecolor="lightblue", linewidth=1, boxstyle=BoxStyle("round", pad=0.4, rounding_size=.8), mutation_scale=10) return node_patch
def test1(ax): # a fancy box with round corners. pad=0.1 p_fancy = FancyBboxPatch((bb.xmin, bb.ymin), abs(bb.width), abs(bb.height), boxstyle="round,pad=0.1", fc=(1., .8, 1.), ec=(1., 0.5, 1.)) ax.add_patch(p_fancy) ax.text(0.1, 0.8, r' boxstyle="round,pad=0.1"', size=10, transform=ax.transAxes) draw_bbox(ax, bb)
def draw(self, structures, confidence, padding): _, _, w_win, h_win = self.ax.get_window_extent().bounds wh_ratio = w_win / h_win self.ax.axis('off') self.ax.axis('equal') self.ax.axis([0, wh_ratio, 0, 1]) n_col, n_row = len(structures), len(confidence) w = (wh_ratio - padding * (n_col + 1)) / n_col h = (1 - padding * (n_row + 1)) / n_row label_kwargs = dict(fontsize=20) y = padding for r in range(n_row): self.ax.text(0, y + h / 2, confidence[r], ha='right', va='center', rotation=90, **label_kwargs) x = padding for c in range(n_col): if r == 0: self.ax.text(x + w / 2, 1, structures[c], ha='center', va='bottom', **label_kwargs) draw_structure(self.ax, (x + padding, y + padding, w - padding * 2, h - padding * 2), structures[c]) button = FancyBboxPatch( (x, y), w, h, boxstyle='Round,pad=0,rounding_size=0.05', alpha=0.2, color='gray', lw=4, picker=True) self.button2idx[button] = (structures[c], confidence[r]) self.idx2button[structures[c]].append(button) self.ax.add_patch(button) x += w + padding y += h + padding
def draw_nodes(nodes, node_padding, node_mutation_scale, fig, sf): """Create a list of FancyBbox Patches, one for each node. Args: nodes (iterable collection of _Node): collection of nodes Returns: list of matplotlib.patches.FancyBboxPatch """ node_patches = [] print("WIDTH_SHIFT, HEIGHT_SHIFT: ", WIDTH_SHIFT, HEIGHT_SHIFT) for node in nodes: # width = len(node.name)*node.font_size/72 # height = node.font_size/72 # node_center_x = node.center.x/72 + .5 # node_center_y = node.center.y/72 + .5 # lower_left_point_x = node_center_x - node.width/2 # lower_left_point_y = node_center_y - node.height/2 fbbp = FancyBboxPatch( # node.lower_left_point, # node.width, # node.height, [ sf * node.lower_left_point[0] / 72 + WIDTH_SHIFT, sf * node.lower_left_point[1] / 72 + HEIGHT_SHIFT ], sf * node.width / 72, sf * node.height / 72, edgecolor=node.edge_color, facecolor=node.fill_color, linewidth=node.edge_width, boxstyle=BoxStyle( "round", pad=0, # pad=node_padding if node_padding else 0.1, rounding_size=.1), # mutation_scale=node_mutation_scale if node_mutation_scale else 1, transform=fig.dpi_scale_trans) node_patches.append(fbbp) return node_patches
def prettyaxesbox(ax=None, linewidth=None, edgecolor="k", facecolor="none", front=True): """ Replaces the box around the axes with a fancybox. This makes it an actual box and not just four lines. If linewidth is None, uses the initialized linewidth. """ # First, figure out what axes object to use. if ax is None: ax = plt.gca() # Get linewidth if necessary. if linewidth is None: linewidth = 1 # Now we're going to make the box around the axes look better. ap = ax.axesPatch zorders = [c.get_zorder() for c in ax.get_children()] if front: z = max(zorders) + 1 else: z = min(zorders) - 1 prettybox = FancyBboxPatch(ap.get_xy(), ap.get_width(), ap.get_height(), boxstyle="square,pad=0.", ec=edgecolor, fc=facecolor, transform=ap.get_transform(), lw=linewidth, zorder=z) # Make current box invisible and make our better one. ap.set_edgecolor("none") ax.set_frame_on(False) ax.add_patch(prettybox) prettybox.set_clip_on(False) plt.draw() return prettybox