def __setup_overflow(self): bbox = self.axes.bbox box = dict(boxstyle='round', fc='white', ec='black', alpha=0.5, clip_box=bbox) self.overflowLabels['left'] = Text(0, 0.9, '', fontsize='xx-small', ha="left", va="top", bbox=box, transform=self.axes.transAxes, alpha=0.5) self.overflowLabels['right'] = Text(1, 0.9, '', fontsize='xx-small', ha="right", va="top", bbox=box, transform=self.axes.transAxes, alpha=0.5) for label in list(self.overflowLabels.values()): self.axes.add_artist(label)
def _build_plots(self, frame): self.figure = Figure(figsize=(8, 8), dpi=72) # initialized when the plot is updated: self._pick_event_handler_id = None self._plot_overlay_elements = [] self._mask_artists = [] obs_axes = (0.1, 0.3, 0.35, 0.6) # (left, bottom, width, height) self.observability_ax = self.figure.add_axes(obs_axes) self.observable_pa = Text(x=0.1, y=0.098, text="PA =", transform=self.figure.transFigure, figure=self.figure) self.figure.texts.append(self.observable_pa) self.observable_day = Text(x=0.1, y=0.058, text="Day of year =", transform=self.figure.transFigure, figure=self.figure) self.figure.texts.append(self.observable_day) detector_axes = (0.55, 0.3, 0.4, 0.6) self.detector_ax = self.figure.add_axes(detector_axes) self.detector_ax.set_aspect('equal', anchor='SE') # companion legend markers self.companion_legend_markers = [] self.companion_legend_labels = [] self.companion_info = [] v_pos = 0.2 line_height = 0.04 for i, color in enumerate((RED_GGPLOT, BLUE_GGPLOT, PURPLE_GGPLOT)): v_pos -= line_height marker = Rectangle((0.55, v_pos), width=0.01, height=0.015, facecolor=color, transform=self.figure.transFigure, figure=self.figure) self.figure.patches.append(marker) self.companion_legend_markers.append(marker) label = Text(x=0.57, y=v_pos, text="Companion {}".format(i + 1), transform=self.figure.transFigure, figure=self.figure) self.figure.texts.append(label) self.companion_legend_labels.append(label) info = Text(x=0.57, y=v_pos - line_height / 2, text="# arcsec @ # deg", transform=self.figure.transFigure, figure=self.figure) self.figure.texts.append(info) self.companion_info.append(info) self._canvas = FigureCanvasTkAgg(self.figure, master=frame) self._canvas.draw() self._canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1) self._toolbar = NavigationToolbar2TkAgg(self._canvas, frame) self._toolbar.update() self._canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1) def on_key_event(event): key_press_handler(event, self._canvas, self._toolbar) self._canvas.mpl_connect('key_press_event', on_key_event)
def test_bar_plt_xaxis_intervalrange(self): # GH 38969 # Ensure IntervalIndex x-axis produces a bar plot as expected from matplotlib.text import Text expected = [Text(0, 0, "([0, 1],)"), Text(1, 0, "([1, 2],)")] s = Series( [1, 2], index=[interval_range(0, 2, inclusive="both")], ) _check_plot_works(s.plot.bar) assert all((a.get_text() == b.get_text()) for a, b in zip(s.plot.bar().get_xticklabels(), expected))
def _init_key(self): # Initially create the strain glyph key self.glyph_key = [] mag = self.key_magnitude units = self.units strain = [mag, -mag, 0.0] sigma = [0.25 * mag, 0.25 * mag, 0.25 * mag] key_pos_axes = self.key_position key_pos_display = self.map_ax.transAxes.transform(key_pos_axes) key_pos_data = self.map_ax.transData.inverted().transform( key_pos_display) posx, posy = key_pos_data self.glyph_key += strain_glyph(key_pos_data, strain, sigma=sigma, scale=self.scale, ext_color=self.extension_color, cmp_color=self.compression_color, alpha=self.alpha, vert=self.vertices, zorder=3) if units is None: text_str = '%s' % mag else: text_str = '%s %s' % (mag, units) textx = posx + 1.1 * mag * self.scale texty = posy self.glyph_key += [ Text(textx, texty, text_str, fontsize=10, color=self.extension_color, zorder=3) ] textx = posx texty = posy + 1.1 * mag * self.scale self.glyph_key += [ Text(textx, texty, '-' + text_str, fontsize=10, color=self.compression_color, zorder=3) ] for a in self.glyph_key: self.map_ax.add_artist(a)
def make_labels(coords): """Returns Text objects with 5' and 3' labels. """ #get five prime coordinates fp_x = coords[0][0] - (coords[1][0] - coords[0][0]) fp_y = coords[0][1] - (coords[1][1] - coords[0][1]) fp_label = Text(fp_x,fp_y,"5'") #get three prime coordinates tp_x = coords[-1][0] - (coords[-2][0] - coords[-1][0]) tp_y = coords[-1][1] - (coords[-2][1] - coords[-1][1]) tp_label = Text(tp_x,tp_y,"3'") return [fp_label,tp_label], [[fp_x,fp_y],[tp_x,tp_y]]
def __set_animation_layout(self): """ Adds layout components that are required for an animation """ offset = self.__offset o_width = self.__width_u phi_o = self._agent.phi + offset gamma_o = self._agent.gamma + offset # U flow (R1) self._arr_u_flow = FancyArrowPatch((o_width, phi_o), (o_width + 0.1, phi_o), arrowstyle='simple', mutation_scale=0, ec='white', fc=self.__u_color) self._ann_u_flow = Text(text="flow: ", ha='right', fontsize="large", x=o_width, y=phi_o - 0.05) # Tap flow (Power) self._arr_power_flow = FancyArrowPatch((self._ann_lf.get_position()[0], offset - 0.05), (self._ann_lf.get_position()[0], 0.0), arrowstyle='simple', mutation_scale=0, ec='white', color=self.__p_color) self._ann_power_flow = Text(text="flow: ", ha='center', fontsize="large", x=self._ann_lf.get_position()[0], y=offset - 0.05) # LS flow (R2) self._arr_r2_l_pos = [(self._ls.get_x(), gamma_o), (self._ls.get_x() - 0.1, gamma_o)] self._arr_r2_flow = FancyArrowPatch(self._arr_r2_l_pos[0], self._arr_r2_l_pos[1], arrowstyle='simple', mutation_scale=0, ec='white', color=self.__ls_color) self._ann_r2_flow = Text(text="flow: ", ha='left', fontsize="large", x=self._ls.get_x(), y=gamma_o - 0.05) # information annotation self._ann_time = Text(x=1, y=0.9 + offset, ha="right") self._ax1.add_artist(self._ann_power_flow) self._ax1.add_artist(self._arr_power_flow) self._ax1.add_artist(self._arr_u_flow) self._ax1.add_artist(self._ann_u_flow) self._ax1.add_artist(self._arr_r2_flow) self._ax1.add_artist(self._ann_r2_flow)
def draw(self, renderer): Table.draw(self, renderer) # Add title if self.title != None: # Position using loc (BEST, UR, UL, LL, LR, CL, CR, LC, UC, C, TR, TL, BL, BR, R, L, T, B) = range(len(self.codes)) # Get table bounds. bounds = self._get_grid_bbox(self._cachedRenderer).bounds y = bounds[1] + bounds[3] + self._approx_text_height() / 2 # Default for left x = bounds[0] ha = 'left' # Right if self._loc in (BEST, UR, LR, R, CR): x = bounds[0] + bounds[2] ha = 'right' # Center if self._loc in (LC, UC, C): x = bounds[0] + bounds[2] / 2.0 ha = 'center' # Create text object title = Text(x, y, text=self.title, ha=ha, va="bottom") title.set_figure(self.figure) title.set_transform(self.get_transform()) title.draw(self._cachedRenderer)
def enable_cursor(self): self.cid_on_mouse_move = self.fig.canvas.mpl_connect( 'motion_notify_event', self._on_mouse_move) self.fig.canvas.mpl_connect('button_press_event', self._on_mouse_press) #self.cid_on_mouse_leave = self.fig.canvas.mpl_connect('axes_leave_event', self._on_mouse_leave) #self.cid_resize = self.fig.canvas.mpl_connect('resize_event', self._resize) self.cid_draw = self.fig.canvas.mpl_connect('draw_event', self._draw) self.cursor_text = Text( 0.7, 0.1, 'n/a', horizontalalignment='left', verticalalignment='center', #bbox=dict(facecolor='white', alpha=1, ec='gray', pad=10), color='white', fontsize='small', alpha=0.8, backgroundcolor='gray', family='monospace', clip_box=self.ax.bbox, animated=True, transform=self.ax.transAxes) self.ax.add_artist(self.cursor_text) self.circle_matched_term = Circle((100, 100), 0.02, alpha=0.5, color='green', animated=True) self.ax.add_patch(self.circle_matched_term)
def draw_promoter(feature, x, y, width, height, figure, loc_index, style_dict): from matplotlib.patches import Rectangle from matplotlib.patches import Wedge from matplotlib.patches import FancyArrow from matplotlib.text import Text base_width = 4 head_width = 8 curve_radius = 10 y_center = y + height/2 y_curve_max = y + height - head_width/2 + base_width/2 y_curve_min = y_curve_max - curve_radius y_tip = y + height - head_width/2 vertical = Rectangle((x, y_center), base_width, y_curve_min-y_center, color="black", linewidth=0) figure.patches.append(vertical) curve = Wedge(center=(x+curve_radius, y_curve_min), r=curve_radius, theta1=90, theta2=180, width=base_width, color="black", linewidth=0) figure.patches.append(curve) horizontal = FancyArrow( x+curve_radius, y_tip, dx=width-curve_radius, dy=0, width=base_width, head_width=head_width, head_length=head_width, length_includes_head=True, color="black", linewidth=0 ) figure.patches.append(horizontal) if "note" in feature.qual: text = Text(x + width/2, y + height/4, feature.qual["note"], color="black", ha="center", va="center", size=9, figure=figure) figure.texts.append(text)
def __init__( self, x=0, y=0, text='', color=None, # defaults to rc params verticalalignment='bottom', horizontalalignment='left', multialignment=None, fontproperties=None, # defaults to FontProperties() rotation=None, linespacing=None, **kwargs): Artist.__init__(self) if color is None: colors = rcParams['text.color'] if fontproperties is None: fontproperties = FontProperties() elif is_string_like(fontproperties): fontproperties = FontProperties(fontproperties) self._animated = False # if is_string_like(text): # text = [text] self._textobjs = [ Text(x[ind], y[ind], text[ind], color, verticalalignment, horizontalalignment, multialignment, fontproperties, rotation, linespacing, **kwargs) for ind in xrange(len(x)) ] self.update(kwargs)
def _generate_node_labels(pos, styles, *, ax): key_map = { 'font_size': 'size', 'font_color': 'color', 'font_family': 'family', 'font_weight': 'weight', 'alpha': 'alpha', 'bbox': 'bbox', 'horizontalalignment': 'horizontalalignment', 'verticalalignment': 'verticalalignment' } node_labels_dict = {} for node, nstyle in styles.items(): properties = {key_map[k]: v for k, v in nstyle.items() if k in key_map} x, y = pos[node] if 'label' in nstyle: label = nstyle['label'] else: label = str(node) # this makes "1" and 1 the same node_labels_dict[node] = Text(x, y, label, transform=ax.transData, clip_on=True, **properties) return node_labels_dict
def on_xlims_change(ax): display_xs = list() fontheight = 24 for p in ax.get_xticks(): xdisplay, ydisplay = ax.transData.transform_point((p, 0)) display_xs.append(xdisplay) dxa = np.array(display_xs) dxd = dxa[1:] - dxa[:-1] min_dx = dxd.min() + 12 tes = list() for l in ax.get_xticklabels(): text = Text(text=l, figure=ax.figure) extent = text.get_window_extent() tes.append(extent.width) fontheight = extent.height max_tx = np.array(tes).max() if min_dx > max_tx: angle = 0 elif min_dx < fontheight * 2: angle = 90 else: angle = math.atan(fontheight / (min_dx - fontheight * 2)) / math.pi * 180 angle = max(0, min(90, angle)) plt.xticks(rotation=angle, horizontalalignment="right") plt.tight_layout()
def _create_ticks(self, step=0.2, tick_length=0.025, **kwargs): x = np.arange(step, 1., step) n = x.shape[0] tick_start, tick_end = np.zeros((n, 3)), np.zeros((n, 3)) tick_start[:, 0] = x tick_start[:, 2] = 1. - x tick_end[:, 0] = x tick_end[:, 2] = 1. - x + tick_length tick_end[:, 1] = -tick_length tick_labels = [] ha = ["center", "left", "right"] va = ["top", "bottom", "center"] rot = [-60, 60, 0] segs = np.zeros((n * 3, 2, 2)) for i, perm in enumerate([(0, 2, 1), (1, 0, 2), (2, 1, 0)]): start = self._simplex_transform.transform(tick_start[:, perm]) end = self._simplex_transform.transform(tick_end[:, perm]) segs[i * n:(i + 1) * n, 0, :], segs[i * n:(i + 1) * n, 1, :] = start, end for j, x_ in enumerate(x): tick_labels.append( Text(end[j, 0], end[j, 1], "{0:.1f}".format(x_), horizontalalignment=ha[i], verticalalignment=va[i], rotation=rot[i], color=kwargs["color"], fontsize=rcParams["xtick.labelsize"])) line_segments = LineCollection(segs, **kwargs) return line_segments, tick_labels
def as_artist(self, origin=(0, 0), **kwargs): """ Matplotlib Text object for this region (`matplotlib.text.Text`). Parameters ---------- origin : array_like, optional The ``(x, y)`` pixel position of the origin of the displayed image. Default is (0, 0). kwargs : `dict` All keywords that a `~matplotlib.text.Text` object accepts Returns ------- text : `~matplotlib.text.Text` Matplotlib Text object. """ from matplotlib.text import Text mpl_params = self.mpl_properties_default('text') mpl_params.update(kwargs) text = Text(self.center.x - origin[0], self.center.y - origin[1], self.text, **mpl_params) return text
def draw_legend(data, da, lyr): """ Draw letter 'a' in the box Parameters ---------- data : dataframe da : DrawingArea lyr : layer Returns ------- out : DrawingArea """ key = Text(x=0.5 * da.width, y=0.5 * da.height, text='a', alpha=data['alpha'], size=data['size'], family=lyr.geom.params['family'], color=data['color'], rotation=data['angle'], horizontalalignment='center', verticalalignment='center') da.add_artist(key) return da
def test_update_mutate_input(): inp = dict(fontproperties=FontProperties(weight="bold"), bbox=None) cache = dict(inp) t = Text() t.update(inp) assert inp['fontproperties'] == cache['fontproperties'] assert inp['bbox'] == cache['bbox']
def keep_ticks(self, label_spacing: Optional[int] = None, tick_spacing: Optional[int] = None, start: int = 0, end: Optional[int] = None) -> 'AxisFormatter': """ Keep only some tick labels and locations of a categorical axis. :param label_spacing: Spacing of labels to keep. :param tick_spacing: Spacing of ticks to keep. :param start: Index of the first label to keep. :param end: Index of the last label to keep, if it is n * spacing from start. """ if label_spacing is not None: labels = self._axis.get_ticklabels() num_labels = len(labels) if end is None or end > num_labels - 1: end = num_labels - 1 self._axis.set_ticklabels([ label.get_text() if (start <= i <= end and (i - start) % label_spacing == 0) else Text() for i, label in enumerate(labels) ]) if tick_spacing is not None: locations = self._axis.get_ticklocs() self._axis.set_ticks([ location for i, location in enumerate(locations) if (i - start) % tick_spacing == 0 ]) return self
def test_text_annotation_get_window_extent(): figure = Figure(dpi=100) renderer = RendererAgg(200, 200, 100) # Only text annotation annotation = Annotation('test', xy=(0, 0)) annotation.set_figure(figure) text = Text(text='test', x=0, y=0) text.set_figure(figure) bbox = annotation.get_window_extent(renderer=renderer) text_bbox = text.get_window_extent(renderer=renderer) eq_(bbox.width, text_bbox.width) eq_(bbox.height, text_bbox.height) _, _, d = renderer.get_text_width_height_descent( 'text', annotation._fontproperties, ismath=False) _, _, lp_d = renderer.get_text_width_height_descent( 'lp', annotation._fontproperties, ismath=False) below_line = max(d, lp_d) # These numbers are specific to the current implementation of Text points = bbox.get_points() eq_(points[0, 0], 0.0) eq_(points[1, 0], text_bbox.width) eq_(points[0, 1], -below_line) eq_(points[1, 1], text_bbox.height - below_line)
def __init__(self, position, state): self.position = position indx = state.positions.index(position) self.top = -state.tops[indx] self.top_line, = pylab.plot([0, width], 2 * [self.top], c='b') self.bottom = -state.bottoms[indx] self.bottom_line, = pylab.plot([0, width], 2 * [self.bottom], c='b') self.edge = -state.edges[indx] self.edge_line, = pylab.plot([0, width], 2 * [self.edge], c='g') self.label = Text(width / 2, (self.top + self.bottom) / 2, str(position), va='center', ha='center') self.axes = pylab.gca() self.axes.add_artist(self.label) self.src_box = None self.exp_box = None self._check_boxes(state)
def inspect(self, vmentry): # the patches use axes transform on the y coordinate to # set the height position of the label independently of # the Y scale rect = Rectangle((vmentry.start, 0.01), vmentry.end - vmentry.start, 0.98) self.patches.append(rect) self.patch_colors.append(self._colors[vmentry.perms]) self._legend_set.add(vmentry.perms) self._ticks.add(vmentry.start) self._ticks.add(vmentry.end) # the label position is centered based on the axes transform label_position = ((vmentry.start + vmentry.end) / 2, self.label_y) vme_path = str(vmentry.path).split("/")[-1] if str( vmentry.path) else "" if not vme_path and vmentry.grows_down: vme_path = "stack" vme_label = "%s %s" % (vmentry.perms, vme_path) label = Text(text=vme_label, rotation="vertical", position=label_position, horizontalalignment="center", verticalalignment="center", fontproperties=self.style["font-small"], transform=self.transform) self.annotations.append(label) self._add_range(vmentry.start, vmentry.end)
def test_bar_plot(self): # GH38947 # Test bar plot with string and int index from matplotlib.text import Text expected = [Text(0, 0, "0"), Text(1, 0, "Total")] df = DataFrame( { "a": [1, 2], }, index=Index([0, "Total"]), ) plot_bar = df.plot.bar() assert all((a.get_text() == b.get_text()) for a, b in zip(plot_bar.get_xticklabels(), expected))
def plot(self, ax=None, **kwargs): """ Forwarding all kwargs to `~matplotlib.text.Text` object and add it to given axis. Parameters ---------- ax : `~matplotlib.axes`, optional Axes kwargs: `dict` keywords that a `~matplotlib.text.Text` accepts Returns ------- ax : `~matplotlib.axes` The axis with the patch. """ import matplotlib.pyplot as plt from matplotlib.text import Text if ax is None: ax = plt.gca() mpl_params = self.mpl_properties_default('text') mpl_params.update(kwargs) text = Text(self.center.x, self.center.y, self.text, **mpl_params) ax.add_artist(text) return ax
def draw_rod(index, rod, anisotropic_component=0): """#FIXME needs to be adapted to work with anisotropic material """ if isinstance(rod.material.epsilon, (list, tuple)): eps = rod.material.epsilon[anisotropic_component] epsstr = ', '.join(['{0:.2f}'.format(f) for f in rod.material.epsilon]) else: eps = rod.material.epsilon epsstr = '{0:.2f}'.format(eps) return (Ellipse((rod.x, rod.y), rod.radius * 2, rod.radius * 2, alpha=eps / maxeps, lw=2.0, ls='dashed', ec='darkblue', fc='lightblue'), Text(rod.x, rod.y, '#%s\n$\epsilon=%s$' % (index, epsstr), ha='center', va='center', family='sans-serif'))
def test_barh_plot_labels_mixed_integer_string(self): # GH39126 # Test barh plot with string and integer at the same column from matplotlib.text import Text df = DataFrame([{ "word": 1, "value": 0 }, { "word": "knowledg", "value": 2 }]) plot_barh = df.plot.barh(x="word", legend=None) expected_yticklabels = [Text(0, 0, "1"), Text(0, 1, "knowledg")] assert all(actual.get_text() == expected.get_text() for actual, expected in zip(plot_barh.get_yticklabels(), expected_yticklabels))
def ani_init(self, axes): self.ax = axes self.centre_x = 0.5 * (self.input_x + self.output_x) min_x = min(self.input_x, self.output_x) max_x = max(self.input_x, self.output_x) if (max_x - min_x) < (2 * self.min_hw): min_x = self.centre_x - self.min_hw max_x = self.centre_x + self.min_hw self.centre_y = 0.5 * (self.input_y + self.output_y) min_y = min(self.input_y, self.output_y) max_y = max(self.input_y, self.output_y) if (max_y - min_y) < (2 * self.min_hh): min_y = self.centre_y - self.min_hh max_y = self.centre_y + self.min_hh self.upper_y = 0.25 * self.centre_y + 0.75 * max_y coords = np.array( [[min_x, max_x, max_x, min_x], [min_y, min_y, max_y, max_y]], dtype=np.float) coords = coords.transpose() poly = Polygon(xy=coords, closed=True, **self.outline_poly_kwargs) self.ax.add_patch(poly) self.box_poly = poly if self.onebit_mode: # Make a circle to show the 'blob'. circ = Circle(xy=(self.centre_x, self.centre_y), axes=self.ax, **self.onebit_circle_kwargs) self.ax.add_patch(circ) self.els['blob_circle'] = circ else: # Make a text to show the value. kwargs = {'fontsize': 30} kwargs.update(self.value_text_kwargs) txt = Text(x=self.centre_x, y=self.centre_y, text=self.value_text_unset, verticalalignment='center', horizontalalignment='center', **self.value_text_kwargs) self.ax.add_artist(txt) self.value_text = txt # Setup self._anidata to contain all animation state information. AniData = SlotsHolder.newtype('pulselatch_anidata', ('value_text', 'blob_circle')) ValueTextData = SlotsHolder.newtype( 'ValueTextData', ('position', 'text', 'color', 'fontstyle', 'fontweight')) self._anidata = AniData() self._anidata.value_text = self._get_element_state( self.value_text, ValueTextData) # Also require a dummy 'bloc_circle' object (for now, just testing) self.blob_circle = None self._anidata.blob_circle = SlotsHolder.newtype( 'DummyBlobCircleData', [])
def _make_plot(self, ax, plt_data, max_val, curPicks, starttime, cur_starttime, sr, transOffset, caption=None): npts = len(plt_data) t = np.array([(starttime + tmp).datetime for tmp in np.arange(0, npts) / sr]) ax.plot(t, plt_data / max_val) plt.ylim([-1, 1]) if caption: ax.text(.95, .9, caption, transform=ax.transAxes, va='top', ha='right', fontsize=10, backgroundcolor='white') for curStage, pickStage in enumerate(curPicks): for pick in pickStage: pick_sample = pick.time.datetime col = 'red' if pick['phase_hint'] == 'P' else 'black' # col = 'red' ax.axvline(pick_sample, c=col) snr = None for c in pick.comments: if 'SNR=' not in c.text: continue snr = c.text.split('=')[1] displayText = '%s%s' % (pick.phase_hint, curStage) if snr: displayText = '%s - %s' % (displayText, snr) label = Text(pick_sample, ax.get_ylim()[1] * .7, displayText, color=col, backgroundcolor='white', size=10, alpha=.8, transform=transOffset) ax.add_artist(label) if hasattr(pick, 'tt_residual'): pick_sample = (pick.time - pick.tt_residual).datetime ax.axvline(pick_sample, c='green')
def draw_region_labels(regions, ax=None, fontsize=7, **kw): if ax is None: ax = plt.gca() ax.artists = [] for region in regions: cent = region.centroid t = Text(cent[1], cent[0], str(region.label), fontsize=fontsize, **kw) t.set_clip_on(True) ax.add_artist(t)
def create_artists(self, legend, text, xdescent, ydescent, width, height, fontsize, trans): tx = Text(width / 2., height / 2, text, fontsize=fontsize, ha="center", va="center") return [tx]
def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans): tx = Text(width / 2, height / 2, orig_handle.get_text(), fontsize=fontsize, ha="center", va="center", fontweight="normal") return [tx]
def _generate_edge_labels(pos, styles, *, ax): key_map = { 'font_size': 'size', 'font_color': 'color', 'font_family': 'family', 'font_weight': 'weight', 'alpha': 'alpha', 'bbox': 'bbox', 'horizontalalignment': 'horizontalalignment', 'verticalalignment': 'verticalalignment' } edge_labels_dict = {} for edge, estyle in styles.items(): properties = {key_map[k]: v for k, v in estyle.items() if k in key_map} if 'label' in estyle: label = estyle['label'] else: label = str(edge) # this makes "1" and 1 the same if 'label_pos' in estyle: label_pos = estyle['label_pos'] else: label_pos = 0.5 (x1, y1) = pos[edge[0]] (x2, y2) = pos[edge[1]] (x, y) = (x1 * label_pos + x2 * (1.0 - label_pos), y1 * label_pos + y2 * (1.0 - label_pos)) if 'rotate' in estyle and estyle['rotate'] is True: # in degrees angle = np.arctan2(y2 - y1, x2 - x1) / (2.0 * np.pi) * 360 # make label orientation "right-side-up" if angle > 90: angle -= 180 if angle < -90: angle += 180 # transform data coordinate angle to screen coordinate angle xy = np.array((x, y)) trans_angle = ax.transData.transform_angles( np.array((angle, )), xy.reshape((1, 2)))[0] else: trans_angle = 0.0 edge_labels_dict[edge] = Text(x, y, label, rotation=trans_angle, transform=ax.transData, clip_on=True, zorder=1, **properties) return edge_labels_dict