Ejemplo n.º 1
0
def plotFragments(fragment_list,
                  clip_patch,
                  color_map,
                  alignment="vertical",
                  ax=None):
    ax = ax if ax is not None else plt.gca

    for fragment in fragment_list:
        start = fragment[1]
        end = fragment[2]
        giemsa_stain = fragment[4]
        rect = None
        if (alignment == "vertical"):
            rect = Rectangle([0, -1 * end],
                             1,
                             end - start,
                             facecolor=color_map[giemsa_stain],
                             edgecolor="none",
                             capstyle="butt")
        else:
            rect = Rectangle([start, 0],
                             end - start,
                             1,
                             facecolor=color_map[giemsa_stain],
                             edgecolor="none",
                             capstyle="butt")
        rect.set_clip_path(clip_patch)

        ax.add_patch(rect)
Ejemplo n.º 2
0
 def _init_legend_box(self, handles, labels):
     """
     Initiallize the legend_box. The legend_box is an instance of
     the OffsetBox, which is packed with legend handles and
     texts. Once packed, their location is calculated during the
     drawing time.
     """
     fontsize = self._fontsize
     text_list = []  # the list of text instances
     handle_list = []  # the list of text instances
     label_prop = dict(verticalalignment='baseline',
                       horizontalalignment='left',
                       fontproperties=self.prop,
                       )
     labelboxes = []
     handleboxes = []
     height = self._approx_text_height() * 0.7
     descent = 0.
     for handle, lab in zip(handles, labels):
         if isinstance(handle, RegularPolyCollection) or \
                isinstance(handle, CircleCollection):
             npoints = self.scatterpoints
         else:
             npoints = self.numpoints
         if npoints > 1:
             xdata = np.linspace(0.3*fontsize,
                                 (self.handlelength-0.3)*fontsize,
                                 npoints)
             xdata_marker = xdata
         elif npoints == 1:
             xdata = np.linspace(0, self.handlelength*fontsize, 2)
             xdata_marker = [0.5*self.handlelength*fontsize]
         if isinstance(handle, Line2D):
             ydata = ((height-descent)/2.)*np.ones(xdata.shape, float)
             legline = Line2D(xdata, ydata)
             legline.update_from(handle)
             self._set_artist_props(legline) # after update
             legline.set_clip_box(None)
             legline.set_clip_path(None)
             legline.set_drawstyle('default')
             legline.set_marker('None')
             handle_list.append(legline)
             legline_marker = Line2D(xdata_marker, ydata[:len(xdata_marker)])
             legline_marker.update_from(handle)
             self._set_artist_props(legline_marker)
             legline_marker.set_clip_box(None)
             legline_marker.set_clip_path(None)
             legline_marker.set_linestyle('None')
             legline._legmarker = legline_marker
         elif isinstance(handle, Patch):
             p = Rectangle(xy=(0., 0.),
                           width = self.handlelength*fontsize,
                           height=(height-descent),
                           )
             p.update_from(handle)
             self._set_artist_props(p)
             p.set_clip_box(None)
             p.set_clip_path(None)
             handle_list.append(p)
         elif isinstance(handle, LineCollection):
             ydata = ((height-descent)/2.)*np.ones(xdata.shape, float)
             legline = Line2D(xdata, ydata)
             self._set_artist_props(legline)
             legline.set_clip_box(None)
             legline.set_clip_path(None)
             lw = handle.get_linewidth()[0]
             dashes = handle.get_dashes()[0]
             color = handle.get_colors()[0]
             legline.set_color(color)
             legline.set_linewidth(lw)
             if dashes[0] is not None: # dashed line
                 legline.set_dashes(dashes[1])
             handle_list.append(legline)
         elif isinstance(handle, RegularPolyCollection):
             ydata = height*self._scatteryoffsets
             size_max, size_min = max(handle.get_sizes()),\
                                  min(handle.get_sizes())
             if self.scatterpoints < 4:
                 sizes = [.5*(size_max+size_min), size_max,
                          size_min]
             else:
                 sizes = (size_max-size_min)*np.linspace(0,1,self.scatterpoints)+size_min
             p = type(handle)(handle.get_numsides(),
                              rotation=handle.get_rotation(),
                              sizes=sizes,
                              offsets=zip(xdata_marker,ydata),
                              transOffset=self.get_transform(),
                              )
             p.update_from(handle)
             p.set_figure(self.figure)
             p.set_clip_box(None)
             p.set_clip_path(None)
             handle_list.append(p)
         elif isinstance(handle, CircleCollection):
             ydata = height*self._scatteryoffsets
             size_max, size_min = max(handle.get_sizes()),\
                                  min(handle.get_sizes())
             if self.scatterpoints < 4:
                 sizes = [.5*(size_max+size_min), size_max,
                          size_min]
             else:
                 sizes = (size_max-size_min)*np.linspace(0,1,self.scatterpoints)+size_min
             p = type(handle)(sizes,
                              offsets=zip(xdata_marker,ydata),
                              transOffset=self.get_transform(),
                              )
             p.update_from(handle)
             p.set_figure(self.figure)
             p.set_clip_box(None)
             p.set_clip_path(None)
             handle_list.append(p)
         else:
             handle_type = type(handle)
             warnings.warn("Legend does not support %s\nUse proxy artist instead.\n\nhttp://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist\n" % (str(handle_type),))
             handle_list.append(None)
         handle = handle_list[-1]
         if handle is not None: # handle is None is the artist is not supproted
             textbox = TextArea(lab, textprops=label_prop,
                                multilinebaseline=True, minimumdescent=True)
             text_list.append(textbox._text)
             labelboxes.append(textbox)
             handlebox = DrawingArea(width=self.handlelength*fontsize,
                                     height=height,
                                     xdescent=0., ydescent=descent)
             handlebox.add_artist(handle)
             if isinstance(handle, RegularPolyCollection) or \
                    isinstance(handle, CircleCollection):
                 handle._transOffset = handlebox.get_transform()
                 handle.set_transform(None)
             if hasattr(handle, "_legmarker"):
                 handlebox.add_artist(handle._legmarker)
             handleboxes.append(handlebox)
     if len(handleboxes) > 0:
         ncol = min(self._ncol, len(handleboxes))
         nrows, num_largecol = divmod(len(handleboxes), ncol)
         num_smallcol = ncol-num_largecol
         largecol = safezip(range(0, num_largecol*(nrows+1), (nrows+1)),
                            [nrows+1] * num_largecol)
         smallcol = safezip(range(num_largecol*(nrows+1), len(handleboxes), nrows),
                            [nrows] * num_smallcol)
     else:
         largecol, smallcol = [], []
     handle_label = safezip(handleboxes, labelboxes)
     columnbox = []
     for i0, di in largecol+smallcol:
         itemBoxes = [HPacker(pad=0,
                              sep=self.handletextpad*fontsize,
                              children=[h, t], align="baseline")
                      for h, t in handle_label[i0:i0+di]]
         itemBoxes[-1].get_children()[1].set_minimumdescent(False)
         columnbox.append(VPacker(pad=0,
                                     sep=self.labelspacing*fontsize,
                                     align="baseline",
                                     children=itemBoxes))
     if self._mode == "expand":
         mode = "expand"
     else:
         mode = "fixed"
     sep = self.columnspacing*fontsize
     self._legend_handle_box = HPacker(pad=0,
                                       sep=sep, align="baseline",
                                       mode=mode,
                                       children=columnbox)
     self._legend_title_box = TextArea("")
     self._legend_box = VPacker(pad=self.borderpad*fontsize,
                                sep=self.labelspacing*fontsize,
                                align="center",
                                children=[self._legend_title_box,
                                          self._legend_handle_box])
     self._legend_box.set_figure(self.figure)
     self.texts = text_list
     self.legendHandles = handle_list
Ejemplo n.º 3
0
    def _init_legend_box(self, handles, labels):
        """
        Initiallize the legend_box. The legend_box is an instance of
        the OffsetBox, which is packed with legend handles and
        texts. Once packed, their location is calculated during the
        drawing time.
        """

        fontsize = self.fontsize

        # legend_box is a HPacker, horizontally packed with
        # columns. Each column is a VPacker, vertically packed with
        # legend items. Each legend item is HPacker packed with
        # legend handleBox and labelBox. handleBox is an instance of
        # offsetbox.DrawingArea which contains legend handle. labelBox
        # is an instance of offsetbox.TextArea which contains legend
        # text.

        text_list = []  # the list of text instances
        handle_list = []  # the list of text instances

        label_prop = dict(
            verticalalignment='baseline',
            horizontalalignment='left',
            fontproperties=self.prop,
        )

        labelboxes = []

        for l in labels:
            textbox = TextArea(l,
                               textprops=label_prop,
                               multilinebaseline=True,
                               minimumdescent=True)
            text_list.append(textbox._text)
            labelboxes.append(textbox)

        handleboxes = []

        # The approximate height and descent of text. These values are
        # only used for plotting the legend handle.
        height = self._approx_text_height() * 0.7
        descent = 0.

        # each handle needs to be drawn inside a box of (x, y, w, h) =
        # (0, -descent, width, height).  And their corrdinates should
        # be given in the display coordinates.

        # NOTE : the coordinates will be updated again in
        # _update_legend_box() method.

        # The transformation of each handle will be automatically set
        # to self.get_trasnform(). If the artist does not uses its
        # default trasnform (eg, Collections), you need to
        # manually set their transform to the self.get_transform().

        for handle in handles:
            if isinstance(handle, RegularPolyCollection):
                npoints = self.scatterpoints
            else:
                npoints = self.numpoints
            if npoints > 1:
                # we put some pad here to compensate the size of the
                # marker
                xdata = np.linspace(0.3 * fontsize,
                                    (self.handlelength - 0.3) * fontsize,
                                    npoints)
                xdata_marker = xdata
            elif npoints == 1:
                xdata = np.linspace(0, self.handlelength * fontsize, 2)
                xdata_marker = [0.5 * self.handlelength * fontsize]

            if isinstance(handle, Line2D):
                ydata = ((height - descent) / 2.) * np.ones(xdata.shape, float)
                legline = Line2D(xdata, ydata)

                legline.update_from(handle)
                self._set_artist_props(legline)  # after update
                legline.set_clip_box(None)
                legline.set_clip_path(None)
                legline.set_drawstyle('default')
                legline.set_marker('None')

                handle_list.append(legline)

                legline_marker = Line2D(xdata_marker,
                                        ydata[:len(xdata_marker)])
                legline_marker.update_from(handle)
                self._set_artist_props(legline_marker)
                legline_marker.set_clip_box(None)
                legline_marker.set_clip_path(None)
                legline_marker.set_linestyle('None')
                # we don't want to add this to the return list because
                # the texts and handles are assumed to be in one-to-one
                # correpondence.
                legline._legmarker = legline_marker

            elif isinstance(handle, Patch):
                p = Rectangle(
                    xy=(0., 0.),
                    width=self.handlelength * fontsize,
                    height=(height - descent),
                )
                p.update_from(handle)
                self._set_artist_props(p)
                p.set_clip_box(None)
                p.set_clip_path(None)
                handle_list.append(p)
            elif isinstance(handle, LineCollection):
                ydata = ((height - descent) / 2.) * np.ones(xdata.shape, float)
                legline = Line2D(xdata, ydata)
                self._set_artist_props(legline)
                legline.set_clip_box(None)
                legline.set_clip_path(None)
                lw = handle.get_linewidth()[0]
                dashes = handle.get_dashes()[0]
                color = handle.get_colors()[0]
                legline.set_color(color)
                legline.set_linewidth(lw)
                legline.set_dashes(dashes)
                handle_list.append(legline)

            elif isinstance(handle, RegularPolyCollection):

                #ydata = self._scatteryoffsets
                ydata = height * self._scatteryoffsets

                size_max, size_min = max(handle.get_sizes()),\
                                     min(handle.get_sizes())
                # we may need to scale these sizes by "markerscale"
                # attribute. But other handle types does not seem
                # to care about this attribute and it is currently ignored.
                if self.scatterpoints < 4:
                    sizes = [.5 * (size_max + size_min), size_max, size_min]
                else:
                    sizes = (size_max - size_min) * np.linspace(
                        0, 1, self.scatterpoints) + size_min

                p = type(handle)(
                    handle.get_numsides(),
                    rotation=handle.get_rotation(),
                    sizes=sizes,
                    offsets=zip(xdata_marker, ydata),
                    transOffset=self.get_transform(),
                )

                p.update_from(handle)
                p.set_figure(self.figure)
                p.set_clip_box(None)
                p.set_clip_path(None)
                handle_list.append(p)

            else:
                handle_list.append(None)

            handlebox = DrawingArea(width=self.handlelength * fontsize,
                                    height=height,
                                    xdescent=0.,
                                    ydescent=descent)

            handle = handle_list[-1]
            handlebox.add_artist(handle)
            if hasattr(handle, "_legmarker"):
                handlebox.add_artist(handle._legmarker)
            handleboxes.append(handlebox)

        # We calculate number of lows in each column. The first
        # (num_largecol) columns will have (nrows+1) rows, and remaing
        # (num_smallcol) columns will have (nrows) rows.
        nrows, num_largecol = divmod(len(handleboxes), self._ncol)
        num_smallcol = self._ncol - num_largecol

        # starting index of each column and number of rows in it.
        largecol = safezip(range(0, num_largecol * (nrows + 1), (nrows + 1)),
                           [nrows + 1] * num_largecol)
        smallcol = safezip(
            range(num_largecol * (nrows + 1), len(handleboxes), nrows),
            [nrows] * num_smallcol)

        handle_label = safezip(handleboxes, labelboxes)
        columnbox = []
        for i0, di in largecol + smallcol:
            # pack handleBox and labelBox into itemBox
            itemBoxes = [
                HPacker(pad=0,
                        sep=self.handletextpad * fontsize,
                        children=[h, t],
                        align="baseline") for h, t in handle_label[i0:i0 + di]
            ]
            # minimumdescent=False for the text of the last row of the column
            itemBoxes[-1].get_children()[1].set_minimumdescent(False)

            # pack columnBox
            columnbox.append(
                VPacker(pad=0,
                        sep=self.labelspacing * fontsize,
                        align="baseline",
                        children=itemBoxes))

        if self._mode == "expand":
            mode = "expand"
        else:
            mode = "fixed"

        sep = self.columnspacing * fontsize

        self._legend_box = HPacker(pad=self.borderpad * fontsize,
                                   sep=sep,
                                   align="baseline",
                                   mode=mode,
                                   children=columnbox)

        self._legend_box.set_figure(self.figure)

        self.texts = text_list
        self.legendHandles = handle_list
Ejemplo n.º 4
0
    def _init_legend_box(self, handles, labels):
        """
        Initiallize the legend_box. The legend_box is an instance of
        the OffsetBox, which is packed with legend handles and
        texts. Once packed, their location is calculated during the
        drawing time.
        """

        fontsize = self.fontsize

        # legend_box is a HPacker, horizontally packed with
        # columns. Each column is a VPacker, vertically packed with
        # legend items. Each legend item is HPacker packed with
        # legend handleBox and labelBox. handleBox is an instance of
        # offsetbox.DrawingArea which contains legend handle. labelBox
        # is an instance of offsetbox.TextArea which contains legend
        # text.


        text_list = []  # the list of text instances
        handle_list = []  # the list of text instances

        label_prop = dict(verticalalignment='baseline',
                          horizontalalignment='left',
                          fontproperties=self.prop,
                          )

        labelboxes = []

        for l in labels:
            textbox = TextArea(l, textprops=label_prop,
                               multilinebaseline=True, minimumdescent=True)
            text_list.append(textbox._text)
            labelboxes.append(textbox)

        handleboxes = []


        # The approximate height and descent of text. These values are
        # only used for plotting the legend handle.
        height = self._approx_text_height() * 0.7
        descent = 0.

        # each handle needs to be drawn inside a box of (x, y, w, h) =
        # (0, -descent, width, height).  And their corrdinates should
        # be given in the display coordinates.

        # NOTE : the coordinates will be updated again in
        # _update_legend_box() method.

        # The transformation of each handle will be automatically set
        # to self.get_trasnform(). If the artist does not uses its
        # default trasnform (eg, Collections), you need to
        # manually set their transform to the self.get_transform().

        for handle in handles:
            if isinstance(handle, RegularPolyCollection):
                npoints = self.scatterpoints
            else:
                npoints = self.numpoints
            if npoints > 1:
                # we put some pad here to compensate the size of the
                # marker
                xdata = np.linspace(0.3*fontsize,
                                    (self.handlelength-0.3)*fontsize,
                                    npoints)
                xdata_marker = xdata
            elif npoints == 1:
                xdata = np.linspace(0, self.handlelength*fontsize, 2)
                xdata_marker = [0.5*self.handlelength*fontsize]

            if isinstance(handle, Line2D):
                ydata = ((height-descent)/2.)*np.ones(xdata.shape, float)
                legline = Line2D(xdata, ydata)

                legline.update_from(handle)
                self._set_artist_props(legline) # after update
                legline.set_clip_box(None)
                legline.set_clip_path(None)
                legline.set_drawstyle('default')
                legline.set_marker('None')

                handle_list.append(legline)

                legline_marker = Line2D(xdata_marker, ydata[:len(xdata_marker)])
                legline_marker.update_from(handle)
                self._set_artist_props(legline_marker)
                legline_marker.set_clip_box(None)
                legline_marker.set_clip_path(None)
                legline_marker.set_linestyle('None')
                # we don't want to add this to the return list because
                # the texts and handles are assumed to be in one-to-one
                # correpondence.
                legline._legmarker = legline_marker

            elif isinstance(handle, Patch):
                p = Rectangle(xy=(0., 0.),
                              width = self.handlelength*fontsize,
                              height=(height-descent),
                              )
                p.update_from(handle)
                self._set_artist_props(p)
                p.set_clip_box(None)
                p.set_clip_path(None)
                handle_list.append(p)
            elif isinstance(handle, LineCollection):
                ydata = ((height-descent)/2.)*np.ones(xdata.shape, float)
                legline = Line2D(xdata, ydata)
                self._set_artist_props(legline)
                legline.set_clip_box(None)
                legline.set_clip_path(None)
                lw = handle.get_linewidth()[0]
                dashes = handle.get_dashes()[0]
                color = handle.get_colors()[0]
                legline.set_color(color)
                legline.set_linewidth(lw)
                legline.set_dashes(dashes)
                handle_list.append(legline)

            elif isinstance(handle, RegularPolyCollection):

                #ydata = self._scatteryoffsets
                ydata = height*self._scatteryoffsets

                size_max, size_min = max(handle.get_sizes()),\
                                     min(handle.get_sizes())
                # we may need to scale these sizes by "markerscale"
                # attribute. But other handle types does not seem
                # to care about this attribute and it is currently ignored.
                if self.scatterpoints < 4:
                    sizes = [.5*(size_max+size_min), size_max,
                             size_min]
                else:
                    sizes = (size_max-size_min)*np.linspace(0,1,self.scatterpoints)+size_min

                p = type(handle)(handle.get_numsides(),
                                 rotation=handle.get_rotation(),
                                 sizes=sizes,
                                 offsets=zip(xdata_marker,ydata),
                                 transOffset=self.get_transform(),
                                 )

                p.update_from(handle)
                p.set_figure(self.figure)
                p.set_clip_box(None)
                p.set_clip_path(None)
                handle_list.append(p)

            else:
                handle_list.append(None)

            handlebox = DrawingArea(width=self.handlelength*fontsize,
                                    height=height,
                                    xdescent=0., ydescent=descent)

            handle = handle_list[-1]
            handlebox.add_artist(handle)
            if hasattr(handle, "_legmarker"):
                handlebox.add_artist(handle._legmarker)
            handleboxes.append(handlebox)


        # We calculate number of lows in each column. The first
        # (num_largecol) columns will have (nrows+1) rows, and remaing
        # (num_smallcol) columns will have (nrows) rows.
        nrows, num_largecol = divmod(len(handleboxes), self._ncol)
        num_smallcol = self._ncol-num_largecol

        # starting index of each column and number of rows in it.
        largecol = safezip(range(0, num_largecol*(nrows+1), (nrows+1)),
                           [nrows+1] * num_largecol)
        smallcol = safezip(range(num_largecol*(nrows+1), len(handleboxes), nrows),
                           [nrows] * num_smallcol)

        handle_label = safezip(handleboxes, labelboxes)
        columnbox = []
        for i0, di in largecol+smallcol:
            # pack handleBox and labelBox into itemBox
            itemBoxes = [HPacker(pad=0,
                                 sep=self.handletextpad*fontsize,
                                 children=[h, t], align="baseline")
                         for h, t in handle_label[i0:i0+di]]
            # minimumdescent=False for the text of the last row of the column
            itemBoxes[-1].get_children()[1].set_minimumdescent(False)

            # pack columnBox
            columnbox.append(VPacker(pad=0,
                                        sep=self.labelspacing*fontsize,
                                        align="baseline",
                                        children=itemBoxes))

        if self._mode == "expand":
            mode = "expand"
        else:
            mode = "fixed"

        sep = self.columnspacing*fontsize

        self._legend_box = HPacker(pad=self.borderpad*fontsize,
                                      sep=sep, align="baseline",
                                      mode=mode,
                                      children=columnbox)

        self._legend_box.set_figure(self.figure)

        self.texts = text_list
        self.legendHandles = handle_list
Ejemplo n.º 5
0
def plotChromosomeIdeogram(ideogram_bed_filename,
                           chromosome,
                           highlighted_region=None,
                           color_map=giemsa_color_map,
                           alignment="vertical",
                           ax=None):
    ax = ax if ax is not None else plt.gca()

    ideogram_bed_file = open(ideogram_bed_filename, "r")

    # load fragments into list
    fragment_list_parm = []
    fragment_list_qarm = []
    for line in ideogram_bed_file:
        if (line[0] == "#"):
            continue

        split_line = line.rstrip().split("\t")

        if (not (split_line[0] == chromosome)):
            continue

        chrom = split_line[0]
        start = int(split_line[1])
        end = int(split_line[2])
        fragment_id = split_line[3]
        giemsa_stain = split_line[4]

        if (fragment_id[0] == "p"):
            fragment_list_parm += [[
                chrom, start, end, fragment_id, giemsa_stain
            ]]
        elif (fragment_id[0] == "q"):
            fragment_list_qarm += [[
                chrom, start, end, fragment_id, giemsa_stain
            ]]

    ideogram_bed_file.close()

    p_start = fragment_list_parm[0][1] if not len(
        fragment_list_parm) == 0 else None
    p_end = fragment_list_parm[-1][2] if not len(
        fragment_list_parm) == 0 else None
    q_start = fragment_list_qarm[0][1] if not len(
        fragment_list_qarm) == 0 else None
    q_end = fragment_list_qarm[-1][2] if not len(
        fragment_list_qarm) == 0 else None

    cap_ext = 2000000

    clip_path_patch_parm = None
    if (not p_start is None):
        # Create Clip path
        if (alignment == "vertical"):
            vertices = [[0, -1 * cap_ext], [0, -1 * p_end + cap_ext],
                        [
                            .5,
                            bezierMidPoint(-1. * p_end, -1 * p_end + cap_ext,
                                           -1 * p_end + cap_ext, 0.5)
                        ], [1, -1 * p_end + cap_ext], [1, -1. * cap_ext],
                        [
                            .5,
                            bezierMidPoint(0, -1. * cap_ext, -1. * cap_ext, .5)
                        ], [0, -1 * cap_ext]]
        else:
            vertices = [[1 * cap_ext, 0], [1 * p_end - cap_ext, 0],
                        [
                            bezierMidPoint(1. * p_end, 1 * p_end - cap_ext,
                                           1 * p_end - cap_ext, 0.5), .5
                        ], [1 * p_end - cap_ext, 1], [1. * cap_ext, 1],
                        [
                            bezierMidPoint(0, 1. * cap_ext, 1. * cap_ext, .5),
                            .5
                        ], [1 * cap_ext, 0]]

        codes = [
            Path.MOVETO, Path.LINETO, Path.CURVE3, Path.CURVE3, Path.LINETO,
            Path.CURVE3, Path.CURVE3
        ]
        clip_path = Path(vertices, codes=codes)
        clip_path_patch_parm = patches.PathPatch(clip_path,
                                                 facecolor="none",
                                                 linewidth=.5,
                                                 capstyle="round")
        ax.add_patch(clip_path_patch_parm)

        rect = None
        if (alignment == "vertical"):
            rect = Rectangle((0, -1 * p_end), 1, p_end, facecolor="none")
        else:
            rect = Rectangle((1 * p_end, 0), p_end, 1, facecolor="none")
        rect.set_clip_path(clip_path_patch_parm)
        ax.add_patch(rect)

        # Plot fragments
        plotFragments(fragment_list_parm,
                      clip_path_patch_parm,
                      color_map,
                      alignment=alignment,
                      ax=ax)
    clip_path_path_qarm = None
    if (not q_start is None):
        if (alignment == "vertical"):
            vertices = [[0, -1 * q_start - cap_ext], [0, -1 * q_end + cap_ext],
                        [
                            .5,
                            bezierMidPoint(-1 * q_end, -1 * q_end + cap_ext,
                                           -1 * q_end + cap_ext, .5)
                        ], [1, -1 * q_end + cap_ext],
                        [1, -1 * q_start - cap_ext],
                        [
                            .5,
                            bezierMidPoint(-1 * q_start,
                                           -1 * q_start - cap_ext,
                                           -1 * q_start - cap_ext, .5)
                        ], [0, -1 * q_start - cap_ext]]
        else:
            vertices = [[1 * q_start + cap_ext, 0], [1 * q_end - cap_ext, 0],
                        [
                            bezierMidPoint(1 * q_end, 1 * q_end - cap_ext,
                                           1 * q_end - cap_ext, .5), .5
                        ], [1 * q_end - cap_ext, 1],
                        [1 * q_start + cap_ext, 1],
                        [
                            bezierMidPoint(1 * q_start, 1 * q_start + cap_ext,
                                           1 * q_start + cap_ext, .5), .5
                        ], [1 * q_start + cap_ext, 0]]

        codes = [
            Path.MOVETO, Path.LINETO, Path.CURVE3, Path.CURVE3, Path.LINETO,
            Path.CURVE3, Path.CURVE3
        ]
        clip_path = Path(vertices, codes=codes)
        clip_path_patch_qarm = patches.PathPatch(clip_path,
                                                 facecolor="none",
                                                 linewidth=.5,
                                                 capstyle="round")
        ax.add_patch(clip_path_patch_qarm)

        rect = None
        if (alignment == "vertical"):
            rect = Rectangle((1, -1 * q_end),
                             1, (q_end - q_start),
                             facecolor="none")
        else:
            rect = Rectangle((1 * q_end, 1), (q_end - q_start),
                             1,
                             facecolor="none")
        rect.set_clip_path(clip_path_patch_qarm)
        ax.add_patch(rect)

        # Plot fragments
        plotFragments(fragment_list_qarm,
                      clip_path_patch_qarm,
                      color_map,
                      alignment=alignment,
                      ax=ax)

    ax.axis('off')

    if (alignment == "vertical"):
        plt.xlim([-.2, 1.2])
        plt.ylim([-1 * q_end, 0])
    else:
        plt.ylim([-.2, 1.2])
        plt.xlim([0, 1 * q_end])

    if (not highlighted_region is None):
        if (alignment == "horizontal"):
            rect = Rectangle(
                (highlighted_region[1], 0),
                width=highlighted_region[2] - highlighted_region[1],
                height=1,
                capstyle="butt",
                linewidth=1,
                edgecolor="r",
                facecolor="none")
            ax.add_patch(rect)
Ejemplo n.º 6
0
                 facecolor='w',
                 zorder=0.5)

# create MNE clipping mask
mne_path = TextPath((0, 0), 'MNE')
dims = mne_path.vertices.max(0) - mne_path.vertices.min(0)
vert = mne_path.vertices - dims / 2.
mult = (plot_dims / dims).min()
mult = [mult, -mult]  # y axis is inverted (origin at top left)
offset = plot_dims / 2. - center_fudge
mne_clip = Path(offset + vert * mult, mne_path.codes)
ax.add_patch(PathPatch(mne_clip, color='w', zorder=0, linewidth=0))
# apply clipping mask to field gradient and lines
im.set_clip_path(mne_clip, transform=im.get_transform())
ax.add_patch(rect)
rect.set_clip_path(mne_clip, transform=im.get_transform())
for coll in cs.collections:
    coll.set_clip_path(mne_clip, transform=im.get_transform())
# get final position of clipping mask
mne_corners = mne_clip.get_extents().corners()

# add tagline
rcParams.update({'font.sans-serif': ['Cooper Hewitt'], 'font.weight': '300'})
tag_path = TextPath((0, 0), 'MEG + EEG  ANALYSIS & VISUALIZATION')
dims = tag_path.vertices.max(0) - tag_path.vertices.min(0)
vert = tag_path.vertices - dims / 2.
mult = tagline_scale_fudge * (plot_dims / dims).min()
mult = [mult, -mult]  # y axis is inverted
offset = mne_corners[-1] - np.array(
    [mne_clip.get_extents().size[0] / 2., -dims[1]]) - tagline_offset_fudge
tag_clip = Path(offset + vert * mult, tag_path.codes)