Exemplo n.º 1
0
        def __init__(self, x, y, text, offset=(0, 0), **kwargs):
            """Initialize an instance of `TextCollection`.

            This class encompasses drawing a collection of text values at a variety
            of locations.

            Parameters
            ----------
            x : array_like
                The x locations, in data coordinates, for the text

            y : array_like
                The y locations, in data coordinates, for the text

            text : array_like of str
                The string values to draw

            offset : (int, int)
                The offset x and y, in normalized coordinates, to draw the text relative
                to the data locations.

            kwargs : arbitrary keywords arguments
            """
            Text.__init__(self, **kwargs)
            self.x = x
            self.y = y
            self.text = text
            self.offset = offset
            if not hasattr(self, '_usetex'):  # Only needed for matplotlib 1.4 compatibility
                self._usetex = None
Exemplo n.º 2
0
 def __init__(self, x, y, text, offset=(0, 0), **kwargs):
     Text.__init__(self, **kwargs)
     self.x = x
     self.y = y
     self.text = text
     self.offset = offset
     if not hasattr(self, '_usetex'):  # Only needed for matplotlib 1.4 compatibility
         self._usetex = None
Exemplo n.º 3
0
 def __init__(self, axes, on_dblclick, *args, **kwargs):
     Text.__init__(self, *args, **kwargs)
     self.axes = axes
     self.axes.add_artist(self)
     self.connections = [
         axes.figure.canvas.mpl_connect('button_press_event', self.onclick),
         axes.figure.canvas.mpl_connect('button_release_event', self.onrelease),
         axes.figure.canvas.mpl_connect('motion_notify_event', self.onmove),
         ]
     self.press = None
     self.on_dblclick = on_dblclick
Exemplo n.º 4
0
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
Exemplo n.º 5
0
    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()
Exemplo n.º 6
0
def test_text_with_arrow_annotation_get_window_extent():
    headwidth = 21
    fig, ax = plt.subplots(dpi=100)
    txt = ax.text(s='test', x=0, y=0)
    ann = ax.annotate(
        'test',
        xy=(0.0, 50.0),
        xytext=(50.0, 50.0), xycoords='figure pixels',
        arrowprops={
            'facecolor': 'black', 'width': 2,
            'headwidth': headwidth, 'shrink': 0.0})

    plt.draw()
    renderer = fig.canvas.renderer
    # bounding box of text
    text_bbox = txt.get_window_extent(renderer=renderer)
    # bounding box of annotation (text + arrow)
    bbox = ann.get_window_extent(renderer=renderer)
    # bounding box of arrow
    arrow_bbox = ann.arrow.get_window_extent(renderer)
    # bounding box of annotation text
    ann_txt_bbox = Text.get_window_extent(ann)

    # make sure annotation with in 50 px wider than
    # just the text
    eq_(bbox.width, text_bbox.width + 50.0)
    # make sure the annotation text bounding box is same size
    # as the bounding box of the same string as a Text object
    eq_(ann_txt_bbox.height, text_bbox.height)
    eq_(ann_txt_bbox.width, text_bbox.width)
    # compute the expected bounding box of arrow + text
    expected_bbox = Bbox.union([ann_txt_bbox, arrow_bbox])
    assert_almost_equal(bbox.height, expected_bbox.height)
Exemplo n.º 7
0
    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)
Exemplo n.º 8
0
  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
Exemplo n.º 9
0
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)
Exemplo n.º 10
0
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']
Exemplo n.º 11
0
    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))
Exemplo n.º 12
0
    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
Exemplo n.º 13
0
    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)
        self.overflowLabels['top'] = Text(0.9,
                                          1,
                                          '',
                                          fontsize='xx-small',
                                          ha="right",
                                          va="top",
                                          bbox=box,
                                          transform=self.axes.transAxes,
                                          alpha=0.5)
        self.overflowLabels['bottom'] = Text(0.9,
                                             0,
                                             '',
                                             fontsize='xx-small',
                                             ha="right",
                                             va="bottom",
                                             bbox=box,
                                             transform=self.axes.transAxes,
                                             alpha=0.5)

        for label in self.overflowLabels.itervalues():
            self.axes.add_artist(label)
Exemplo n.º 14
0
    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))
Exemplo n.º 15
0
    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', [])
Exemplo n.º 16
0
    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')
Exemplo n.º 17
0
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)
Exemplo n.º 18
0
 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]
Exemplo n.º 19
0
 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]
Exemplo n.º 20
0
def is_math_text(text, usetex=False):
    """
    Comprueba si un texto es aceptado por la figura o no.
    :param text: String. Texto matemático (Sin usar $)
    :param usetex: Bool. Usar o no el compilador de Latex.
    :return: Bool
    """

    _, is_acceptable = Text.is_math_text(str(text), bool(usetex))
    return is_acceptable
Exemplo n.º 21
0
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
Exemplo n.º 22
0
 def create_artists(self, legend, tup, xdescent, ydescent, width, height,
                    fontsize, trans):
     tx = Text(width / 2.,
               height / 2,
               tup[0],
               fontsize=fontsize,
               ha="center",
               va="center",
               color=tup[1],
               fontweight="bold")
     return [tx]
Exemplo n.º 23
0
 def string(self, x, y, string, ha=None, va=None, rotation=None, color=None):
     opts = self.text_opts.copy()
     if ha is not None:
         opts['ha'] = ha
     if va is not None:
         opts['va'] = va
     if rotation is not None:
         opts['rotation'] = rotation
     if color is not None:
         opts['color'] = color
     return Text(x, y, string, **opts)
Exemplo n.º 24
0
    def axes(self, ax):
        self._axes = ax
        from matplotlib.text import Text
        self._text = Text(self.x,
                          self.y,
                          f"${self.string}$",
                          horizontalalignment='center',
                          verticalalignment='center',
                          size=FONT,
                          usetex=True)

        ax.add_artist(self._text)
Exemplo n.º 25
0
 def __init__(self, location='C', alpha=0.75, color='red', textprop={'fontsize':20, 'fontweight':'bold'}, *args, **kwargs):
     
     self.figure = None
     self._text_alpha = alpha
     self._text = Text(visible=False,color=color,alpha=alpha,zorder=100,**textprop)
     self.set_location( location )
     
     self._timer = None
     self._fadeout_timer = None
     self._fadeout_alpha = 0
     
     super(AxesMessage, self).__init__(*args, **kwargs)
Exemplo n.º 26
0
    def __setup_measure(self):
        dashesHalf = [1, 5, 5, 5, 5, 5]
        self.lines[Markers.HFS] = Line2D([0, 0], [0, 0], dashes=dashesHalf,
                                         color='purple')
        self.lines[Markers.HFE] = Line2D([0, 0], [0, 0], dashes=dashesHalf,
                                         color='purple')
        self.lines[Markers.OFS] = Line2D([0, 0], [0, 0], dashes=dashesHalf,
                                         color='#996600')
        self.lines[Markers.OFE] = Line2D([0, 0], [0, 0], dashes=dashesHalf,
                                         color='#996600')
        if matplotlib.__version__ >= '1.3':
            effect = patheffects.withStroke(linewidth=3, foreground="w",
                                            alpha=0.75)
            self.lines[Markers.HFS].set_path_effects([effect])
            self.lines[Markers.HFE].set_path_effects([effect])
            self.lines[Markers.OFS].set_path_effects([effect])
            self.lines[Markers.OFE].set_path_effects([effect])

        for line in self.lines.itervalues():
            self.axes.add_line(line)

        bbox = self.axes.bbox
        box = dict(boxstyle='round', fc='white', ec='purple', clip_box=bbox)
        self.labels[Markers.HFS] = Text(0, 0, '-3dB', fontsize='xx-small',
                                        ha="center", va="top", bbox=box,
                                        color='purple')
        self.labels[Markers.HFE] = Text(0, 0, '-3dB', fontsize='xx-small',
                                        ha="center", va="top", bbox=box,
                                        color='purple')
        box['ec'] = '#996600'
        self.labels[Markers.OFS] = Text(0, 0, 'OBW', fontsize='xx-small',
                                        ha="center", va="top", bbox=box,
                                        color='#996600')
        self.labels[Markers.OFE] = Text(0, 0, 'OBW', fontsize='xx-small',
                                        ha="center", va="top", bbox=box,
                                        color='#996600')

        for label in self.labels.itervalues():
            self.axes.add_artist(label)
Exemplo n.º 27
0
 def create_artists(self, legend, orig_handle, xdescent, ydescent, width,
                    height, fontsize, trans):
     p = Text(x=-xdescent, y=-ydescent, text=orig_handle.get_text())
     self.update_prop(p, orig_handle, legend)
     p.set_transform(trans)
     p.set_fontsize(0.75 * fontsize)
     c = Rectangle(xy=(-xdescent, -ydescent - (height / 5)),
                   width=width,
                   height=7 * height / 5,
                   facecolor="none",
                   edgecolor="none")
     c.set_transform(trans)
     p.set_clip_path(c)
     return [p]
Exemplo n.º 28
0
 def shape(self, height, yrange, rotated):
     rot = 0
     if rotated: rot += 90
     #if span.Reverse: rot+= 180
     g = rlg2mpl.Group()
     kw = dict(ha='center', va='baseline', rotation=rot,
             font_properties=self.font_properties)
     for (motif, cvalues, offsets) in self.per_shape_values:
         letter = self.alphabet[motif]
         c = len(cvalues)
         for (i, (x,y)) in enumerate(offsets):
             s = Text(x, y, letter, color=cvalues[i%c], **kw)
             g.add(s)
     return g
Exemplo n.º 29
0
 def __call__(self, height, label, map, value, yrange, rotated):
     #return self.FeatureClass(label, map)
     g = rlg2mpl.Group()
     last = first = None
     if self.range_required and not yrange:
         warnings.warn("'%s' graph values are all zero" % label)
         yrange = 1.0
     if map.useful and self.one_span:
         map = map.getCoveringSpan()
     for (i, span) in enumerate(map.spans):
         #if last is not None:
         #    g.add(rlg2mpl.Line(last, height, part.Start, height))
         if span.lost or (value is None and self.range_required):
             continue
         if span.Reverse:
             (start, end) = (span.End, span.Start)
             (tidy_start, tidy_end) = (span.tidy_end, span.tidy_start)
         else:
             (start, end) = (span.Start, span.End)
             (tidy_start, tidy_end) = (span.tidy_start, span.tidy_end)
         shape = self._item_shape(start,
                                  end,
                                  tidy_start,
                                  tidy_end,
                                  height,
                                  value,
                                  yrange,
                                  rotated,
                                  last=i == len(map.spans) - 1)
         g.add(shape)
         last = end
         if first is None:
             first = start
     if self.showLabel and label and last is not None and height > 7:
         font_height = 12  #self.label_font.get_size_in_points()
         text_width = llen(label, font_height)
         if (text_width < abs(first - last)):
             label_shape = Text(
                 (first + last) / 2,
                 height / 2,
                 label,
                 ha="center",
                 va="center",
                 rotation=[0, 90][rotated],
                 #font_properties=self.label_font,
             )
             g.add(label_shape)
         else:
             pass  #warnings.warn("couldn't fit feature label '%s'" % label)
     return g
Exemplo n.º 30
0
def plot_marker_text(project, marker, offset, marker_scale, base_y, axes):
    """
        Plots a markers text using the given offset and scale
    """
    text = getattr(marker, "__plot_text", None)
    within_range = bool(project.axes_xlimit == 0
                        or (marker.position >= project.axes_xmin
                            and marker.position <= project.axes_xmax))
    if marker.visible and marker.style != "offset" and within_range:
        # prevent empty $$ from causing an error:
        save_label = marker.label.replace("$$", "")

        # Calculate position and set transform:
        x = float(marker.position) + float(marker.x_offset)
        if marker.top == 0:  # relative to base
            y = base_y + (marker.top_offset + marker.y_offset) * marker_scale
            transform = axes.transData
        elif marker.top == 1:  # top of plot
            y = settings.PLOT_TOP + float(marker.y_offset)
            transform = transforms.blended_transform_factory(
                axes.transData,
                axes.get_figure().transFigure)

        kws = dict(text=save_label,
                   x=x,
                   y=y,
                   clip_on=False,
                   transform=transform,
                   horizontalalignment=marker.align,
                   verticalalignment="center",
                   rotation=(90 - marker.angle),
                   rotation_mode="anchor",
                   color=marker.color,
                   weight="heavy")

        if text:
            for key in kws:
                getattr(text, "set_%s" % key)(kws[key])
        else:
            text = Text(**kws)
        if not text in axes.get_children():
            axes.add_artist(text)
    elif text:
        try:
            text.remove()
        except:
            pass
    marker.__plot_text = text
    return text
Exemplo n.º 31
0
 def __init__(self,
              depends=(),
              essential_data=None,
              create_type=1,
              infinite=False):
     self.text = Text(0, 0, '')
     super(KingGeometry, self).__init__([], [])
     super(KingCurve, self).__init__(depends=depends,
                                     essential_data=essential_data,
                                     create_type=create_type,
                                     infinite=infinite)
     self.text.set_text(self.get_label())
     self.mouse_select_priority = 2
     if create_type == 1:
         self.mouse_translation = True
Exemplo n.º 32
0
    def test_update_legend(self):
        line1 = Line2D([], [], label='line1')
        line2 = Line2D([], [], label='line2')
        line3 = Line2D([], [], label='line_not_to_show1')
        line4 = Line2D([], [], label='')
        line3.set_linestyle('None')
        line1_text = Text('line1')
        line2_text = Text('line2')

        get_legend_mock = MagicMock()
        get_legend_mock.get_lines = MagicMock(return_value=[line1, line2])
        get_legend_mock.get_texts = MagicMock(
            return_value=[line1_text, line2_text])
        self.axes.get_children = MagicMock(
            return_value=[line1, line2, line3, line4, "nonsense", 4])
        self.axes.legend = MagicMock(return_value=get_legend_mock)

        self.slice_plot.update_legend()
        self.axes.legend.assert_called_with([line1, line2], ['line1', 'line2'],
                                            fontsize=ANY)
        self.assertEqual(self.slice_plot._legend_dict[line1], line1)
        self.assertEqual(self.slice_plot._legend_dict[line2], line2)
        self.assertEqual(self.slice_plot._legend_dict[line1_text], line1)
        self.assertEqual(self.slice_plot._legend_dict[line2_text], line2)
Exemplo n.º 33
0
def make_letters(coords,letters,color='black'):
    """Returns list of Text objects, given list of coordinates and letteres.
    
        - coords: list of [x,y] coordinates, already scaled to matplotlib axes.
        - letters: list of letters to be drawn at given coordinates.  Must be
            same size list as coords.
        - color: color of the letters.
    """
    letter_list = []
    for coord, letter in zip(coords, letters):
        x_coord, y_coord = coord
        curr_letter = Text(x_coord, y_coord, letter)
        letter_list.append(curr_letter)
    
    return letter_list
Exemplo n.º 34
0
    def make_new_artist(self):
        """
        Compute new form of the element to be drawn, using information from self's fields.

        Usually, this will mean creating a new artist and applying a transformation to it, based on the chosen effect.

        Sometimes, the element to be drawn will consist of a *list* of artists.

        :return: new artist --- or list of artists --- to be drawn.

        """

        retval = []

        if self.is_right_angle(self.theta1, self.theta2):
            # Right angle: draw square of side radius/2, rotated according to the segments' position
            vertices = np.array([
                self.center,
                (self.center[0] + self.radius / 2, self.center[1]),
                (self.center[0] + self.radius / 2,
                 self.center[1] + self.radius / 2),
                (self.center[0], self.center[1] + self.radius / 2),
            ])
            retval.append(
                Polygon(vertices,
                        closed=True,
                        fill=True,
                        transform=Affine2D().rotate_deg_around(
                            *self.center, self.theta1) + self.ax.transData,
                        **self.artist_kwargs))
        else:
            # Not right angle: draw wedge
            retval.append(
                Wedge(self.center, self.radius, self.theta1, self.theta2,
                      **self.artist_kwargs))

        if self.label is not None:
            retval.append(
                Text(
                    x=self.x_label,
                    y=self.y_label,
                    text=self.label,
                    color=self.labelcolor,
                    usetex=True,
                    fontsize=30  # TODO
                ))

        return retval
Exemplo n.º 35
0
 def remove(self):
     for connection in self.connections:
         self.axes.figure.canvas.mpl_disconnect(connection)
     Text.remove(self)