Пример #1
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
Пример #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

        # 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 = []
        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.

        # 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, lab in zip(handles, labels):
            if isinstance(handle, RegularPolyCollection) or \
                   isinstance(handle, CircleCollection):
                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')
                if self.markerscale != 1:
                    newsz = legline_marker.get_markersize() * self.markerscale
                    legline_marker.set_markersize(newsz)
                # 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)
                if dashes[0] is not None:  # dashed line
                    legline.set_dashes(dashes[1])
                handle_list.append(legline)

            elif isinstance(handle, RegularPolyCollection):

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

                size_max, size_min = max(handle.get_sizes())*self.markerscale**2,\
                                     min(handle.get_sizes())*self.markerscale**2
                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())*self.markerscale**2,\
                                     min(handle.get_sizes())*self.markerscale**2
                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)

                # special case for collection instances
                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:

            # 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.
            ncol = min(self._ncol, len(handleboxes))
            nrows, num_largecol = divmod(len(handleboxes), ncol)
            num_smallcol = 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)
        else:
            largecol, 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_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
Пример #3
0
    def y_tick_label(self, y, size, offset=7, ax=None):
        """
        uses the icon as a ticklabel at location x

        Args:
            y (float)
                the position of the tick
            size (float)
                scaling the size of the icon
            offset (integer)
                how far the icon should be from the axis in points
            ax (matplotlib axis)
                the axis to put the label on

        """
        if ax is None:
            ax = plt.gca()
        if self.final_image is not None:
            imagebox = OffsetImage(self.final_image, zoom=size)
            ab = AnnotationBbox(imagebox, (0, y),
                                xybox=(-offset, 0),
                                xycoords=('axes fraction', 'data'),
                                box_alignment=(1, .5),
                                boxcoords='offset points',
                                bboxprops={
                                    'edgecolor': 'none',
                                    'facecolor': 'none'
                                },
                                arrowprops={
                                    'arrowstyle': '-',
                                    'shrinkA': 0,
                                    'shrinkB': 1
                                },
                                pad=0.1)
            ax.add_artist(ab)
            zorder = ab.zorder
        else:
            zorder = 0
        if self.marker:
            if self.final_image is not None:
                markersize = max(self.final_image.size)
            else:
                markersize = 50
            markersize = markersize * size
            d = DrawingArea(markersize, markersize)
            if self.marker_front:
                zorder_marker = zorder + 0.1
            else:
                zorder_marker = zorder - 0.1
            d.set_zorder(zorder_marker)
            d.set_alpha(0)
            if self.marker_front:
                d.add_artist(
                    plt.Line2D([markersize / 2], [markersize / 2],
                               marker=self.marker,
                               markeredgecolor=self.col,
                               markerfacecolor=(0, 0, 0, 0),
                               markersize=markersize,
                               markeredgewidth=self.markeredgewidth,
                               transform=d.get_transform(),
                               zorder=zorder_marker))
            else:
                d.add_artist(
                    plt.Line2D([markersize / 2], [markersize / 2],
                               marker=self.marker,
                               markeredgecolor=self.col,
                               markerfacecolor=self.col,
                               markersize=markersize,
                               markeredgewidth=self.markeredgewidth,
                               transform=d.get_transform(),
                               zorder=zorder_marker))
            ab_marker = AnnotationBbox(d, (0, y),
                                       xybox=(-offset, 0),
                                       xycoords=('axes fraction', 'data'),
                                       box_alignment=(1, 0.5),
                                       boxcoords='offset points',
                                       bboxprops={
                                           'edgecolor': 'none',
                                           'facecolor': 'none'
                                       },
                                       arrowprops={
                                           'arrowstyle': '-',
                                           'shrinkA': 0,
                                           'shrinkB': 1
                                       },
                                       pad=0.1)
            ab_marker.set_zorder(zorder_marker)
            ab_marker.set_alpha(0)
            ax.add_artist(ab_marker)
        if self.string is not None:
            ax.annotate(self.string, (0, y),
                        xytext=(-offset, 0),
                        xycoords=('axes fraction', 'data'),
                        textcoords='offset points',
                        horizontalalignment='right',
                        verticalalignment='center',
                        arrowprops={
                            'arrowstyle': '-',
                            'shrinkA': 0,
                            'shrinkB': 1
                        },
                        zorder=zorder + 1,
                        fontsize=self.fontsize,
                        fontname=self.fontname,
                        color=self.fontcolor)
Пример #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 = []
        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.

        # 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, lab in zip(handles, labels):
            if isinstance(handle, RegularPolyCollection) or \
                   isinstance(handle, CircleCollection):
                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')
                if self.markerscale !=1:
                    newsz = legline_marker.get_markersize()*self.markerscale
                    legline_marker.set_markersize(newsz)
                # 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)
                if dashes[0] is not None: # dashed line
                    legline.set_dashes(dashes[1])
                handle_list.append(legline)

            elif isinstance(handle, RegularPolyCollection):

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

                size_max, size_min = max(handle.get_sizes())*self.markerscale**2,\
                                     min(handle.get_sizes())*self.markerscale**2
                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())*self.markerscale**2,\
                                     min(handle.get_sizes())*self.markerscale**2
                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)

                # special case for collection instances
                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:

            # 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.
            ncol = min(self._ncol, len(handleboxes))
            nrows, num_largecol = divmod(len(handleboxes), ncol)
            num_smallcol = 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)
        else:
            largecol, 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_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
Пример #5
0
Файл: icon.py Проект: caiw/pyrsa
    def _tick_label(
        self,
        x,
        y,
        size,
        ax=None,
        linewidth=None,
        xybox=None,
        xycoords=None,
        box_alignment=None,
        horizontalalignment=None,
        verticalalignment=None,
        rotation=None,
    ):
        """
        uses the icon as a ticklabel at location x

        Args:
            x (float)
                the horizontal position of the tick
            y (float)
                the vertical position of the tick
            size (float)
                scaling the size of the icon
            ax (matplotlib axis)
                the axis to put the label on

        """
        ret_val = {}
        if ax is None:
            ax = plt.gca()
        tickline_color = self.color
        # np.any chokes on str input so need to test for this first
        if not (isinstance(tickline_color, str) or np.any(tickline_color)):
            tickline_color = [0.8, 0.8, 0.8]
        if self.final_image is not None:
            imagebox = OffsetImage(self.final_image, zoom=size, dpi_cor=True)
            ret_val['image'] = AnnotationBbox(
                imagebox,
                (x, y),
                xybox=xybox,
                xycoords=xycoords,
                box_alignment=box_alignment,
                boxcoords="offset points",
                bboxprops={
                    "edgecolor": "none",
                    "facecolor": "none"
                },
                arrowprops={
                    "linewidth": linewidth,
                    "color": tickline_color,
                    "arrowstyle": "-",
                    "shrinkA": 0,
                    "shrinkB": 1,
                },
                pad=0.0,
                annotation_clip=False,
            )
            zorder = ret_val['image'].zorder
            ax.add_artist(ret_val['image'])
        else:
            zorder = 0
        if self.marker:
            if self.final_image is not None:
                markersize = max(self.final_image.size)
            else:
                markersize = 50
            markersize = markersize * size
            d = DrawingArea(markersize, markersize)
            if self.marker_front:
                zorder_marker = zorder + 0.1
            else:
                zorder_marker = zorder - 0.1
            d.set_zorder(zorder_marker)
            d.set_alpha(0)
            if self.marker_front:
                d.add_artist(
                    plt.Line2D(
                        [markersize / 2],
                        [markersize / 2],
                        marker=self.marker,
                        markeredgecolor=self.color,
                        markerfacecolor=(0, 0, 0, 0),
                        markersize=markersize,
                        markeredgewidth=self.markeredgewidth,
                        transform=d.get_transform(),
                        zorder=zorder_marker,
                    ))
            else:
                d.add_artist(
                    plt.Line2D(
                        [markersize / 2],
                        [markersize / 2],
                        marker=self.marker,
                        markeredgecolor=self.color,
                        markerfacecolor=self.color,
                        markersize=markersize,
                        markeredgewidth=self.markeredgewidth,
                        transform=d.get_transform(),
                        zorder=zorder_marker,
                    ))
            ret_val['marker'] = AnnotationBbox(
                d,
                (x, y),
                xybox=xybox,
                xycoords=xycoords,
                box_alignment=box_alignment,
                boxcoords="offset points",
                bboxprops={
                    "edgecolor": "none",
                    "facecolor": "none"
                },
                arrowprops={
                    "linewidth": linewidth,
                    "color": tickline_color,
                    "arrowstyle": "-",
                    "shrinkA": 0,
                    "shrinkB": 1,
                },
                pad=0.0,
                annotation_clip=False,
            )
            ret_val['marker'].set_zorder(zorder_marker)
            ret_val['marker'].set_alpha(0)
            ax.add_artist(ret_val['marker'])
        if self.string is not None:
            ret_val['string'] = ax.annotate(
                self.string,
                (x, y),
                xytext=xybox,
                xycoords=xycoords,
                textcoords="offset points",
                horizontalalignment=horizontalalignment,
                verticalalignment=verticalalignment,
                arrowprops={
                    "linewidth": linewidth,
                    "color": tickline_color,
                    "arrowstyle": "-",
                    "shrinkA": 0,
                    "shrinkB": 1,
                },
                zorder=zorder + 0.2,
                fontsize=self.font_size,
                fontname=self.font_name,
                color=self.font_color,
                rotation=rotation,
            )
        return ret_val