def __init__(self, x, y, text, axes, **kwargs):
        super(CurvedText, self).__init__(x[0], y[0], ' ', **kwargs)

        axes.add_artist(self)

        self.__x = x
        self.__y = y
        self.__zorder = self.get_zorder()

        self.__characters = []
        for c in text:
            t = mtext.Text(0, 0, c, **kwargs)

            t.set_ha('center')
            t.set_rotation(0)
            t.set_zorder(self.__zorder + 1)

            self.__characters.append((c, t))
            axes.add_artist(t)
示例#2
0
def addText(ax, xPos, yPos, textString, normalFont):
    if ('DISK' not in textString):
        size = 18
    else:
        size = 25

    if (normalFont == True):
        weight = 'normal'
    else:
        weight = 'bold'
    txt = text.Text(xPos,
                    yPos,
                    textString,
                    ha='left',
                    va='bottom',
                    fontweight=weight,
                    fontsize=size,
                    axes=ax)
    ax.add_artist(txt)
示例#3
0
    def __init__(self, Q, X, Y, U, label, **kw):
        martist.Artist.__init__(self)
        self.Q = Q
        self.X = X
        self.Y = Y
        self.U = U
        self.coord = kw.pop('coordinates', 'axes')
        self.color = kw.pop('color', None)
        self.label = label
        self._labelsep_inches = kw.pop('labelsep', 0.1)
        self.labelsep = (self._labelsep_inches * Q.ax.figure.dpi)

        # try to prevent closure over the real self
        weak_self = weakref.ref(self)

        def on_dpi_change(fig):
            self_weakref = weak_self()
            if self_weakref is not None:
                self_weakref.labelsep = (self_weakref._labelsep_inches *
                                         fig.dpi)
                self_weakref._initialized = False  # simple brute force update
                # works because _init is
                # called at the start of
                # draw.

        self._cid = Q.ax.figure.callbacks.connect('dpi_changed', on_dpi_change)

        self.labelpos = kw.pop('labelpos', 'N')
        self.labelcolor = kw.pop('labelcolor', None)
        self.fontproperties = kw.pop('fontproperties', dict())
        self.kw = kw
        _fp = self.fontproperties
        # boxprops = dict(facecolor='red')
        self.text = mtext.Text(
            text=label,  # bbox=boxprops,
            horizontalalignment=self.halign[self.labelpos],
            verticalalignment=self.valign[self.labelpos],
            fontproperties=font_manager.FontProperties(**_fp))

        if self.labelcolor is not None:
            self.text.set_color(self.labelcolor)
        self._initialized = False
        self.zorder = Q.zorder + 0.1
示例#4
0
        def create_artists(i, v):
            x = (i + 0.5) * self._spacing
            y = 0.5
            r = scaled_radius(v)
            c = patches.Ellipse((x, y),
                                r,
                                yscale * r,
                                transform=fig.transFigure,
                                figure=fig,
                                fill=False)

            t = text.Text(x,
                          y,
                          str(v),
                          transform=fig.transFigure,
                          figure=fig,
                          verticalalignment='center',
                          horizontalalignment='center',
                          fontsize=300 * r)
            return c, t
示例#5
0
 def legend_artist(self, legend, orig_handle, fontsize, handlebox):
     letter, index = orig_handle
     x0, y0 = handlebox.xdescent, handlebox.ydescent
     width, height = handlebox.width, handlebox.height
     x = x0 + width / 2.0
     y = y0 + height / 2.0
     normVal = norm(index)
     colorRgb = cmap(normVal)
     patch = matplotlib.patches.RegularPolygon(
         (x, y),
         6,
         height,
         orientation=math.pi / 2.0,
         facecolor=colorRgb,
         transform=handlebox.get_transform(),
     )
     handlebox.add_artist(patch)
     txt = mpl_text.Text(x=x, y=y, text=letter, ha="center", va="center", size=7)
     handlebox.add_artist(txt)
     return (patch, txt)
示例#6
0
 def legend_artist(self, legend, orig_handle, fontsize, handlebox):
     #        print orig_handle
     x0, y0 = handlebox.xdescent, handlebox.ydescent
     width, height = handlebox.width, handlebox.height
     myfont = fm.FontProperties(
         fname="/usr/share/fonts/truetype/ttf-ancient-scripts/Symbola605.ttf"
     )
     patch = mpl_text.Text(x=0,
                           y=0,
                           text=orig_handle.my_text,
                           color=orig_handle.my_color,
                           verticalalignment=u'baseline',
                           horizontalalignment=u'left',
                           multialignment=None,
                           rotation=0,
                           linespacing=None,
                           rotation_mode=None,
                           fontproperties=myfont,
                           size=orig_handle.my_size)
     handlebox.add_artist(patch)
     return patch
示例#7
0
 def __init__(self, axes, text, x, y):
     self.axes = axes
     self.text = text
     self.x = x
     self.y = y
     self.bbox = {
         'boxstyle': 'square',
         'facecolor': "#98b2d3",
         'edgecolor': "None",
         'alpha': 0
     }
     self.text_obj = text_obj.Text(x=x,
                                   y=y,
                                   text=text,
                                   alpha=0.,
                                   color='#013a4b',
                                   fontsize=30,
                                   verticalalignment='center',
                                   horizontalalignment='center',
                                   bbox=self.bbox)
     self.axes.add_artist(self.text_obj)
示例#8
0
 def labels(self, inline):
     levels = self.label_levels
     fslist = self.fslist
     trans = self.ax.transData
     _colors = self.label_mappable.to_rgba(self.label_cvalues)
     fmt = self.fmt
     for icon, lev, color, cvalue, fsize in zip(self.label_indices,
                                       self.label_levels,
                                       _colors,
                                       self.label_cvalues, fslist):
         con = self.collections[icon]
         lw = self.get_label_width(lev, fmt, fsize)
         additions = []
         for segNum, linecontour in enumerate(con._segments):
             # for closed contours add one more point to
             # avoid division by zero
             if npy.all(linecontour[0] == linecontour[-1]):
                 linecontour = npy.concatenate((linecontour,
                                            linecontour[1][npy.newaxis,:]))
                 #linecontour.append(linecontour[1])
             # transfer all data points to screen coordinates
             slc = trans.seq_xy_tups(linecontour)
             if self.print_label(slc,lw):
                 x,y, rotation, ind  = self.locate_label(slc, lw)
                 # transfer the location of the label back to
                 # data coordinates
                 dx,dy = trans.inverse_xy_tup((x,y))
                 t = text.Text(dx, dy, rotation = rotation,
                          horizontalalignment='center',
                          verticalalignment='center')
                 _text = self.get_text(lev,fmt)
                 self.set_label_props(t, _text, color)
                 self.cl.append(t)
                 self.cl_cvalues.append(cvalue)
                 if inline:
                     new = self.break_linecontour(linecontour, rotation,
                                                    lw, ind)
                     con._segments[segNum] = new[0]
                     additions.append(new[1])
         con._segments.extend(additions)
示例#9
0
文件: vmmap.py 项目: jrtc27/cheriplot
    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 = patches.Rectangle((vmentry.start, 0),
        #                          vmentry.end - vmentry.start, self.y_max)
        rect = patches.Rectangle((vmentry.start, 0.01),
                                 vmentry.end - vmentry.start, 0.98)
        self.patches.append(rect)
        self.patch_colors.append(self._colors[vmentry.perms])

        # 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(text=vme_label, rotation="vertical",
                          position=label_position,
                          horizontalalignment="center",
                          verticalalignment="center",
                          transform=self.transform)
        self.annotations.append(label)
示例#10
0
    def get_real_label_width(self, lev, fmt, fsize):
        """
        This computes actual onscreen label width.
        This uses some black magic to determine onscreen extent of non-drawn
        label.  This magic may not be very robust.
        """
        # Find middle of axes
        xx = np.mean(np.asarray(self.ax.axis()).reshape(2, 2), axis=1)

        # Temporarily create text object
        t = text.Text(xx[0], xx[1])
        self.set_label_props(t, self.get_text(lev, fmt), 'k')

        # Some black magic to get onscreen extent
        # NOTE: This will only work for already drawn figures, as the canvas
        # does not have a renderer otherwise.  This is the reason this function
        # can't be integrated into the rest of the code.
        bbox = t.get_window_extent(renderer=self.ax.figure.canvas.renderer)

        # difference in pixel extent of image
        lw = np.diff(bbox.corners()[0::2, 0])[0]

        return lw
示例#11
0
    def plot(self, ax, title):
        '''
        Plot data on given axis

        Parameters
        ----------
        ax: matplotlib.axes.Axes
            axis on which data will be drawn
        title:
            title of graph
        '''
        if self.freq is None:
            scale = 1
            ax.get_xaxis().set_visible(False)
        else:
            scale = self.freq

        self._plot(ax, scale)

        height = ax.get_ylim()
        if len(self.con) > 1:
            for txt, cn in zip(self.text, self.con):
                l = lines.Line2D([cn * scale] * 2,
                                 height,
                                 lw=1,
                                 color='black',
                                 axes=ax)
                t = text.Text(cn * scale + 2,
                              height[1],
                              txt,
                              axes=ax,
                              horizontalalignment='left',
                              verticalalignment='top')
                ax.add_line(l)
                ax.add_artist(t)

        ax.set_title(title)
示例#12
0
    def __init__(
        self,
        s,
        textprops=None,
        multilinebaseline=None,
        minimumdescent=True,
    ):
        """
        *s* : a string to be displayed.
        *textprops* : property dictionary for the text
        *multilinebaseline* : If True, baseline for multiline text is
                              adjusted so that it is (approximatedly)
                              center-aligned with singleline text.
        *minimumdescent*  : If True, the box has a minimum descent of "p".
        """
        if textprops is None:
            textprops = {}

        if not textprops.has_key("va"):
            textprops["va"] = "baseline"

        self._text = mtext.Text(0, 0, s, **textprops)

        OffsetBox.__init__(self)

        self._children = [self._text]

        self.offset_transform = mtransforms.Affine2D()
        self.offset_transform.clear()
        self.offset_transform.translate(0, 0)
        self._baseline_transform = mtransforms.Affine2D()
        self._text.set_transform(self.offset_transform +
                                 self._baseline_transform)

        self._multilinebaseline = multilinebaseline
        self._minimumdescent = minimumdescent
示例#13
0
 def __init__(self, Q, X, Y, U, label, **kw):
     artist.Artist.__init__(self)
     self.Q = Q
     self.X = X
     self.Y = Y
     self.U = U
     self.coord = kw.pop('coordinates', 'axes')
     self.color = kw.pop('color', None)
     self.label = label
     self.labelsep = (kw.pop('labelsep', 0.1) * Q.ax.figure.dpi)
     self.labelpos = kw.pop('labelpos', 'N')
     self.labelcolor = kw.pop('labelcolor', None)
     self.fontproperties = kw.pop('fontproperties', dict())
     self.kw = kw
     _fp = self.fontproperties
     self.text = text.Text(
         text=label,
         horizontalalignment=self.halign[self.labelpos],
         verticalalignment=self.valign[self.labelpos],
         fontproperties=font_manager.FontProperties(**_fp))
     if self.labelcolor is not None:
         self.text.set_color(self.labelcolor)
     self._initialized = False
     self.zorder = Q.zorder + 0.1
示例#14
0
    def __init__(self, Q, X, Y, U, label, **kw):
        martist.Artist.__init__(self)
        self.Q = Q
        self.X = X
        self.Y = Y
        if type(U) in (tuple, list): self.U, self.V = U
        else: self.U, self.V = U, 0
        self.coord = kw.pop('coordinates', 'axes')
        self.color = kw.pop('color', None)
        self.label = label
        self._labelsep_inches = kw.pop('labelsep', 0.1)
        self.labelsep = (self._labelsep_inches * Q.ax.figure.dpi)

        def on_dpi_change(fig):
            self.labelsep = (self._labelsep_inches * fig.dpi)
            self._initialized = False  # simple brute force update
            # works because _init is called
            # at the start of draw.

        Q.ax.figure.callbacks.connect('dpi_changed', on_dpi_change)

        self.labelpos = kw.pop('labelpos', 'N')
        self.labelcolor = kw.pop('labelcolor', None)
        self.fontproperties = kw.pop('fontproperties', dict())
        self.kw = kw
        _fp = self.fontproperties
        #boxprops = dict(facecolor='red')
        self.text = mtext.Text(
            text=label,  # bbox=boxprops,
            horizontalalignment=self.halign[self.labelpos],
            verticalalignment=self.valign[self.labelpos],
            fontproperties=font_manager.FontProperties(**_fp))
        if self.labelcolor is not None:
            self.text.set_color(self.labelcolor)
        self._initialized = False
        self.zorder = Q.zorder + 0.1
示例#15
0
                         np.random.rand(2, random.randint(2, 15))))
    lc = collections.LineCollection(verts, axes=ax)
    ax.add_collection(lc)

# test a plain-ol-line
line = lines.Line2D([0 * cm, 1.5 * cm], [0 * cm, 2.5 * cm],
                    lw=2,
                    color='black',
                    axes=ax)
ax.add_line(line)

if 0:
    # test a patch
    # Not supported at present.
    rect = patches.Rectangle((1 * cm, 1 * cm),
                             width=5 * cm,
                             height=2 * cm,
                             alpha=0.2,
                             axes=ax)
    ax.add_patch(rect)

t = text.Text(3 * cm, 2.5 * cm, 'text label', ha='left', va='bottom', axes=ax)
ax.add_artist(t)

ax.set_xlim(-1 * cm, 10 * cm)
ax.set_ylim(-1 * cm, 10 * cm)
# ax.xaxis.set_units(inch)
ax.grid(True)
ax.set_title("Artists with units")
plt.show()
示例#16
0
 def legend_artist(self, legend, orig_handle, fontsize, handlebox):
     patch = mpl_text.Text(x=0, y=0, text=orig_handle.my_text, color=orig_handle.my_color,
                           verticalalignment=u'baseline', horizontalalignment=u'left',
                           fontsize=fontsize_legnd)
     handlebox.add_artist(patch)
     return patch
示例#17
0
    def create_artists(self):
        self.line_left = lines.Line2D([], [],
                                      color=set_interval.lc,
                                      lw=set_interval.lw,
                                      visible=False)
        self.line_right = lines.Line2D([], [],
                                       color=set_interval.lc,
                                       lw=set_interval.lw,
                                       visible=False)
        self.collection = colls.PolyCollection([self.verts],
                                               facecolors=set_interval.fc,
                                               edgecolors=set_interval.ec,
                                               visible=False,
                                               alpha=set_interval.alpha)

        # Texts
        self.bounds_textboxes = []
        x = self.left
        y = -1.8 * self.height * 1.7
        text = str(round(self.left, 1))
        self.bounds_textboxes += [
            text_obj.Text(x=x,
                          y=y,
                          text=text,
                          visible=False,
                          color=set_text.fc,
                          alpha=1.,
                          fontsize=set_text.fs,
                          bbox=set_interval.bbox,
                          verticalalignment='center',
                          horizontalalignment='center')
        ]
        x = self.right
        text = str(round(self.right, 1))
        self.bounds_textboxes += [
            text_obj.Text(x=x,
                          y=y,
                          text=text,
                          visible=False,
                          color=set_text.fc,
                          alpha=1.,
                          fontsize=set_text.fs,
                          bbox=set_interval.bbox,
                          verticalalignment='center',
                          horizontalalignment='center')
        ]

        x = (self.left + self.right) / 2.
        y = 1.8 * self.height * 1.7
        p_left, p_center, p_right = self._bounds_to_p()
        text = str(int(round(100. * p_center))) + '%'
        self.bounds_textboxes += [
            text_obj.Text(x=x,
                          y=y,
                          text=text,
                          visible=False,
                          color=set_text.fc,
                          alpha=1.,
                          fontsize=set_text.fs,
                          bbox=set_interval.bbox,
                          verticalalignment='center',
                          horizontalalignment='center')
        ]

        self.line_left.set_zorder(10)
        self.line_right.set_zorder(10)
        self.collection.set_zorder(2)

        self.artists = [self.line_left, self.line_right, self.collection]
        self.artists += self.bounds_textboxes
示例#18
0
    def create_artists(self):
        self.artists = []

        # Pdf line
        self.pdf_line = lines.Line2D([], [],
                                     alpha=set_pdf_line.alpha,
                                     color=set_pdf_line.lc,
                                     lw=set_pdf_line.lw)
        self.artists = [self.pdf_line]

        # Mean line
        self.mean_line = lines.Line2D([self.mean, self.mean], [0, self.y_mean],
                                      color=set_mean_line.lc,
                                      lw=set_mean_line.lw,
                                      visible=False)
        self.artists += [self.mean_line]

        # Areas
        self._update_area_verts()
        self.area_collections = []
        for i, k in enumerate(self.area_verts.keys()):
            fc = set_area.fc[1]
            ec = set_area.ec[1]
            if self.area_status:
                fc = set_area.fc[0]
                ec = set_area.ec[0]
            verts = self.area_verts[k]
            collection = colls.PolyCollection([verts],
                                              facecolors=fc,
                                              edgecolors=ec,
                                              visible=False,
                                              alpha=1.)
            self.area_collections += [collection]
        self.artists += self.area_collections  # 3 polygons for areas

        # Texts
        p_left, p_center, p_right = self._bounds_to_p()

        self.textboxes = []
        for k in self.texts.keys():
            if k == 'center':
                x = (self.left + self.right) / 2.
                y = 0.9 * (self.area_verts['center'][1, 1] +
                           self.area_verts['center'][-2, 1]) / 2.
                self.texts[k] = str(int(round(100 * p_center))) + '%'
            if k == 'left':
                x = self.left
                y = 1.1 * (self.area_verts['center'][1, 1])
                self.texts[k] = str(int(round(100. * p_left))) + '%'
            if k == 'right':
                x = self.right
                y = 1.1 * (self.area_verts['center'][-2, 1])
                self.texts[k] = str(int(round(100 * p_right))) + '%'
            self.textboxes += [
                text_obj.Text(x=x,
                              y=y,
                              text=self.texts[k],
                              visible=False,
                              color=set_text.fc,
                              alpha=1.,
                              fontsize=set_text.fs,
                              bbox=set_text.bbox,
                              verticalalignment='center',
                              horizontalalignment='center')
            ]
        self.artists += self.textboxes

        # correct z_orders
        z0 = self.area_collections[0].get_zorder()
        self.mean_line.set_zorder(z0 + 1)
        self.pdf_line.set_zorder(z0 + 2)
        for t in self.textboxes:
            t.set_zorder(z0 + 3)
示例#19
0
    def _add_gridline_label(self, value, axis, upper_end):
        """
        Create a Text artist on our axes for a gridline label.

        Args:

        * value
            Coordinate value of this gridline.  The text contains this
            value, and is positioned centred at that point.

        * axis
            which axis the label is on: 'x' or 'y'.

        * upper_end
            If True, place at the maximum of the "other" coordinate (Axes
            coordinate == 1.0).  Else 'lower' end (Axes coord = 0.0).

        """
        transform = self._crs_transform()
        shift_dist_points = 5     # A margin from the map edge.
        if upper_end is False:
            shift_dist_points = -shift_dist_points
        if axis == 'x':
            x = value
            y = 1.0 if upper_end else 0.0
            h_align = 'center'
            v_align = 'bottom' if upper_end else 'top'
            tr_x = transform
            tr_y = self.axes.transAxes + \
                mtrans.ScaledTranslation(
                    0.0,
                    shift_dist_points * (1.0 / 72),
                    self.axes.figure.dpi_scale_trans)
            str_value = self.xformatter(value)
            user_label_style = self.xlabel_style
        elif axis == 'y':
            y = value
            x = 1.0 if upper_end else 0.0
            if matplotlib.__version__ > '2.0':
                v_align = 'center_baseline'
            else:
                v_align = 'center'
            h_align = 'left' if upper_end else 'right'
            tr_y = transform
            tr_x = self.axes.transAxes + \
                mtrans.ScaledTranslation(
                    shift_dist_points * (1.0 / 72),
                    0.0,
                    self.axes.figure.dpi_scale_trans)
            str_value = self.yformatter(value)
            user_label_style = self.ylabel_style
        else:
            raise ValueError(
                "Unknown axis, {!r}, must be either 'x' or 'y'".format(axis))

        # Make a 'blended' transform for label text positioning.
        # One coord is geographic, and the other a plain Axes
        # coordinate with an appropriate offset.
        label_transform = mtrans.blended_transform_factory(
            x_transform=tr_x, y_transform=tr_y)

        label_style = {'verticalalignment': v_align,
                       'horizontalalignment': h_align,
                       }
        label_style.update(user_label_style)

        # Create and add a Text artist with these properties
        text_artist = mtext.Text(x, y, str_value,
                                 clip_on=False,
                                 transform=label_transform, **label_style)
        if axis == 'x':
            self.xlabel_artists.append(text_artist)
        elif axis == 'y':
            self.ylabel_artists.append(text_artist)
        self.axes.add_artist(text_artist)
示例#20
0
 def legend_artist(self, legend, orig_handle, fontsize, handlebox):
     x0, y0 = handlebox.xdescent, handlebox.ydescent
     title = mtext.Text(x0, y0, orig_handle, **self.text_props)
     handlebox.add_artist(title)
     return title
示例#21
0
def boxrlabel(box, s, **kargs):
    if 'fontsize' not in kargs:
        kargs['fontsize'] = 15
    x, y = box.xmax, (box.ymin + box.ymax) / 2
    return mtext.Text(x, y, s, va='center', ha='left', **kargs)
示例#22
0
    def __init__(self, Q, X, Y, U, label,
                 *, angle=0, coordinates='axes', color=None, labelsep=0.1,
                 labelpos='N', labelcolor=None, fontproperties=None,
                 **kw):
        """
        Add a key to a quiver plot.

        The positioning of the key depends on *X*, *Y*, *coordinates*, and
        *labelpos*.  If *labelpos* is 'N' or 'S', *X*, *Y* give the position of
        the middle of the key arrow.  If *labelpos* is 'E', *X*, *Y* positions
        the head, and if *labelpos* is 'W', *X*, *Y* positions the tail; in
        either of these two cases, *X*, *Y* is somewhere in the middle of the
        arrow+label key object.

        Parameters
        ----------
        Q : `matplotlib.quiver.Quiver`
            A `.Quiver` object as returned by a call to `~.Axes.quiver()`.
        X, Y : float
            The location of the key.
        U : float
            The length of the key.
        label : str
            The key label (e.g., length and units of the key).
        angle : float, default: 0
            The angle of the key arrow, in degrees anti-clockwise from the
            x-axis.
        coordinates : {'axes', 'figure', 'data', 'inches'}, default: 'axes'
            Coordinate system and units for *X*, *Y*: 'axes' and 'figure' are
            normalized coordinate systems with (0, 0) in the lower left and
            (1, 1) in the upper right; 'data' are the axes data coordinates
            (used for the locations of the vectors in the quiver plot itself);
            'inches' is position in the figure in inches, with (0, 0) at the
            lower left corner.
        color : color
            Overrides face and edge colors from *Q*.
        labelpos : {'N', 'S', 'E', 'W'}
            Position the label above, below, to the right, to the left of the
            arrow, respectively.
        labelsep : float, default: 0.1
            Distance in inches between the arrow and the label.
        labelcolor : color, default: :rc:`text.color`
            Label color.
        fontproperties : dict, optional
            A dictionary with keyword arguments accepted by the
            `~matplotlib.font_manager.FontProperties` initializer:
            *family*, *style*, *variant*, *size*, *weight*.
        **kwargs
            Any additional keyword arguments are used to override vector
            properties taken from *Q*.
        """
        martist.Artist.__init__(self)
        self.Q = Q
        self.X = X
        self.Y = Y
        self.U = U
        self.angle = angle
        self.coord = coordinates
        self.color = color
        self.label = label
        self._labelsep_inches = labelsep
        self.labelsep = (self._labelsep_inches * Q.axes.figure.dpi)

        # try to prevent closure over the real self
        weak_self = weakref.ref(self)

        def on_dpi_change(fig):
            self_weakref = weak_self()
            if self_weakref is not None:
                self_weakref.labelsep = self_weakref._labelsep_inches * fig.dpi
                # simple brute force update works because _init is called at
                # the start of draw.
                self_weakref._initialized = False

        self._cid = Q.axes.figure.callbacks.connect(
            'dpi_changed', on_dpi_change)

        self.labelpos = labelpos
        self.labelcolor = labelcolor
        self.fontproperties = fontproperties or dict()
        self.kw = kw
        _fp = self.fontproperties
        # boxprops = dict(facecolor='red')
        self.text = mtext.Text(
            text=label,  # bbox=boxprops,
            horizontalalignment=self.halign[self.labelpos],
            verticalalignment=self.valign[self.labelpos],
            fontproperties=font_manager.FontProperties._from_any(_fp))

        if self.labelcolor is not None:
            self.text.set_color(self.labelcolor)
        self._initialized = False
        self.zorder = Q.zorder + 0.1
示例#23
0
def plotGraphs(jointPosSeq, jointAnglesSeq, musLengthsSeq, musExcSeq, musActSeq, musForcesSeq, t1, t2, msecInterval, armAnimation, saveGraphs, saveName):
	# graph parameters
	toDegrees = 360/(2*pi)
	toSamples = 1/msecInterval*1000 
	legFont = 11
	linWidth = 3
	color1 = "red"
	color2 = "blue"
	color3 = "green"
	color4 = "purple"
	line1 = "-"
	line2 = ":"
	gridOn = 1
	
	# plot with 6 subplots for joint angles, trajectory and each of muscles
	fig1 = figure()
		
	# time variables
	T = arange(t1, t2, msecInterval/1000.0);
	t1Samples = t1*toSamples
	t2Samples = t2*toSamples
	
	if armAnimation:
		speedFactor = 1 # speed of animation
		
		#create figure and axes
		figAnim = figure()
		axAnim = figAnim.add_subplot(111)
		axAnim.grid(gridOn);
		# set axes size to fit arm
		axAnim.set_xlim(-armLen[0]-armLen[1]-0.1, armLen[0]+armLen[1]+0.1)
		axAnim.set_ylim(-armLen[0]-armLen[1]-0.1, armLen[0]+armLen[1]+0.1)
		
		###########################
		# 2D arm movement animation
		armImages=[]
		for t in arange(t1Samples,t2Samples):
			# Update the arm position based on jointPosSeq
			if useJointPos:
				# use x = z (pnt file) ; y = x (pnt file)
				shoulderPosx = jointPosSeq[1, t]
				shoulderPosy = jointPosSeq[0, t]
				elbowPosx = jointPosSeq[3, t]
				elbowPosy = jointPosSeq[2, t]
				wristPosx = jointPosSeq[5, t]
				wristPosy = jointPosSeq[4, t]
				
				# update jointAnglesSeq based on pos !!!
				
			# Update the arm position based on jointAnglesSeq	
			else:
				armAng = jointAnglesSeq[:,t]
				shoulderPosx = 0
				shoulderPosy = 0
				elbowPosx = armLen[0] * cos(armAng[0]) # end of elbow
				elbowPosy = armLen[0] * sin(armAng[0])
				wristPosx = elbowPosx + armLen[1] * cos(+armAng[0]+armAng[1]) # wrist=arm position
				wristPosy = elbowPosy + armLen[1] * sin(+armAng[0]+armAng[1])
			
			# create
			armLine1 = lines.Line2D([0, elbowPosx-shoulderPosx], [0, elbowPosy-shoulderPosy], color=color1, linestyle=line1, linewidth=linWidth)
			armLine2 = lines.Line2D([elbowPosx-shoulderPosx, wristPosx-shoulderPosx], [elbowPosy-shoulderPosy, wristPosy-shoulderPosy], color=color2, linestyle=line1, linewidth=linWidth)
			axAnim.add_line(armLine1)
			axAnim.add_line(armLine2)
			#label = plt.legend(armLine1, str(t/toSamples) )
			label = text.Text(x=0, y=0.5, text="time = "+str(t/toSamples), weight='bold' )
			axAnim.add_artist(label)
			armImages.append([armLine1, armLine2, label])
		
		# add blank frames
		blankFrames = int(1*toSamples)
		for t in range(blankFrames):
			# Update the arm position
			armLine1 = lines.Line2D([0, 0], [0, 0], color=color1, linestyle=line1, linewidth=linWidth)
			armLine2 = lines.Line2D([0,0 ], [0,0], color=color2, linestyle=line1, linewidth=linWidth)
			axAnim.add_line(armLine1)
			axAnim.add_line(armLine2)			
			armImages.append([armLine1, armLine2])
		
		# generate animation 
		armAnim = animation.ArtistAnimation(figAnim, armImages, interval=msecInterval/speedFactor, repeat_delay=500, blit=True)
	
	###########################
	# Plot joint angles vs time
	ax = fig1.add_subplot(321)
	#T = arange(0, secLength, msecInterval/1000.0);
	
	T=T[:len(jointAnglesSeq[0,t1Samples:t2Samples])]
	ax.plot(T,jointAnglesSeq[0,t1Samples:t2Samples]*toDegrees,color=color1,linestyle=line1, linewidth=linWidth, label="shoulder")
	ax.plot(T,jointAnglesSeq[1,t1Samples:t2Samples]*toDegrees,color=color2,linestyle=line1, linewidth=linWidth, label="elbow")
      
	ax.set_ylabel('angle (deg)', fontsize = legFont)
	ax.set_xlabel('time (sec)', fontsize = legFont)
	ax.set_title('Joint angles')
	ax.legend(loc='upper center', bbox_to_anchor=(1.0, 1.0),  borderaxespad=0., prop={'size':legFont})
	#ax.set_xlim([t1, t2])
    #ax.set_ylim(bmmYlims_sh)
	ax.grid(gridOn)
	
	############################
	# Plot x-y pos vs time
	ax = fig1.add_subplot(322)
	
	# calculate x and y trajectories based on angles
	if useJointPos:
		xTraj = jointPosSeq[4, t1Samples:t2Samples]
		yTraj = jointPosSeq[5, t1Samples:t2Samples]
	else:
		xTraj = armLen[0]*cos(jointAnglesSeq[0,t1Samples:t2Samples])+armLen[1]*cos(jointAnglesSeq[1,t1Samples:t2Samples])
		yTraj = armLen[0]*sin(jointAnglesSeq[0,t1Samples:t2Samples])+armLen[0]*sin(jointAnglesSeq[1,t1Samples:t2Samples])
	
	#ax.plot(xTraj, yTraj,color=color2,linestyle=line1, linewidth=linWidth)
	ax.plot(T, xTraj,color=color1,linestyle=line1, linewidth=linWidth, label="x")
	ax.plot(T, yTraj,color=color2,linestyle=line1, linewidth=linWidth, label="y")
	
	ax.set_ylabel('position (m)', fontsize = legFont)
	#ax.set_xlabel('x position (m)', fontsize = legFont)
	ax.set_xlabel('time (sec)', fontsize = legFont)
	ax.set_title('X-Y trajectory')
	ax.legend(loc='upper center', bbox_to_anchor=(1.0, 1.0),  borderaxespad=0., prop={'size':legFont})
	#ax.set_xlim([t1, t2])
    #ax.set_ylim(bmmYlims_sh)
	ax.grid(gridOn)
	
	############################
	# Plot excitation, activation and force for each muscle
	
	# calculate normalized force (activation and length already normalized)
	#musActSeqNorm = musActSeq/musActSeq[:,t1Samples:t2Samples].max()
	musForcesSeqNorm = musForcesSeq/musForcesSeq[:,t1Samples:t2Samples].max()
	#musLengthsSeqNorm = musLengthsSeq/musLengthsSeq[:,t1Samples:t2Samples].max()
	
	# Note arrangement of muscle branches in data arrays:
	#DELT1(0)  DELT2(1) DELT3(2) Infraspinatus(3) Latissimus_dorsi_1(4) Latissimus_dorsi_2(5) Latissimus_dorsi_3(6) 
	#Teres_minor(7) PECM1(8) PECM2(9) PECM3(10) Coracobrachialis(11) TRIlong(12) TRIlat(13) TRImed(14) BIClong(15) BICshort(16) BRA(17)  
	# is different from muscle groups:
	# Sh ext = DELT3, Infraspinatus, Latissimus_dorsi_1-3, Teres_minor
	# Sh flex = PECM1, PECM2, PECM3, DELT1, Coracobrachialis
	# El ext = TRIlong, TRIlat, TRImed
	# El flex = BIClong, BICshort, BRA
	shext=[2,3,4,5,6,7]
	shflex=[0,8,9,10,11]
	elext=[12,13,14]
	elflex=[15,16,17]
	musList=[shext, shflex,elext,elflex]
		
	for iMus in range(numMuscles):
		ax = fig1.add_subplot(3,2,iMus+3)
		# set number of muscle branches - assume each node has 3 branches (treat the Brachialis as a branch of Biceps=elbow flexor)
		#iBranches = 3
		
		### Excitation and Activation ####
		# equivalent for all branches of same muscle group
		offset = 2  # use offset 3 because only DELT3 is used (order of muscle branches doesn't correspond muscle groups!)
		ax.plot(T, musExcSeq[musList[iMus][offset],t1Samples:t2Samples],color=color1,linestyle=line1, linewidth=linWidth, label="excitation")
		ax.plot(T, musActSeq[musList[iMus][offset],t1Samples:t2Samples],color=color2,linestyle=line1, linewidth=linWidth, label="activation")
		
		# for show branches plot individual branches and mean value for force and length
		if showBranches:
			### Force and Length ###
			for iBranch in range(len(musList[iMus])):
				ax.plot(T, musForcesSeqNorm[musList[iMus][iBranch],t1Samples:t2Samples],color=color3,linestyle=line2, linewidth=linWidth-1)
				ax.plot(T, musLengthsSeq[musList[iMus][iBranch],t1Samples:t2Samples],color=color4,linestyle=line2, linewidth=linWidth-1)
			ax.plot(T, musForcesSeqNorm[musList[iMus],t1Samples:t2Samples].mean(axis=0),color=color3,linestyle=line1, linewidth=linWidth, label="force (mean)")
			ax.plot(T, musLengthsSeq[musList[iMus],t1Samples:t2Samples].mean(axis=0),color=color4,linestyle=line1, linewidth=linWidth, label="length (mean)")
		# for NOT show branches show mean value for force and single value for length
		else:
			### Force ###
			# For shoulder extensor group show only posterior Deltoid, branch 3 (DELT3) or Infraspinatus (INFSP) 
			# branch 2 (DELT2 = lateral deltoid) also available but currently not included in shoulder extensor group
			if iMus == 0:
				offset = 2 # DELT3
				#offset = 12 # INFSP 
				ax.plot(T, musForcesSeqNorm[musList[iMus][offset],t1Samples:t2Samples],color=color3,linestyle=line1, linewidth=linWidth, label="force")
			# For rest of muscles use mean value of all branches
			else:
				offset=0
				ax.plot(T, musForcesSeqNorm[musList[iMus],t1Samples:t2Samples].mean(axis=0),color=color3,linestyle=line1, linewidth=linWidth, label="force")
			
			### Length ####
			# show length only of one muscle indicated by the index 'offset' - DELT3, PECM1, BIClong, TRIlong
			maxLength = 0.20 
			ax.plot(T, musLengthsSeq[musList[iMus][offset],t1Samples:t2Samples]/maxLength,color=color4,linestyle=line1, linewidth=linWidth, label="length")
	
		# show branche label
		if (showBranches):
			ax.plot(-1, -1,color=color3,linestyle=line2, linewidth=linWidth, label="force (branches)")
			ax.plot(-1, -1,color=color4,linestyle=line2, linewidth=linWidth, label="length (branches)")
		
		# axis properties
		ax.set_ylabel('normalized value', fontsize = legFont)
		ax.set_ylim([0,1])
		ax.set_xlim([t1,t2])
		ax.set_xlabel('time (sec)', fontsize = legFont)
		ax.set_title(muscleNames[iMus])
		if iMus==3:
			ax.legend(loc='upper center', bbox_to_anchor=(-0.2, 1.8),  borderaxespad=0., prop={'size':legFont})
		ax.grid(gridOn)
	
	# show graphs
	fig1.tight_layout()
	show()
	
	# save graphs using startPos and pattern in filename
	if saveGraphs:
		saveFolder = 'gif/'
		fig1.savefig(saveFolder+saveName, bbox_inches=0)
示例#24
0
def plotHtsTrajHM(hchem_id,
                  exp_id,
                  add_t0=False,
                  use_resp='fc',
                  fgsz=(18, 4),
                  vmin=-3,
                  vmax=3,
                  fs=0.9,
                  xyoff=[2, -6],
                  ctrl=False,
                  iconc=3,
                  FT=FT1,
                  FTLB=FTLB1,
                  LCi=None,
                  draw_chem=False,
                  CM=cm.RdYlBu_r,
                  suffix=1,
                  save=None,
                  loc=None,
                  cb=False,
                  sub_title=None):
    # Get the conc-resp data
    X_CR = getChemConcResp(hchem_id,
                           exp_id=exp_id,
                           ret='df',
                           add_t0=add_t0,
                           prows=[
                               'chem_id', 'hchem_id', 'chem_name',
                               'chem_casrn', 'timeh', 'lconc'
                           ],
                           pcols=['assay_id'])
    if X_CR.shape[0] == 0: return

    resp_col = None
    leg_txt = None
    if use_resp == 'zs':
        resp_col = 'pzsc'
        leg_txt = 'Z'
    elif use_resp == 'fc':
        resp_col = 'slfc',
        leg_txt = r'$log_2(FC)$'
    elif use_resp == 'pct':
        resp_col = 'ppct'
        leg_txt = 'Prcnt'
    else:
        resp_col = 'slfc'
        leg_txt = r'$log_2(FC)$'

    X_FC = X_CR.ix[:, resp_col]

    # Get LEC
    LEC = None
    EFF = None
    #X_AR = getChemAssayResults(hchem_id,exp_id=exp_id,ret='df')
    #if X_AR.shape[0]==0: return
    #try:
    #    LEC = X_AR['llec']
    #    EFF = X_AR['lfc_eff']
    #except:
    #    print "No LEC data"

    fig = pl.figure(figsize=fgsz)
    FT0 = set([i for i in X_FC.columns])
    TM0 = sorted(set([i[-2] for i in X_FC.index]))
    LC0 = list(sorted(set([i[-1] for i in X_FC.index])))
    if LCi:
        LC0 = [LC0[i] for i in LCi]

    #gs1 = gridspec.GridSpec(2,6,width_ratios=[1,1,1,1,1,1])
    #if ctrl:
    #    gs1 = gridspec.GridSpec(1,8,width_ratios=[1,1,1,1,1,1,1,1])
    #else:

    gs1 = None
    if len(LC0) > 5:
        gs1 = gridspec.GridSpec(2, 8, width_ratios=[1, 1, 1, 1, 1, 1, 1, 0.3])
        ax = pl.subplot(gs1[0:1, 0:1])
    else:
        gs1 = gridspec.GridSpec(1, 7, width_ratios=[1.2, 1, 1, 1, 1, 1, 0.3])
        ax = pl.subplot(gs1[0, 0])

    # Chemical name casrn
    # ['chem_id', 'hchem_id', 'chem_name', 'chem_casrn', 'lconc']
    chem = X_FC.index[0][2]
    casrn = X_FC.index[0][3]
    sid = X_FC.index[0][1]
    cid = X_FC.index[0][0]
    nm = None
    if len(LC0) > 5:
        nm = '\n'.join(wrap(chem, 30)) + '\n' + casrn + '\n' + sid
        if sub_title: nm += '\n' + sub_title
    else:
        nm = '\n'.join(wrap(chem, 25))

    txt = text.Text(50,
                    50,
                    nm,
                    ha='center',
                    va='center',
                    color='#111111',
                    fontproperties=fm.FontProperties(size=10))
    ax.add_artist(txt)

    ax.set_axis_off()
    ax.set_xlim(0, 100)
    ax.set_ylim(0, 100)

    k = 0
    iconc = -1

    for lc in LC0:
        uM = np.round(10**(lc + 6), decimals=2)
        X = X_FC[FT].select(lambda xx: xx[iconc] == lc, axis=0)
        #print lc,X_FC.shape,X.shape
        TM = ['%dh' % tm for tm in TM0]
        i = k % 5 + 1
        if k < 5:
            j = 0
        else:
            j = 1
        ax = pl.subplot(gs1[j, i])

        x = ax.pcolor(X.as_matrix(),
                      cmap=CM,
                      edgecolors='white',
                      lw=1,
                      vmin=vmin,
                      vmax=vmax)

        ax.set_title(r'%5.2f$\mu$M' % uM)

        if len(LC0) <= 5 or j == 1:
            ax.xaxis.tick_bottom()
            ax.set_xticks(np.arange(len(FT0)) + 0.5, minor=False)
            ax.set_xticklabels([FTLB[ft] for ft in X.columns], rotation=90)
            for tick in ax.get_xticklines():
                tick.set_visible(True)
            for tick in ax.get_xticklabels():
                tick.set_fontsize(9)
        else:
            for tick in ax.get_xticklines():
                tick.set_visible(True)
            for lab in ax.get_xticklabels():
                lab.set_visible(False)

        if (len(LC0) > 5 and i == 2) or i == 1:
            ax.yaxis.tick_left()
            ax.set_ylim(top=len(TM))
            ax.set_yticks(np.arange(len(TM)) + 0.5, minor=False)
            ax.set_yticklabels(TM)
            for tick in ax.get_yticklines():
                tick.set_visible(True)
            for tick in ax.get_yticklabels():
                tick.set_fontsize(10)
        else:
            for tick in ax.get_yticklines():
                tick.set_visible(False)
            for lab in ax.get_yticklabels():
                lab.set_visible(False)
        k += 1

    if len(LC0) > 5:
        ax = pl.subplot(gs1[:, 7])
    else:
        ax = pl.subplot(gs1[:, 6])

    ax.set_axis_off()
    if cb:
        cbr = pl.colorbar(x, ax=ax, shrink=0.9, ticks=range(-vmax, vmax + 1))
        cbr.ax.set_xlabel(leg_txt, fontsize=10)

    pl.subplots_adjust(wspace=0.3, hspace=0.3, top=1, bottom=0)
    if save and loc:
        fig.savefig(loc + "traj-hm-%s-%s-%s-%s-%d.svg" %
                    (resp_col, exp_id.lower(), hchem_id.lower(),
                     chem.lower().replace(' ', '-'), suffix))
        fig.savefig(loc + "traj-hm-%s-%s-%s-%s-%d.png" %
                    (resp_col, exp_id.lower(), hchem_id.lower(),
                     chem.lower().replace(' ', '-'), suffix))
示例#25
0
def plotHtsConcRespHM(hchem_id,
                      exp_id,
                      add_t0=False,
                      use_resp='fc',
                      fgsz=(20, 4),
                      vmin=-3,
                      vmax=3,
                      fs=0.9,
                      xyoff=[2, -6],
                      ctrl=False,
                      iconc=3,
                      FT=FT1,
                      FTLB=FTLB1,
                      lec=False,
                      CM=cm.RdYlBu_r,
                      draw_chem=False,
                      save=None,
                      loc=None,
                      cb=False,
                      sub_title=None):
    # Get the conc-resp data
    X_CR = getChemConcResp(hchem_id, exp_id=exp_id, ret='df', add_t0=add_t0)
    if X_CR.shape[0] == 0: return
    # Get the fold change
    resp_col = None
    leg_txt = None
    if use_resp == 'zs':
        resp_col = 'pzsc'
        leg_txt = 'Z'
    elif use_resp == 'fc':
        resp_col = 'slfc',
        leg_txt = r'$log_2(FC)$'
    elif use_resp == 'pct':
        resp_col = 'ppct'
        leg_txt = 'Prcnt'
    else:
        resp_col = 'slfc'
        leg_txt = r'$log_2(FC)$'

    X_FC = X_CR[resp_col]

    # Get LEC
    LEC = None
    EFF = None
    X_AR = getChemAssayResults(hchem_id, exp_id=exp_id, ret='df')
    if X_AR.shape[0] == 0: return
    try:
        LEC = X_AR['llec']
        EFF = X_AR['lfc_eff']
    except:
        print "No LEC data"

    if not lec: LEC = None
    fig = pl.figure(figsize=fgsz)
    FT0 = set([i[1] for i in X_FC.columns])
    TM0 = sorted(set([i[0] for i in X_FC.columns]))
    #gs1 = gridspec.GridSpec(2,6,width_ratios=[1,1,1,1,1,1])
    #if ctrl:
    #    gs1 = gridspec.GridSpec(1,8,width_ratios=[1,1,1,1,1,1,1,1])
    #else:
    gs1 = gridspec.GridSpec(2, 8, width_ratios=[1, 1, 1, 1, 1, 1, 1, 0.3])

    # Chemical name casrn
    # ['chem_id', 'hchem_id', 'chem_name', 'chem_casrn', 'lconc']
    ax = pl.subplot(gs1[0:2, 0:2])
    chem = X_FC.index[0][2]
    casrn = X_FC.index[0][3]
    sid = X_FC.index[0][1]
    cid = X_FC.index[0][0]
    nm = '\n'.join(wrap(chem, 30)) + '\n' + casrn + '\n' + sid
    if sub_title: nm += '\n' + sub_title

    txt = text.Text(60,
                    100,
                    nm,
                    ha='center',
                    va='center',
                    color='#111111',
                    fontproperties=fm.FontProperties(size=10))
    ax.add_artist(txt)
    ax.set_axis_off()
    ax.set_xlim(right=120)
    ax.set_ylim(top=120)

    k = 0
    iconc = -1
    for ft in FT:
        if ft not in FT0: continue
        X = X_FC[[(tm, ft) for tm in TM0]]
        TM = ['%dh' % tm for tm in TM0]
        i = k % 5 + 2
        if k < 5:
            j = 0
        else:
            j = 1
        ax = pl.subplot(gs1[j, i])
        x = ax.pcolor(X.T,
                      cmap=CM,
                      edgecolors='white',
                      lw=1,
                      vmin=vmin,
                      vmax=vmax)
        ax.set_title(FTLB[ft])
        # Calc conc
        LC = [ii[iconc] for ii in X.index]
        uM_log = np.array(LC)
        uM = np.round(10**np.array(uM_log + 6, dtype=np.float), decimals=2)

        try:
            LLC = [v[iconc] for v in X_FC.index]
            LLCx = np.arange(len(LLC)) + 0.5

            for it, tm in enumerate(TM0):
                if tm == 0: continue
                lec_ft = LEC[(tm, ft)]
                if lec_ft == 0 or np.isnan(lec_ft): continue
                lec_fc = EFF[(tm, ft)]
                col = ifthen(lec_fc < 0, 'red', 'blue')
                ilc = np.interp(lec_ft, LLC, LLCx)
                ax.text(ilc,
                        it + 0.5,
                        r'$\bullet$',
                        ha='center',
                        va='center',
                        color=col,
                        fontproperties=fm.FontProperties(size=20))
        except:
            pass
        #print i
        #if i == 0:
        #print i,j,ft
        if j == 1 or ctrl:
            ax.xaxis.tick_bottom()
            ax.set_xticks(np.arange(len(uM)) + 0.5, minor=False)
            ax.set_xticklabels(uM, rotation=90)
            for tick in ax.get_xticklines():
                tick.set_visible(True)
            for tick in ax.get_xticklabels():
                tick.set_fontsize(9)
        else:
            for tick in ax.get_xticklines():
                tick.set_visible(True)
            for lab in ax.get_xticklabels():
                lab.set_visible(False)

        if i == 2:
            ax.yaxis.tick_left()
            ax.set_ylim(top=len(TM))
            ax.set_yticks(np.arange(len(TM)) + 0.5, minor=False)
            ax.set_yticklabels(TM)
            for tick in ax.get_yticklines():
                tick.set_visible(True)
            for tick in ax.get_yticklabels():
                tick.set_fontsize(10)
        else:
            for tick in ax.get_yticklines():
                tick.set_visible(False)
            for lab in ax.get_yticklabels():
                lab.set_visible(False)
        k += 1

    ax = pl.subplot(gs1[:, 7])
    ax.set_axis_off()
    if cb:
        cbr = pl.colorbar(x, ax=ax, shrink=0.9, ticks=range(-vmax, vmax + 1))
        cbr.ax.set_xlabel(leg_txt, fontsize=10)
    if save and loc:
        fig.savefig(loc + "cr-%s-%s-%s-%s.svg" %
                    (resp_col, exp_id.lower(), hchem_id.lower(),
                     chem.lower().replace(' ', '-')))

    pl.subplots_adjust(wspace=0.1, hspace=0.3, top=0.9, bottom=0.1)
示例#26
0
 def __init__(self, *args, **kwargs):
     # we'll update the position when the line data is set
     self.text = mtext.Text(0, 0, '')
     LINES.Line2D.__init__(self, *args, **kwargs)
     self.text.set_text(kwargs["label"])
示例#27
0
 def create_artists(self, legend, orig_handle, x0, y0, width, height,
                    fontsize, trans):
     if orig_handle == 'CloudTopPressure':
         l1 = plt.Line2D([0.5 * width], [0.5 * height],
                         marker='s',
                         ms=2.5,
                         color='xkcd:magenta')
         l2 = plt.Line2D([
             x0 + 0.5 * width - 0.4 * height,
             x0 + 0.5 * width + 0.4 * height
         ], [0.5 * height, 0.5 * height],
                         linestyle='-',
                         color='xkcd:magenta',
                         lw=1)
         l3 = plt.Line2D([0.5 * width, 0.5 * width],
                         [0.1 * height, 0.9 * height],
                         linestyle='-',
                         color='xkcd:magenta',
                         lw=1)
         return [l1, l2, l3]
     if orig_handle == 'SurfacePressure':
         l1 = plt.Line2D([0.5 * width], [0.5 * height],
                         marker='o',
                         ms=2.5,
                         color='xkcd:red')
         l2 = plt.Line2D([
             x0 + 0.5 * width - 0.4 * height,
             x0 + 0.5 * width + 0.4 * height
         ], [0.5 * height, 0.5 * height],
                         linestyle='-',
                         color='xkcd:red',
                         lw=1)
         l3 = plt.Line2D([0.5 * width, 0.5 * width],
                         [0.1 * height, 0.9 * height],
                         linestyle='-',
                         color='xkcd:red',
                         lw=1)
         return [l1, l2, l3]
     if orig_handle == 'ErrorBar':
         l1 = plt.Line2D([width / 2], [0.5 * height],
                         marker='o',
                         ms=10,
                         color='w',
                         markeredgecolor='k',
                         alpha=0.2)
         l2 = plt.Line2D([x0, x0], [0.2 * height, 0.8 * height],
                         linestyle='-',
                         color='k',
                         lw=2)
         l3 = plt.Line2D([y0 + width, y0 + width],
                         [0.2 * height, 0.8 * height],
                         linestyle='-',
                         color='k',
                         lw=2)
         l4 = plt.Line2D([x0, y0 + width], [0.5 * height, 0.5 * height],
                         color='k',
                         lw=2)
         return [l1, l2, l3, l4]
     elif orig_handle == 'Limit':
         l1 = plt.Line2D([2 * width / 3], [0.5 * height],
                         marker='o',
                         ms=10,
                         color='w',
                         markeredgecolor='k',
                         alpha=0.2)
         l2 = plt.Line2D([x0 + width / 3, x0 + width / 3],
                         [0.2 * height, 0.8 * height],
                         linestyle='-',
                         color='k',
                         lw=2)
         l3 = plt.Line2D([y0 + width, y0 + width],
                         [0.2 * height, 0.8 * height],
                         linestyle='-',
                         color='k',
                         lw=2)
         l4 = plt.Line2D([x0 + width / 3, y0 + width],
                         [0.5 * height, 0.5 * height],
                         color='k',
                         lw=2)
         l5 = plt.Line2D([x0, y0 + width / 3], [0.5 * height, 0.5 * height],
                         color='k',
                         ls=':',
                         lw=2)
         l6 = plt.Line2D([x0 + 3 * 0.2 * height, x0, x0 + 3 * 0.2 * height],
                         [0.2 * height, 0.5 * height, 0.8 * height],
                         color='k',
                         ls='-',
                         lw=2)
         return [l1, l2, l3, l4, l5, l6]
     elif orig_handle == 'UpperLimit':
         #l1 = plt.Line2D([width/2], [0.5*height], marker = 'o', ms=10,color='w',markeredgecolor='k',alpha=0.2)
         l2 = plt.Line2D([x0 + width, x0 + width],
                         [0.2 * height, 0.8 * height],
                         linestyle='-',
                         color='k',
                         lw=2)
         l3 = plt.Line2D([x0, y0 + width], [0.5 * height, 0.5 * height],
                         color='k',
                         lw=2)
         l4 = plt.Line2D([x0 + 3 * 0.2 * height, x0, x0 + 3 * 0.2 * height],
                         [0.2 * height, 0.5 * height, 0.8 * height],
                         color='k',
                         ls='-',
                         lw=2)
         return [l1, l2, l3, l4]
     elif orig_handle == 'LowerLimit':
         l1 = plt.Line2D([width / 2], [0.5 * height],
                         marker='o',
                         ms=10,
                         color='w',
                         markeredgecolor='k',
                         alpha=0.2)
         l2 = plt.Line2D([x0 + width, x0 + width],
                         [0.2 * height, 0.8 * height],
                         linestyle='-',
                         color='k',
                         lw=2)
         l3 = plt.Line2D([x0, y0 + width], [0.5 * height, 0.5 * height],
                         color='k',
                         lw=2)
         l4 = plt.Line2D([x0 + 3 * 0.2 * height, x0, x0 + 3 * 0.2 * height],
                         [0.2 * height, 0.5 * height, 0.8 * height],
                         color='k',
                         ls='-',
                         lw=2)
         return [l1, l2, l3, l4]
     elif orig_handle == 'Unconstrained':
         l1 = plt.Line2D([width / 2], [0.5 * height],
                         marker='o',
                         ms=10,
                         color='w',
                         markeredgecolor='k',
                         alpha=0.2)
         l2 = plt.Line2D([
             x0 + width - 3 * 0.2 * height, x0 + width,
             x0 + width - 3 * 0.2 * height
         ], [0.2 * height, 0.5 * height, 0.8 * height],
                         linestyle='-',
                         color='k',
                         lw=2)
         l3 = plt.Line2D([x0, y0 + width], [0.5 * height, 0.5 * height],
                         color='k',
                         lw=2,
                         ls=':')
         l4 = plt.Line2D([x0 + 3 * 0.2 * height, x0, x0 + 3 * 0.2 * height],
                         [0.2 * height, 0.5 * height, 0.8 * height],
                         color='k',
                         ls='-',
                         lw=2)
         return [l1, l2, l3, l4]
     elif orig_handle == 'SNR5':
         l1 = plt.Line2D([x0, x0 + width], [0.5 * height, 0.5 * height],
                         lw=2,
                         color='k',
                         ls='-',
                         alpha=0.2)
         l2 = plt.Line2D([width / 2], [0.5 * height],
                         marker='o',
                         ms=10,
                         color='w',
                         markeredgecolor='k')
         return [l1, l2]
     elif orig_handle == 'SNR10':
         l1 = plt.Line2D([x0, x0 + width], [0.5 * height, 0.5 * height],
                         lw=2,
                         color='k',
                         ls='-',
                         alpha=0.2)
         l2 = plt.Line2D([width / 2], [0.5 * height],
                         marker='s',
                         ms=10,
                         color='w',
                         markeredgecolor='k')
         return [l1, l2]
     elif orig_handle == 'SNR15':
         l1 = plt.Line2D([x0, x0 + width], [0.5 * height, 0.5 * height],
                         lw=2,
                         color='k',
                         ls='-',
                         alpha=0.2)
         l2 = plt.Line2D([width / 2], [0.5 * height],
                         marker='D',
                         ms=10,
                         color='w',
                         markeredgecolor='k')
         return [l1, l2]
     elif orig_handle == 'SNR20':
         l1 = plt.Line2D([x0, x0 + width], [0.5 * height, 0.5 * height],
                         lw=2,
                         color='k',
                         ls='-',
                         alpha=0.2)
         l2 = plt.Line2D([width / 2], [0.5 * height],
                         marker='v',
                         ms=10,
                         color='w',
                         markeredgecolor='k')
         return [l1, l2]
     elif orig_handle == 'R20':
         l1 = plt.Line2D([width / 2], [0.5 * height],
                         marker='o',
                         ms=10,
                         color='w',
                         markeredgecolor='k',
                         alpha=0.2)
         l2 = plt.Line2D([x0, x0 + width], [0.5 * height, 0.5 * height],
                         lw=2,
                         color='C3',
                         ls='-')
         return [l1, l2]
     elif orig_handle == 'R35':
         l1 = plt.Line2D([width / 2], [0.5 * height],
                         marker='o',
                         ms=10,
                         color='w',
                         markeredgecolor='k',
                         alpha=0.2)
         l2 = plt.Line2D([x0, x0 + width], [0.5 * height, 0.5 * height],
                         lw=2,
                         color='C2',
                         ls='-')
         return [l1, l2]
     elif orig_handle == 'R50':
         l1 = plt.Line2D([width / 2], [0.5 * height],
                         marker='o',
                         ms=10,
                         color='w',
                         markeredgecolor='k',
                         alpha=0.2)
         l2 = plt.Line2D([x0, x0 + width], [0.5 * height, 0.5 * height],
                         lw=2,
                         color='C0',
                         ls='-')
         return [l1, l2]
     elif orig_handle == 'R100':
         l1 = plt.Line2D([width / 2], [0.5 * height],
                         marker='o',
                         ms=10,
                         color='w',
                         markeredgecolor='k',
                         alpha=0.2)
         l2 = plt.Line2D([x0, x0 + width], [0.5 * height, 0.5 * height],
                         lw=2,
                         color='C1',
                         ls='-')
         return [l1, l2]
     elif orig_handle == 'Prior':
         l1 = plt.Line2D([width / 2], [0.5 * height],
                         marker='o',
                         ms=10,
                         color='w',
                         markeredgecolor='k',
                         alpha=0.2)
         l2 = plt.Line2D([x0, x0 + width], [0.5 * height, 0.5 * height],
                         lw=2,
                         color='Black',
                         ls='-')
         return [l1, l2]
     else:
         title = mtext.Text(x0,
                            y0,
                            orig_handle + '',
                            weight='bold',
                            usetex=False,
                            **self.text_props,
                            fontsize=18)
         return [title]
示例#28
0
def main(argv=sys.argv):

    parser = argparse.ArgumentParser(
        description=(
            "Stitch a multi-tile image using the nominal stage positions and"
            " display the resulting image."
        )
    )
    parser.add_argument(
        "input", help="Path to image (BioFormats supported formats only)"
    )
    parser.add_argument(
        "-n", "--numbers", action="store_true", help="Display tile numbers"
    )
    parser.add_argument(
        "-b", "--bounds", action="store_true", help="Display tile bounds"
    )
    parser.add_argument(
        "-c", "--channel", type=int, default=0,
        help="Channel number to display; default: 0",
    )
    parser.add_argument(
        "-l", "--log", action="store_true", help="Log-transform pixel intensities"
    )
    args = parser.parse_args()

    reader = reg.BioformatsReader(args.input)
    metadata = reader.metadata

    positions = metadata.positions - metadata.origin
    mshape = ((positions + metadata.size).max(axis=0) + 1).astype(int)
    mosaic = np.zeros(mshape, dtype=np.uint16)

    total = reader.metadata.num_images
    for i in range(total):
        sys.stdout.write("\rLoading %d/%d" % (i + 1, total))
        sys.stdout.flush()
        img = reader.read(c=args.channel, series=i)
        img = skimage.util.img_as_uint(img)
        if args.log:
            scale = 65535 / np.log(65535)
            img = (np.log(np.maximum(img, 1)) * scale).astype(np.uint16)
        # Round position so paste will skip the expensive subpixel shift.
        pos = np.round(positions[i])
        utils.paste(mosaic, img, pos, np.maximum)
    print()

    ax = plt.gca()

    plt.imshow(X=mosaic, axes=ax)

    h, w = metadata.size
    for i, (x, y) in enumerate(np.fliplr(positions)):
        if args.bounds:
            rect = mpatches.Rectangle((x, y), w, h, color='black', fill=False)
            ax.add_patch(rect)
        if args.numbers:
            xc = x + w / 2
            yc = y + h / 2
            circle = mpatches.Circle((xc, yc), w / 5, color='salmon', alpha=0.5)
            text = mtext.Text(
                xc, yc, str(i), color='k', size=10, ha='center', va='center'
            )
            ax.add_patch(circle)
            ax.add_artist(text)

    plt.show()
示例#29
0
    def __init__(self, fig, sort_func, data):
        # Create the animation objects

        # Artists are scaled according to aspect ratio. We'll need to undo
        # this to draw circles.
        xsize, ysize = fig.get_size_inches()
        yscale = xsize / ysize

        # This magic invisible line makes the figure show up
        fig.lines.append(
            lines.Line2D([0, 0], [0, 1],
                         transform=fig.transFigure,
                         figure=fig,
                         color='white'))

        self._spacing = 1.0 / (len(data) + 1)
        self._radius = 0.8 * self._spacing
        smallest = min(*data)
        largest = max(*data)

        def scaled_radius(value):
            interp = (value - smallest) / (largest - smallest)
            return self._radius * (0.6 + interp * 0.4)

        def create_artists(i, v):
            x = (i + 0.5) * self._spacing
            y = 0.5
            r = scaled_radius(v)
            c = patches.Ellipse((x, y),
                                r,
                                yscale * r,
                                transform=fig.transFigure,
                                figure=fig,
                                fill=False)

            t = text.Text(x,
                          y,
                          str(v),
                          transform=fig.transFigure,
                          figure=fig,
                          verticalalignment='center',
                          horizontalalignment='center',
                          fontsize=300 * r)
            return c, t

        def create_arrow():
            return patches.Polygon(self._arrow_points(),
                                   closed=True,
                                   transform=fig.transFigure,
                                   figure=fig,
                                   visible=False)

        self._circles, self._texts = map(
            list, zip(*[create_artists(i, v) for i, v in enumerate(data)]))
        self._arrows = [create_arrow(), create_arrow()]

        fig.patches.extend(self._circles)
        fig.patches.extend(self._arrows)
        fig.texts.extend(self._texts)

        self._label = text.Text(0,
                                0.9,
                                transform=fig.transFigure,
                                figure=fig,
                                verticalalignment='top',
                                horizontalalignment='left',
                                fontsize=200 * self._spacing)
        fig.texts.append(self._label)

        # Collect effects and generate animation frames
        effects = []
        sort.run(sort_func, data, lambda *e: effects.append(e))
        self._generate_frames(effects)
        self._focused = []
示例#30
0
    def __init__(self, *args, **kwargs):
        self.text = mtext.Text(0, 0, '')
        lines.Line2D.__init__(self, *args, **kwargs)

        self.text.set_text(self.get_label())