def dna_logo(self, save=False, show=True, count=True, ax=None): freq = np.array(self._freq(count)) en = 2.88539008 / max(sum(self.count), 1.5) info = (np.log(5) / np.log(2) - en - self.entropy(count=count)) if np.min(info) < 0: info -= np.min(info) height = (freq.T * info).T order = ['A', 'G', 'C', 'T', '-'] height = [ sorted(list(zip(order, i)), key=lambda x: x[1]) for i in height ] fp = FontProperties(family="monospace", weight="bold") LETTERS = { "T": TextPath((-0.395, 0), "T", size=1.35, prop=fp), "G": TextPath((-0.395, 0), "G", size=1.35, prop=fp), "A": TextPath((-0.395, 0), "A", size=1.35, prop=fp), "C": TextPath((-0.395, 0), "C", size=1.35, prop=fp), "-": TextPath((-0.395, 0), "I", size=1.35, prop=fp) } COLOR_SCHEME = { 'G': 'orange', 'A': 'red', 'C': 'blue', 'T': 'darkgreen', '-': 'black' } if ax: ax = ax drawx = False else: fig, ax = plt.subplots(figsize=(7, 2)) drawx = True for x, scores in enumerate(height): y = 0 for letter, score in scores: text = LETTERS[letter] t = mpl.transforms.Affine2D().scale(1.2, score) + \ mpl.transforms.Affine2D().translate(x+1, y) + ax.transData p = PathPatch(text, lw=0, fc=COLOR_SCHEME[letter], transform=t) ax.add_artist(p) y += score x_tick_label = ([ str(k + 1) + '\n' + i[-1][0] for k, i in enumerate(height) ] if drawx else [str(k + 1) for k, i in enumerate(height)]) ax.set_title('{} Total count: {}'.format(str(self.name), sum(self.count)), fontsize=6) ax.set_xticks(range(1, len(height) + 1), ) ax.set_xticklabels(x_tick_label) ax.set_xlim((0, len(height) + 1)) ax.set_ylim((0, 2.33)) ax.tick_params(axis='both', which='both', labelsize=6) if save: plt.tight_layout() save = save if isinstance(save, str) else str(self.name) + '_logo.svg' plt.savefig(str(save), dpi=150) if show: plt.tight_layout() plt.show()
def plot_logo(self): LETTERS = { "T": TextPath((-0.305, 0), "T", size=1, prop=fp), "G": TextPath((-0.384, 0), "G", size=1, prop=fp), "A": TextPath((-0.35, 0), "A", size=1, prop=fp), "C": TextPath((-0.366, 0), "C", size=1, prop=fp) } COLOR_SCHEME = { 'G': 'orange', 'A': "#CC0000", 'C': 'mediumblue', 'T': 'darkgreen' } def add_letter(base, x, y, scale, ax): """ Add letter to axis at positions x/y""" text = LETTERS[base] t = mpl.transforms.Affine2D().scale(1*globscale, scale*globscale) + \ mpl.transforms.Affine2D().translate(x,y) + ax.transData p = PathPatch(text, lw=0, fc=COLOR_SCHEME[base], transform=t) if ax != None: ax.add_artist(p) return p self.calc_bit_score() self.length = self.bits.shape[1] fp = FontProperties(family='sans-serif', weight="bold") globscale = 1.35 #Plot logo fig, ax = plt.subplots(figsize=(10, 3)) max_y = 0 for position in range(self.length): #0-based positions base_bit_tups = zip(OneMotif.bases, self.bits[:, position]) #Go through bases sorted from lowest to highest bit score y = 0 #position to place letter for (base, score) in sorted(base_bit_tups, key=lambda tup: tup[1]): add_letter(base, position + 1, y, score, ax) y += score max_y = max(max_y, y) plt.xticks(range(1, self.length + 1)) plt.xlim((0.2, self.length + 0.8)) plt.ylim((0, max_y)) plt.tight_layout() return (fig, ax)
def _set_mathtext_path(self): """ Draws mathtext markers '$...$' using TextPath object. Submitted by tcb """ from matplotlib.text import TextPath from matplotlib.font_manager import FontProperties # again, the properties could be initialised just once outside # this function # Font size is irrelevant here, it will be rescaled based on # the drawn size later props = FontProperties(size=1.0) text = TextPath(xy=(0, 0), s=self.get_marker(), fontproperties=props, usetex=rcParams['text.usetex']) if len(text.vertices) == 0: return xmin, ymin = text.vertices.min(axis=0) xmax, ymax = text.vertices.max(axis=0) width = xmax - xmin height = ymax - ymin max_dim = max(width, height) self._transform = Affine2D() \ .translate(-xmin + 0.5 * -width, -ymin + 0.5 * -height) \ .scale(1.0 / max_dim) self._path = text self._snap = False
def display_points(self, image_idx, image): visible_points_coords = self.database.get_visible_points_coords(image) self.clear_images(image_idx) for point_id, coords in visible_points_coords.items(): color = distinct_colors[divmod(hash(point_id), 19)[1]] text_path = TextPath((0, 0), point_id, size=10) p1 = PathPatch(text_path, transform=IdentityTransform(), alpha=1, color=color) offsetbox2 = AuxTransformBox(IdentityTransform()) offsetbox2.add_artist(p1) ab = AnnotationBbox(offsetbox2, ((coords[0] + 30), (coords[1] + 30)), bboxprops=dict(alpha=0.05)) circle = mpatches.Circle((coords[0], coords[1]), 20, color=color, fill=False) self.plt_artists[image_idx].append(ab) self.plt_artists[image_idx].append(circle) self.subplots[image_idx].add_artist(ab) self.subplots[image_idx].add_artist(circle) self.figures[image_idx].canvas.draw_idle()
def get_patch(self, **kwargs): patch = [PolygonPatch(self.shape, fc=kwargs.get('color', FURNITURE_COLORS['skin']), ec=kwargs.get('color', FURNITURE_COLORS['gray'])), PathPatch(TextPath((self.x, self.y), self.name, size=0.5), fc='black', ec='black')] if SHOW_HIT_BOXES: patch.append(get_hit_box_visualization(self.hit_box_shape)) return patch
def display_points(self, view): visible_points_coords = self.database.get_visible_points_coords( view.current_image) self.clear_artists(view) for point_id, coords in visible_points_coords.items(): color = distinct_colors[divmod(hash(point_id), 19)[1]] text_path = TextPath((0, 0), point_id, size=10) p1 = PathPatch(text_path, transform=IdentityTransform(), alpha=1, color=color) offsetbox2 = AuxTransformBox(IdentityTransform()) offsetbox2.add_artist(p1) ab = AnnotationBbox(offsetbox2, ((coords[0] + 30), (coords[1] + 30)), bboxprops=dict(alpha=0.05)) circle = mpatches.Circle((coords[0], coords[1]), 10, color=color, fill=False) dot = mpatches.Circle((coords[0], coords[1]), 2, color=color, fill=False) for art in (ab, circle, dot): view.plt_artists.append(art) view.subplot.add_artist(art) view.figure.canvas.draw()
def _set_mathtext_path(self): """ Draw mathtext markers '$...$' using TextPath object. Submitted by tcb """ from matplotlib.text import TextPath # again, the properties could be initialised just once outside # this function text = TextPath(xy=(0, 0), s=self.get_marker(), usetex=rcParams['text.usetex']) if len(text.vertices) == 0: return xmin, ymin = text.vertices.min(axis=0) xmax, ymax = text.vertices.max(axis=0) width = xmax - xmin height = ymax - ymin max_dim = max(width, height) self._transform = Affine2D() \ .translate(-xmin + 0.5 * -width, -ymin + 0.5 * -height) \ .scale(1.0 / max_dim) self._path = text self._snap = False
def text3d(self, xyz, s, zdir="z", zorder=1, size=None, angle=0, usetex=False, **kwargs): d = {'-x': np.array([[-1.0, 0.0, 0], [0.0, 1.0, 0.0], [0, 0.0, -1]]), '-y': np.array([[0.0, 1.0, 0], [-1.0, 0.0, 0.0], [0, 0.0, 1]]), '-z': np.array([[1.0, 0.0, 0], [0.0, -1.0, 0.0], [0, 0.0, -1]])} x, y, z = xyz if "y" in zdir: x, y, z = x, z, y elif "x" in zdir: x, y, z = y, z, x elif "z" in zdir: x, y, z = x, y, z text_path = TextPath((-0.5, -0.5), s, size=size, usetex=usetex) aff = Affine2D() trans = aff.rotate(angle) # apply additional rotation of text_paths if side is dark if '-' in zdir: trans._mtx = np.dot(d[zdir], trans._mtx) trans = trans.translate(x, y) p = PathPatch(trans.transform_path(text_path), **kwargs) self.ax.add_patch(p) art3d.pathpatch_2d_to_3d(p, z=z, zdir=zdir) p.stable_zorder = zorder return p
def draw_text(txt, x, y, w, h, gca): v_max_scale = 0.7 h_max_scale = 0.8 rotate = (abs(w) < abs(h)) fp = FontProperties(family="arial") fsize = w if rotate else h tp = TextPath((0, 0), txt, size=fsize, prop=fp) bw, bh = w, h (__, __, tw, th) = tp.get_extents().bounds if rotate: tp = tp.transformed(Affine2D().rotate_deg(90).translate(th, 0)) bw, bh = bh, bw if tw < h_max_scale * bw: scale = v_max_scale * bh / th else: scale = h_max_scale * bw / tw tp = tp.transformed(Affine2D().scale(scale)) (__, __, tw, th) = tp.get_extents().bounds tp = tp.transformed(Affine2D().translate(x + (w - tw) / 2, y + (h - th) / 2)) txt = PathPatch(tp, linewidth=0.3, facecolor="0", edgecolor="0") gca.add_patch(txt)
def curly(ax, x, y, scale, color): # adapted from # https://stackoverflow.com/questions/50039667/matplotlib-scale-text-curly-brackets # doesn't behave as expected tp = TextPath((0, 0), "}", size=.2) trans = mtrans.Affine2D().scale(1, scale) + \ mtrans.Affine2D().translate(0.5, y/5) + ax.transAxes pp = PathPatch(tp, lw=0, fc=color, transform=trans) ax.add_artist(pp)
def _letterAt(letter, x, y, yscale=1, ax=None): fp = FontProperties(family="Arial", weight="bold") globscale = 1.35 LETTERS = { "T": TextPath((-0.305, 0), "T", size=1, prop=fp), "G": TextPath((-0.384, 0), "G", size=1, prop=fp), "A": TextPath((-0.35, 0), "A", size=1, prop=fp), "C": TextPath((-0.366, 0), "C", size=1, prop=fp) } COLOR_SCHEME = {'G': 'orange', 'A': 'red', 'C': 'blue', 'T': 'darkgreen'} text = LETTERS[letter] t = mpl.transforms.Affine2D().scale(1*globscale, yscale*globscale) + \ mpl.transforms.Affine2D().translate(x,y) + ax.transData p = PathPatch(text, lw=0, fc=COLOR_SCHEME[letter], transform=t) if ax != None: ax.add_artist(p) return p
def addLetter(char, x, y, height, color): text = TextPath((0, 0), char, size=1, prop=fontprop) bbox = text.get_extents() (tx0, ty0), tw, th = bbox.min, bbox.width, bbox.height trans = Affine2D.identity() \ .translate(-tx0, -ty0) \ .scale(0.9/tw, height/th) \ .translate(x+0.5, y) t = trans.transform_path(text) pylab.gca().add_patch(PathPatch(t, fc=color, ec='none'))
def addletter(let, x, y, height, color, alpha=1): text = TextPath((0, 0), let, size=1, prop=fontprop) bbox = text.get_extents() tx0, ty0 = bbox.min tw, th = bbox.width, bbox.height trans = Affine2D.identity() \ .translate(-tx0,-ty0) \ .scale(0.9/tw,height/th) \ .translate(x,y) t = trans.transform_path(text) pylab.gca().add_patch(PathPatch(t, fc=color, ec='none', alpha=alpha))
def text3d(ax, xyz, s, zdir="z", size=None, angle=0, **kwargs): x, y, z = xyz if zdir == "y": x, y, z = x, z, y elif zdir == "x": x, y, z = y, z, x else: x, y, z = x, y, z text_path = TextPath((0, 0), s, size=size) trans = Affine2D().rotate(angle).translate(x, y) p = PathPatch(trans.transform_path(text_path), **kwargs) ax.add_patch(p) art3d.pathpatch_2d_to_3d(p, z=z, zdir=zdir)
def _plot_logo_from_scores(all_scores): fp = FontProperties(family="Arial", weight="bold") globscale = 1.35 LETTERS = { "T": TextPath((-0.305, 0), "T", size=1, prop=fp), "G": TextPath((-0.384, 0), "G", size=1, prop=fp), "A": TextPath((-0.35, 0), "A", size=1, prop=fp), "C": TextPath((-0.366, 0), "C", size=1, prop=fp) } COLOR_SCHEME = {'G': 'orange', 'A': 'red', 'C': 'blue', 'T': 'darkgreen'} def letterAt(letter, x, y, yscale=1, ax=None): text = LETTERS[letter] t = mpl.transforms.Affine2D().scale(1*globscale, yscale*globscale) + \ mpl.transforms.Affine2D().translate(x,y) + ax.transData p = PathPatch(text, lw=0, fc=COLOR_SCHEME[letter], transform=t) if ax != None: ax.add_artist(p) return p fig, ax = plt.subplots(figsize=(10, 3)) x = 1 maxi = 0 for scores in all_scores: y = 0 for base, score in scores: letterAt(base, x, y, score, ax) y += score x += 1 maxi = max(maxi, y) plt.xticks(range(1, x)) plt.xlim((0, x)) plt.ylim((0, maxi)) plt.tight_layout() return fig, ax
def letterAt(letter, x, y, yscale=1, ax=None): """ This function is used in the sequence_logo function, and is not exported in the module. From https://stackoverflow.com/a/42631740/2312821 """ fp = FontProperties(family="DejaVu Sans", weight="bold") globscale = 1.35 LETTERS = { "T" : TextPath((-0.305, 0), "T", size=1, prop=fp), "G" : TextPath((-0.384, 0), "G", size=1, prop=fp), "A" : TextPath((-0.35, 0), "A", size=1, prop=fp), "C" : TextPath((-0.366, 0), "C", size=1, prop=fp) } COLOR_SCHEME = {'G': 'orange', 'A': 'red', 'C': 'blue', 'T': 'darkgreen'} text = LETTERS[letter] t = mpl.transforms.Affine2D().scale(1*globscale, yscale*globscale) + \ mpl.transforms.Affine2D().translate(x,y) + ax.transData p = PathPatch(text, lw=0, fc=COLOR_SCHEME[letter], transform=t) if ax != None: ax.add_artist(p) return p
def text_on_2D(ax, s, xy=(0.5, 0.95), xlim=None, ylim=None, size=None, angle=0.0, usetex=False, center=True, aspect_ratio=1.0, **kwargs): #FIXME expand and add to text_on_the_wall #xlim = ax.get_xlim() #ylim = ax.get_ylim() #aspect_ratio = (ylim[1] - ylim[0])/(ylim[1] - ylim[0]) #size = 0.8 #center = True #angle = 0.0 #usetex=False #s = r"$\delta=0.00$" if xlim == None: xlim = ax.get_xlim() if ylim == None: ylim = ax.get_ylim() x = xlim[0] + (xlim[1] - xlim[0]) * xy[0] y = ylim[0] + (ylim[1] - ylim[0]) * xy[1] xy1 = (x, y) text_path = TextPath((0, 0), s, size=size, usetex=usetex) #Scale by aspect ratio scale_path = Affine2D().scale(1.0, sy=aspect_ratio) text_path = scale_path.transform_path(text_path) #Get bbox to center text bbox = text_path.get_extents() bbox_points = bbox.get_points() _b = bbox_points.sum(axis=0) / 2 if center == True: trans = Affine2D().rotate(angle).translate(xy1[0] - _b[0], xy1[1] - _b[1]) else: trans = Affine2D().rotate(angle).translate(xy1[0], xy1[1] - _b[1]) tp = trans.transform_path(text_path) p1 = PathPatch(tp, **kwargs) ax.add_patch(p1)
def letterAt(letter, x, y, yscale=1, ax=None, color=None, alpha=1.0): #fp = FontProperties(family="Arial", weight="bold") #fp = FontProperties(family="Ubuntu", weight="bold") fp = FontProperties(family="DejaVu Sans", weight="bold") globscale = 1.35 LETTERS = { "T": TextPath((-0.305, 0), "T", size=1, prop=fp), "G": TextPath((-0.384, 0), "G", size=1, prop=fp), "A": TextPath((-0.35, 0), "A", size=1, prop=fp), "C": TextPath((-0.366, 0), "C", size=1, prop=fp), "UP": TextPath((-0.488, 0), '$\\Uparrow$', size=1, prop=fp), "DN": TextPath((-0.488, 0), '$\\Downarrow$', size=1, prop=fp), "(": TextPath((-0.25, 0), "(", size=1, prop=fp), ".": TextPath((-0.125, 0), "-", size=1, prop=fp), ")": TextPath((-0.1, 0), ")", size=1, prop=fp) } COLOR_SCHEME = { 'G': 'orange', 'A': 'red', 'C': 'blue', 'T': 'darkgreen', 'UP': 'green', 'DN': 'red', '(': 'black', '.': 'black', ')': 'black' } text = LETTERS[letter] chosen_color = COLOR_SCHEME[letter] if color is not None: chosen_color = color t = mpl.transforms.Affine2D().scale(1*globscale, yscale*globscale) + \ mpl.transforms.Affine2D().translate(x,y) + ax.transData p = PathPatch(text, lw=0, fc=chosen_color, alpha=alpha, transform=t) if ax != None: ax.add_artist(p) return p
def text3d(ax, xyz, s, zdir="z", size=0.1, angle=0, **kwargs): x, y, z = xyz if zdir == "y": xy, z = (x, z), y elif zdir == "x": xy, z = (y, z), x else: xy, z = (x, y), z path = TextPath((0, 0), s, size=size, prop=FontProperties(family="Roboto")) V = path.vertices V[:, 0] -= (V[:, 0].max() - V[:, 0].min()) / 2 trans = Affine2D().rotate(angle).translate(xy[0], xy[1]) path = PathPatch(trans.transform_path(path), **kwargs) ax.add_patch(path) art3d.pathpatch_2d_to_3d(path, z=z, zdir=zdir)
def plot(table, word, filename): """ precondition: the table and word must be valid poscondition: plots the words and their frequencies """ sorted_word, sorted_count = sort(table) plt.ylabel('Frequency') plt.xlabel("Rank of Word" + " (" + str(word) + " is" + " rank " + str(sorted_word.index(word) + 1) + ")") plt.title('Word Frequencies: ' + str(filename)) plt.loglog(sorted_word, sorted_count) plt.xscale('symlog') label = TextPath((-20, 10), str(word), linewidth=50) plt.plot(word, get(table, word), marker=label, markersize=40, color="red") plt.plot(word, get(table, word), marker='*', markersize=10, color="red") plt.show()
def text3d(ax, xyz, s, zdir="z", size=None, angle=0, usetex=False, **kwargs): x, y, z = xyz if zdir == "y": xy1, z1 = (x, z), y elif zdir == "y": xy1, z1 = (y, z), x else: xy1, z1 = (x, y), z text_path = TextPath((0, 0), s, size=size, usetex=usetex) trans = Affine2D().rotate(angle).translate(xy1[0], xy1[1]) p1 = PathPatch(trans.transform_path(text_path), **kwargs) ax.add_patch(p1) art3d.pathpatch_2d_to_3d(p1, z=z1, zdir=zdir)
def text3d(ax, xyz, s, zdir="z", size=0.1, angle=0, font='Arial', weight='normal', ha='left', va='center', **kwargs): x, y, z = xyz xlim, ylim, zlim = ax.get_xlim(), ax.get_ylim(), ax.get_zlim() xmin, xmax, ymin, ymax, zmin, zmax = xlim[0], xlim[1], ylim[0], ylim[ 1], zlim[0], zlim[1] xlen, ylen, zlen = xmax - xmin, ymax - ymin, zmax - zmin minLen_axis = np.min([xlen, ylen, zlen]) aspect = ax.get_box_aspect() fontscale = 1 if zdir == "y": xy, z, fontscale = (x, z), y, (xlen / zlen) / (aspect[0] / aspect[2]) elif zdir == "x": xy, z, fontscale = (y, z), x, (ylen / zlen) / (aspect[1] / aspect[2]) else: xy, z, fontscale = (x, y), z, (xlen / ylen) / (aspect[0] / aspect[1]) path = TextPath((0, 0), s, size=size, prop=FontProperties(family=font, weight=weight)) V = path.vertices if (ha == 'center'): V[:, 0] -= (V[:, 0].max() - V[:, 0].min()) / 2 # 居中 elif (ha == 'right'): V[:, 0] -= V[:, 0].max() if (va == 'center'): V[:, 1] -= (V[:, 1].max() - V[:, 1].min()) / 2 # 居中 elif (va == 'top'): V[:, 1] -= V[:, 1].max() trans = Affine2D().rotate(angle / 180 * np.pi).scale( 1, 1 / fontscale).translate(xy[0], xy[1]) path = PathPatch(trans.transform_path(path), clip_on=False, **kwargs) ax.add_patch(path) art3d.pathpatch_2d_to_3d(path, z=z, zdir=zdir)
def text_on_the_wall(ax, xyz, s, zdir="z", size=None, angle=0, usetex=False, center=True, aspect_ratio=1.0, **kwargs): x, y, z = xyz if zdir == "y": xy1, z1 = (x, z), y elif zdir == "x": xy1, z1 = (y, z), x else: xy1, z1 = (x, y), z text_path = TextPath((0, 0), s, size=size, usetex=usetex) #Scale by aspect ratio scale_path = Affine2D().scale(1.0, sy=aspect_ratio) text_path = scale_path.transform_path(text_path) #Get bbox to center text bbox = text_path.get_extents() bbox_points = bbox.get_points() _b = bbox_points.sum(axis=0) / 2 if center == True: trans = Affine2D().rotate(angle).translate(xy1[0] - _b[0], xy1[1] - _b[1]) else: trans = Affine2D().rotate(angle).translate(xy1[0], xy1[1] - _b[1]) tp = trans.transform_path(text_path) p1 = PathPatch(tp, **kwargs) ax.add_patch(p1) art3d.pathpatch_2d_to_3d(p1, z=z1, zdir=zdir)
def text3d(ax, xyz, s, zdir="z", size=None, angle=0, usetex=False, **kwargs): ''' Plots the string 's' on the axes 'ax', with position 'xyz', size 'size', and rotation angle 'angle'. 'zdir' gives the axis which is to be treated as the third dimension. usetex is a boolean indicating whether the string should be interpreted as latex or not. Any additional keyword arguments are passed on to transform_path. Note: zdir affects the interpretation of xyz. ''' x, y, z = xyz if zdir == "y": xy1, z1 = (x, z), y elif zdir == "y": xy1, z1 = (y, z), x else: xy1, z1 = (x, y), z text_path = TextPath((0, 0), s, size=size, usetex=usetex) trans = Affine2D().rotate(angle).translate(xy1[0], xy1[1]) p1 = PathPatch(trans.transform_path(text_path), **kwargs) ax.add_patch(p1) art3d.pathpatch_2d_to_3d(p1, z=z1, zdir=zdir)
def text3d(ax, xyz, s, zdir="z", size=None, angle=0, usetex=False, **kwargs): """ Plots the string *s* on the axes *ax*, with position *xyz*, size *size*, and rotation angle *angle*. *zdir* gives the axis which is to be treated as the third dimension. *usetex* is a boolean indicating whether the string should be run through a LaTeX subprocess or not. Any additional keyword arguments are forwarded to `.transform_path`. Note: zdir affects the interpretation of xyz. """ x, y, z = xyz if zdir == "y": xy1, z1 = (x, z), y elif zdir == "x": xy1, z1 = (y, z), x else: xy1, z1 = (x, y), z text_path = TextPath((0, 0), s, size=size, usetex=usetex) trans = Affine2D().rotate(angle).translate(xy1[0], xy1[1]) p1 = PathPatch(trans.transform_path(text_path), **kwargs) ax.add_patch(p1) art3d.pathpatch_2d_to_3d(p1, z=z1, zdir=zdir)
if 1: usetex = plt.rcParams["text.usetex"] fig = plt.figure(1) # EXAMPLE 1 ax = plt.subplot(211) from matplotlib._png import read_png fn = get_sample_data("grace_hopper.png", asfileobj=False) arr = read_png(fn) text_path = TextPath((0, 0), "!?", size=150) p = PathClippedImagePatch(text_path, arr, ec="k", transform=IdentityTransform()) #p.set_clip_on(False) # make offset box offsetbox = AuxTransformBox(IdentityTransform()) offsetbox.add_artist(p) # make anchored offset box ao = AnchoredOffsetbox(loc=2, child=offsetbox, frameon=True, borderpad=0.2) ax.add_artist(ao)
ax1.axis('off') except: print('image missing') # Scatter plot ax2 = fig.add_subplot(1, 2, 2) ax2.plot(df_red['x'], df_red['y'], ".", label='Red', color='r') ax2.plot(df_green['x'], df_green['y'], ".", label='Green', color='g') ax2.plot(df_blue['x'], df_blue['y'], ".", label='Blue', color='b') ax2.plot(df_yellow['x'], df_yellow['y'], ".", label='Yellow', color='y') #Candidates for c in candidates: ax2.plot(c[1], c[2], marker=TextPath((0, 0), c[0]), markersize=20, color='k') ax2.set_xlim(-10, 10) ax2.set_ylim(-10, 10) ax2.set_title('Political Compass') ax2.set_xlabel('Planned Economy <-- Economics --> Free Market') ax2.set_ylabel('Liberal <-- Government --> Authoritarian') lgd2 = ax2.legend(loc=1) fig.savefig("Simulated_Spectrum", dpi=300) if centerists: mean_center = [0, 0] cov_center = [[5, 0], [0, 5]] # diagonal covariance pos_center = np.random.multivariate_normal(mean_center, cov_center, 3500)
def __init__(self, transform, label_x, label_y, length=0.15, fontsize=0.08, loc=2, angle=0, aspect_ratio=1, pad=0.4, borderpad=0.4, frameon=False, color='w', alpha=1, sep_x=0.01, sep_y=0, fontproperties=None, back_length=0.15, head_width=10, head_length=15, tail_width=2, text_props=None, arrow_props=None, **kwargs): """ Draw two perpendicular arrows to indicate directions. Parameters ---------- transform : `matplotlib.transforms.Transform` The transformation object for the coordinate system in use, i.e., :attr:`matplotlib.axes.Axes.transAxes`. label_x, label_y : str Label text for the x and y arrows length : float, optional, default: 0.15 Length of the arrow, given in coordinates of *transform*. fontsize : float, optional, default: 0.08 Size of label strings, given in coordinates of *transform*. loc : int, optional, default: 2 Location of the direction arrows. 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 angle : float, optional, default: 0 The angle of the arrows in degrees. aspect_ratio : float, optional, default: 1 The ratio of the length of arrow_x and arrow_y. Negative numbers can be used to change the direction. pad : float, optional, default: 0.4 Padding around the labels and arrows, in fraction of the font size. borderpad : float, optional, default: 0.4 Border padding, in fraction of the font size. frameon : bool, optional, default: False If True, draw a box around the arrows and labels. color : str, optional, default: 'white' Color for the arrows and labels. alpha : float, optional, default: 1 Alpha values of the arrows and labels sep_x, sep_y : float, optional, default: 0.01 and 0 respectively Separation between the arrows and labels in coordinates of *transform*. fontproperties : `matplotlib.font_manager.FontProperties`, optional Font properties for the label text. back_length : float, optional, default: 0.15 Fraction of the arrow behind the arrow crossing. head_width : float, optional, default: 10 Width of arrow head, sent to ArrowStyle. head_length : float, optional, default: 15 Length of arrow head, sent to ArrowStyle. tail_width : float, optional, default: 2 Width of arrow tail, sent to ArrowStyle. text_props, arrow_props : dict Properties of the text and arrows, passed to `.textpath.TextPath` and `.patches.FancyArrowPatch`. **kwargs Keyworded arguments to pass to :class:`matplotlib.offsetbox.AnchoredOffsetbox`. Attributes ---------- arrow_x, arrow_y : `matplotlib.patches.FancyArrowPatch` Arrow x and y text_path_x, text_path_y : `matplotlib.textpath.TextPath` Path for arrow labels p_x, p_y : `matplotlib.patches.PathPatch` Patch for arrow labels box : `matplotlib.offsetbox.AuxTransformBox` Container for the arrows and labels. Notes ----- If *prop* is passed as a keyword argument, but *fontproperties* is not, then *prop* is be assumed to be the intended *fontproperties*. Using both *prop* and *fontproperties* is not supported. Examples -------- >>> import matplotlib.pyplot as plt >>> import numpy as np >>> from mpl_toolkits.axes_grid1.anchored_artists import ( ... AnchoredDirectionArrows) >>> fig, ax = plt.subplots() >>> ax.imshow(np.random.random((10, 10))) >>> arrows = AnchoredDirectionArrows(ax.transAxes, '111', '110') >>> ax.add_artist(arrows) >>> fig.show() Using several of the optional parameters, creating downward pointing arrow and high contrast text labels. >>> import matplotlib.font_manager as fm >>> fontprops = fm.FontProperties(family='monospace') >>> arrows = AnchoredDirectionArrows(ax.transAxes, 'East', 'South', ... loc='lower left', color='k', ... aspect_ratio=-1, sep_x=0.02, ... sep_y=-0.01, ... text_props={'ec':'w', 'fc':'k'}, ... fontproperties=fontprops) """ if arrow_props is None: arrow_props = {} if text_props is None: text_props = {} arrowstyle = ArrowStyle("Simple", head_width=head_width, head_length=head_length, tail_width=tail_width) if fontproperties is None and 'prop' in kwargs: fontproperties = kwargs.pop('prop') if 'color' not in arrow_props: arrow_props['color'] = color if 'alpha' not in arrow_props: arrow_props['alpha'] = alpha if 'color' not in text_props: text_props['color'] = color if 'alpha' not in text_props: text_props['alpha'] = alpha t_start = transform t_end = t_start + transforms.Affine2D().rotate_deg(angle) self.box = AuxTransformBox(t_end) length_x = length length_y = length * aspect_ratio self.arrow_x = FancyArrowPatch((0, back_length * length_y), (length_x, back_length * length_y), arrowstyle=arrowstyle, shrinkA=0.0, shrinkB=0.0, **arrow_props) self.arrow_y = FancyArrowPatch((back_length * length_x, 0), (back_length * length_x, length_y), arrowstyle=arrowstyle, shrinkA=0.0, shrinkB=0.0, **arrow_props) self.box.add_artist(self.arrow_x) self.box.add_artist(self.arrow_y) text_path_x = TextPath( (length_x + sep_x, back_length * length_y + sep_y), label_x, size=fontsize, prop=fontproperties) self.p_x = PathPatch(text_path_x, transform=t_start, **text_props) self.box.add_artist(self.p_x) text_path_y = TextPath((length_x * back_length + sep_x, length_y * (1 - back_length) + sep_y), label_y, size=fontsize, prop=fontproperties) self.p_y = PathPatch(text_path_y, **text_props) self.box.add_artist(self.p_y) AnchoredOffsetbox.__init__(self, loc, pad=pad, borderpad=borderpad, child=self.box, frameon=frameon, **kwargs)
(0.6, 0.8, 0.8), (1.0, 1.0, 1.0))} # color map: field lines (red | blue) redbl = {'red': ((0., 1., 1.), (0.5, 1., 0.), (1., 0., 0.)), 'blue': ((0., 0., 0.), (0.5, 0., 1.), (1., 1., 1.)), 'green': ((0., 0., 0.), (1., 0., 0.)), 'alpha': ((0., 0.4, 0.4), (1., 0.4, 0.4))} mne_field_grad_cols = LinearSegmentedColormap('mne_grad', yrtbc) mne_field_line_cols = LinearSegmentedColormap('mne_line', redbl) # plot gradient and contour lines im = plt.imshow(Z, cmap=mne_field_grad_cols, aspect='equal') cs = plt.contour(Z, 9, cmap=mne_field_line_cols, linewidths=1) plot_dims = np.r_[np.diff(ax.get_xbound()), np.diff(ax.get_ybound())] # create MNE clipping mask mne_path = TextPath((0, 0), 'MNE') dims = mne_path.vertices.max(0) - mne_path.vertices.min(0) vert = mne_path.vertices - dims / 2. mult = (plot_dims / dims).min() mult = [mult, -mult] # y axis is inverted (origin at top left) offset = plot_dims / 2. - center_fudge mne_clip = Path(offset + vert * mult, mne_path.codes) # apply clipping mask to field gradient and lines im.set_clip_path(mne_clip, transform=im.get_transform()) for coll in cs.collections: coll.set_clip_path(mne_clip, transform=im.get_transform()) # get final position of clipping mask mne_corners = mne_clip.get_extents().corners() # add tagline rcParams.update({'font.sans-serif': ['Cooper Hewitt'], 'font.weight': 'light'})
'M':(-0.301,0), 'N':(-0.301,0), 'P':(-0.301,0), 'Q':(-0.301,0), 'R':(-0.301,0), 'S':(-0.301,0), 'T':(-0.301,0), 'V':(-0.301,0), 'W':(-0.301,0), 'Y':(-0.301,0), 'X':(-0.301,0) } fp = FontProperties(family="Ubuntu", weight="bold") LETTERS = {i: TextPath((aa_textpaths[i]), i, size=1, prop=fp) for i in aa_letters} globscale = 1.35 # define color schemes aa_1 = {i:'blue' for i in ['R','H','K']} aa_2 = {i:'red' for i in ['D','E']} aa_3 = {i:'cyan' for i in ['S','T','N','Q']} aa_4 = {i:'green' for i in ['A','I','L','M','F','W','Y','V']} aa_5 = {i:'yellow' for i in ['C','G','P']} COLOR_SCHEME = {**aa_1,**aa_2,**aa_3,**aa_4,**aa_5} def letterAt(letter, x, y, yscale=1, ax=None): text = LETTERS[letter]