Ejemplo n.º 1
0
                lm_pos_pred = output['lm_pos_output'][
                    0, :, :].cpu().detach().numpy() * hm_size

                category_gt = sample['category_label'][0]
                category_gt_name = const.CATEGORY_NAMES[int(category_gt)]
                category_type = sample['category_type'][0].cpu().numpy()

                # get category prediction if it is in network output and create text box
                if 'category_loss' in loss:
                    _, category_pred = output['category_output'][0].topk(
                        1, 0, True, True)
                    category_pred_name = const.CATEGORY_NAMES[int(
                        category_pred)]

                    if (category_pred == category_gt):
                        text_pred = TextArea('pred: ' + category_pred_name,
                                             textprops=dict(color='green'))
                    else:
                        text_pred = TextArea('pred: ' + category_pred_name,
                                             textprops=dict(color='red'))
                else:
                    text_pred = TextArea('pred: ----',
                                         textprops=dict(color='red'))
                text_gt = TextArea('gt: ' + category_gt_name,
                                   textprops=dict(color='blue'))
                text_box = HPacker(children=[text_gt, text_pred],
                                   align='left',
                                   pad=5,
                                   sep=5)

                # prepare input image
                image = unnormalize_image(sample['image'][0, :, :, :].cpu())
Ejemplo n.º 2
0
    def __init__(self,
                 transform,
                 sizex=0,
                 sizey=0,
                 labelx=None,
                 labely=None,
                 loc=4,
                 pad=0.1,
                 borderpad=0.1,
                 sep=2,
                 prop=None,
                 label_fontsize=label_fontsize,
                 color='k',
                 **kwargs):
        """
        Draw a horizontal and/or vertical  bar with the size in data coordinate
        of the give axes. A label will be drawn underneath (center-aligned).
        - transform : the coordinate frame (typically axes.transData)
        - sizex,sizey : width of x,y bar, in data units. 0 to omit
        - labelx,labely : labels for x,y bars; None to omit
        - loc : position in containing axes
        - pad, borderpad : padding, in fraction of the legend font size (or prop)
        - sep : separation between labels and bars in points.
        - **kwargs : additional arguments passed to base class constructor
        """
        from matplotlib.patches import Rectangle
        from matplotlib.offsetbox import AuxTransformBox, VPacker, HPacker, TextArea, DrawingArea
        bars = AuxTransformBox(transform)
        if sizex:
            bars.add_artist(
                Rectangle((0, 0),
                          sizex,
                          0,
                          fc="none",
                          linewidth=axes_linewidth,
                          color=color))
        if sizey:
            bars.add_artist(
                Rectangle((0, 0),
                          0,
                          sizey,
                          fc="none",
                          linewidth=axes_linewidth,
                          color=color))

        if sizex and labelx:
            textareax = TextArea(labelx,
                                 minimumdescent=False,
                                 textprops=dict(size=label_fontsize,
                                                color=color))
            bars = VPacker(children=[bars, textareax],
                           align="center",
                           pad=0,
                           sep=sep)
        if sizey and labely:
            ## VPack a padstr below the rotated labely, else label y goes below the scale bar
            ## Just adding spaces before labely doesn't work!
            padstr = '\n ' * len(labely)
            textareafiller = TextArea(padstr,
                                      textprops=dict(size=label_fontsize /
                                                     3.0))
            textareay = TextArea(labely,
                                 textprops=dict(size=label_fontsize,
                                                rotation='vertical',
                                                color=color))
            ## filler / pad string VPack-ed below labely
            textareayoffset = VPacker(children=[textareay, textareafiller],
                                      align="center",
                                      pad=0,
                                      sep=sep)
            ## now HPack this padded labely to the bars
            bars = HPacker(children=[textareayoffset, bars],
                           align="top",
                           pad=0,
                           sep=sep)

        AnchoredOffsetbox.__init__(self,
                                   loc,
                                   pad=pad,
                                   borderpad=borderpad,
                                   child=bars,
                                   prop=prop,
                                   frameon=False,
                                   **kwargs)
Ejemplo n.º 3
0
                    cbar.cmap.set_under('w')
                    cbar.set_clim(0, cmap_range_max)

            print(var, cmap_range_min, cmap_range_max)  #, data_array

            if var == "comp":
                norm = mpl.colors.Normalize(vmin=cmap_range_min,
                                            vmax=cmap_range_max)
                im = ax.imshow(data_array, cmap=var_cmap, norm=norm)
                # im = ax.imshow(data_array, cmap=var_cmap)
                box1 = DrawingArea(50, 20, 0, 0)
                rt1 = plt.Rectangle((0, 5), 20, 13, fc="#1f78b4")
                rt2 = plt.Rectangle((25, 5), 20, 13, fc="#a6cee3")
                box1.add_artist(rt1)
                box1.add_artist(rt2)
                box2 = TextArea("Solid silicates",
                                textprops=dict(color="k", size=20))
                box = HPacker(children=[box1, box2],
                              align="center",
                              pad=0,
                              sep=5)
                anchored_box1 = AnchoredOffsetbox(
                    loc=2,
                    child=box,
                    pad=0.,
                    frameon=False,
                    bbox_to_anchor=(0.025, 0.98),
                    bbox_transform=ax.transAxes,
                    borderpad=0.,
                )
                ax.add_artist(anchored_box1)
Ejemplo n.º 4
0
    def draw(self, renderer, *args, **kwargs):
        if not self.get_visible():
            return
        if self.dx == 0:
            return

        # Get parameters
        from matplotlib import rcParams # late import

        def _get_value(attr, default):
            value = getattr(self, attr)
            if value is None:
                value = rcParams.get('scalebar.' + attr, default)
            return value

        length_fraction = _get_value('length_fraction', 0.2)
        height_fraction = _get_value('height_fraction', 0.01)
        location = _get_value('location', 'upper right')
        if isinstance(location,six.string_types):
            location = self._LOCATIONS[location]
        pad = _get_value('pad', 0.2)
        border_pad = _get_value('border_pad', 0.1)
        sep = _get_value('sep', 5)
        frameon = _get_value('frameon', True)
        color = _get_value('color', 'k')
        box_color = _get_value('box_color', 'w')
        box_alpha = _get_value('box_alpha', 1.0)
        scale_loc = _get_value('scale_loc', 'bottom')
        label_loc = _get_value('label_loc', 'top')
        font_properties = self.font_properties

        if font_properties is None:
            textprops = {'color': color}
        else:
            textprops = {'color': color, 'fontproperties': font_properties}

        ax = self.axes
        xlim, ylim = ax.get_xlim(), ax.get_ylim()
        label = self.label

        # Create label
        if label:
            txtlabel = TextArea(label, minimumdescent=False, textprops=textprops)
        else:
            txtlabel = None

        # Create sizebar
        length_px = abs(xlim[1] - xlim[0]) * length_fraction
        length_px, scale_label = self._calculate_length(length_px)

        size_vertical = abs(ylim[1] - ylim[0]) * height_fraction

        sizebar = AuxTransformBox(ax.transData)
        sizebar.add_artist(Rectangle((0, 0), length_px, size_vertical,
                                     fill=True, facecolor=color,
                                     edgecolor=color))

        txtscale = TextArea(scale_label, minimumdescent=False, textprops=textprops)

        if scale_loc in ['bottom', 'right']:
            children = [sizebar, txtscale]
        else:
            children = [txtscale, sizebar]
        if scale_loc in ['bottom', 'top']:
            Packer = VPacker
        else:
            Packer = HPacker
        boxsizebar = Packer(children=children, align='center', pad=0, sep=sep)

        # Create final offset box
        if txtlabel:
            if label_loc in ['bottom', 'right']:
                children = [boxsizebar, txtlabel]
            else:
                children = [txtlabel, boxsizebar]
            if label_loc in ['bottom', 'top']:
                Packer = VPacker
            else:
                Packer = HPacker
            child = Packer(children=children, align='center', pad=0, sep=sep)
        else:
            child = boxsizebar

        box = AnchoredOffsetbox(loc=location,
                                pad=pad,
                                borderpad=border_pad,
                                child=child,
                                frameon=frameon)

        box.axes = ax
        box.set_figure(self.get_figure())
        box.patch.set_color(box_color)
        box.patch.set_alpha(box_alpha)
        box.draw(renderer)
Ejemplo n.º 5
0
    def _init_legend_box(self, handles, labels, markerfirst=True):
        """
        Initialize 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
        handles_and_labels = []

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

        # The approximate height and descent of text. These values are
        # only used for plotting the legend handle.
        descent = 0.35 * self._approx_text_height() * (self.handleheight - 0.7)
        # 0.35 and 0.7 are just heuristic numbers and may need to be improved.
        height = self._approx_text_height() * self.handleheight - descent
        # each handle needs to be drawn inside a box of (x, y, w, h) =
        # (0, -descent, width, height).  And their coordinates should
        # be given in the display coordinates.

        # The transformation of each handle will be automatically set
        # to self.get_transform(). If the artist does not use its
        # default transform (e.g., Collections), you need to
        # manually set their transform to the self.get_transform().
        legend_handler_map = self.get_legend_handler_map()

        for orig_handle, lab in zip(handles, labels):
            handler = self.get_legend_handler(legend_handler_map, orig_handle)
            if handler is None:
                cbook._warn_external(
                    "Legend does not support {!r} instances.\nA proxy artist "
                    "may be used instead.\nSee: "
                    "http://matplotlib.org/users/legend_guide.html"
                    "#creating-artists-specifically-for-adding-to-the-legend-"
                    "aka-proxy-artists".format(orig_handle))
                # We don't have a handle for this artist, so we just defer
                # to None.
                handle_list.append(None)
            else:
                textbox = TextArea(lab,
                                   textprops=label_prop,
                                   multilinebaseline=True,
                                   minimumdescent=True)
                handlebox = DrawingArea(width=self.handlelength * fontsize,
                                        height=height,
                                        xdescent=0.,
                                        ydescent=descent)

                text_list.append(textbox._text)
                # Create the artist for the legend which represents the
                # original artist/handle.
                handle_list.append(
                    handler.legend_artist(self, orig_handle, fontsize,
                                          handlebox))
                handles_and_labels.append((handlebox, textbox))

        if handles_and_labels:
            # We calculate number of rows in each column. The first
            # (num_largecol) columns will have (nrows+1) rows, and remaining
            # (num_smallcol) columns will have (nrows) rows.
            ncol = min(self._ncol, len(handles_and_labels))
            nrows, num_largecol = divmod(len(handles_and_labels), ncol)
            num_smallcol = ncol - num_largecol
            # starting index of each column and number of rows in it.
            rows_per_col = [nrows + 1] * num_largecol + [nrows] * num_smallcol
            start_idxs = np.concatenate([[0], np.cumsum(rows_per_col)[:-1]])
            cols = zip(start_idxs, rows_per_col)
        else:
            cols = []

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

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

        mode = "expand" if self._mode == "expand" else "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.º 6
0
import numpy as np

from matplotlib.patches import Circle
from matplotlib.offsetbox import (TextArea, DrawingArea, OffsetImage,
                                  AnnotationBbox)
from matplotlib.cbook import get_sample_data


fig, ax = plt.subplots()

# Define a 1st position to annotate (display it with a marker)
xy = (0.5, 0.7)
ax.plot(xy[0], xy[1], ".r")

# Annotate the 1st position with a text box ('Test 1')
offsetbox = TextArea("Test 1")

ab = AnnotationBbox(offsetbox, xy,
                    xybox=(-20, 40),
                    xycoords='data',
                    boxcoords="offset points",
                    arrowprops=dict(arrowstyle="->"))
ax.add_artist(ab)

# Annotate the 1st position with another text box ('Test')
offsetbox = TextArea("Test")

ab = AnnotationBbox(offsetbox, xy,
                    xybox=(1.02, xy[1]),
                    xycoords='data',
                    boxcoords=("axes fraction", "data"),
Ejemplo n.º 7
0
    def _init_legend_box(self, handles, labels):
        """
        Initialize 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.
        descent = 0.35 * self._approx_text_height() * (self.handleheight - 0.7)
        # 0.35 and 0.7 are just heuristic numbers. this may need to be improbed
        height = self._approx_text_height() * self.handleheight - descent
        # each handle needs to be drawn inside a box of (x, y, w, h) =
        # (0, -descent, width, height).  And their coordinates 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().

        legend_handler_map = self.get_legend_handler_map()

        for orig_handle, lab in zip(handles, labels):

            handler = self.get_legend_handler(legend_handler_map, orig_handle)

            if handler is None:
                warnings.warn(
                    "Legend does not support %s\nUse proxy artist "
                    "instead.\n\n"
                    "http://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist\n"
                    % (str(orig_handle), ))
                handle_list.append(None)
                continue

            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)

            handle = handler(
                self,
                orig_handle,
                #xdescent, ydescent, width, height,
                fontsize,
                handlebox)

            handle_list.append(handle)

            handleboxes.append(handlebox)

        if len(handleboxes) > 0:

            # We calculate number of rows in each column. The first
            # (num_largecol) columns will have (nrows+1) rows, and remaining
            # (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
Ejemplo n.º 8
0
    def draw(self, renderer, *args, **kwargs):
        if not self.get_visible():
            return
        if self.dx == 0:
            return

        # Late import
        from matplotlib import rcParams

        # Deprecation
        if rcParams.get("scalebar.height_fraction") is not None:
            warnings.warn(
                "The scalebar.height_fraction parameter in matplotlibrc is deprecated. "
                "Use scalebar.width_fraction instead.",
                DeprecationWarning,
            )
            rcParams.setdefault("scalebar.width_fraction",
                                rcParams["scalebar.height_fraction"])

        # Get parameters
        def _get_value(attr, default):
            value = getattr(self, attr)
            if value is None:
                value = rcParams.get("scalebar." + attr, default)
            return value

        length_fraction = _get_value("length_fraction", 0.2)
        width_fraction = _get_value("width_fraction", 0.01)
        location = _get_value("location", "upper right")
        if isinstance(location, str):
            location = self._LOCATIONS[location.lower()]
        pad = _get_value("pad", 0.2)
        border_pad = _get_value("border_pad", 0.1)
        sep = _get_value("sep", 5)
        frameon = _get_value("frameon", True)
        color = _get_value("color", "k")
        box_color = _get_value("box_color", "w")
        box_alpha = _get_value("box_alpha", 1.0)
        scale_loc = _get_value("scale_loc", "bottom").lower()
        label_loc = _get_value("label_loc", "top").lower()
        font_properties = self.font_properties
        fixed_value = self.fixed_value
        fixed_units = self.fixed_units or self.units
        rotation = _get_value("rotation", "horizontal").lower()
        label = self.label

        # Create text properties
        textprops = {"color": color, "rotation": rotation}
        if font_properties is not None:
            textprops["fontproperties"] = font_properties

        # Calculate value, units and length
        ax = self.axes
        xlim = ax.get_xlim()
        ylim = ax.get_ylim()
        if rotation == "vertical":
            xlim, ylim = ylim, xlim

        # Mode 1: Auto
        if self.fixed_value is None:
            length_px = abs(xlim[1] - xlim[0]) * length_fraction
            length_px, value, units = self._calculate_best_length(length_px)

        # Mode 2: Fixed
        else:
            value = fixed_value
            units = fixed_units
            length_px = self._calculate_exact_length(value, units)

        scale_text = self.scale_formatter(value,
                                          self.dimension.to_latex(units))

        width_px = abs(ylim[1] - ylim[0]) * width_fraction

        # Create scale bar
        if rotation == "horizontal":
            scale_rect = Rectangle(
                (0, 0),
                length_px,
                width_px,
                fill=True,
                facecolor=color,
                edgecolor="none",
            )
        else:
            scale_rect = Rectangle(
                (0, 0),
                width_px,
                length_px,
                fill=True,
                facecolor=color,
                edgecolor="none",
            )

        scale_bar_box = AuxTransformBox(ax.transData)
        scale_bar_box.add_artist(scale_rect)

        scale_text_box = TextArea(scale_text, textprops=textprops)

        if scale_loc in ["bottom", "right"]:
            children = [scale_bar_box, scale_text_box]
        else:
            children = [scale_text_box, scale_bar_box]

        if scale_loc in ["bottom", "top"]:
            Packer = VPacker
        else:
            Packer = HPacker

        scale_box = Packer(children=children, align="center", pad=0, sep=sep)

        # Create label
        if label:
            label_box = TextArea(label, textprops=textprops)
        else:
            label_box = None

        # Create final offset box
        if label_box:
            if label_loc in ["bottom", "right"]:
                children = [scale_box, label_box]
            else:
                children = [label_box, scale_box]

            if label_loc in ["bottom", "top"]:
                Packer = VPacker
            else:
                Packer = HPacker

            child = Packer(children=children, align="center", pad=0, sep=sep)
        else:
            child = scale_box

        box = AnchoredOffsetbox(loc=location,
                                pad=pad,
                                borderpad=border_pad,
                                child=child,
                                frameon=frameon)

        box.axes = ax
        box.set_figure(self.get_figure())
        box.patch.set_color(box_color)
        box.patch.set_alpha(box_alpha)
        box.draw(renderer)
Ejemplo n.º 9
0
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.offsetbox import AnchoredOffsetbox, TextArea, HPacker, VPacker

with open('./watchlist.json') as data_file:
    data = json.load(data_file)

y1 = data['test']['mlogloss']
x1 = [i for i in range(1, len(y1)+1)]

y2 = data['train']['mlogloss']

plt.plot(x1, y1, label='test')
plt.plot(x1, y2, label='train')
plt.xlabel('Iterations')
plt.ylabel('Log Loss')
ybox1 = TextArea("", textprops=dict(color="r", size=15,rotation=90,ha='left',va='bottom'))
ybox2 = TextArea("",     textprops=dict(color="k", size=15,rotation=90,ha='left',va='bottom'))
ybox3 = TextArea("", textprops=dict(color="b", size=15,rotation=90,ha='left',va='bottom'))

ybox = VPacker(children=[ybox1, ybox2, ybox3],align="bottom", pad=0, sep=5)

ax = plt.subplot(111)

anchored_ybox = AnchoredOffsetbox(loc=8, child=ybox, pad=0., frameon=False, bbox_to_anchor=(-0.08, 0.4),
                                  bbox_transform=ax.transAxes, borderpad=0.)

ax.add_artist(anchored_ybox)
plt.legend()
plt.show()
Ejemplo n.º 10
0
def plot_mixtures(axes, project, mixtures):
    legend = getattr(project, "__plot_mixture_legend", None)
    if legend:
        try: legend.remove()
        except ValueError: pass

    figure = axes.get_figure()
    trans = figure.transFigure

    def create_rect_patch(ec="#000000", fc=None):
        _box = AuxTransformBox(transforms.IdentityTransform())
        rect = FancyBboxPatch(
            xy=(0, 0),
            width=0.02,
            height=0.02,
            boxstyle='square',
            ec=ec,
            fc=fc,
            mutation_scale=14, # font size
            transform=trans,
            alpha=1.0 if (ec is not None or fc is not None) else 0.0
        )
        _box.add_artist(rect)
        return _box

    legends = []
    for mixture in mixtures:
        legend_items = []

        # Add title:
        title = TextArea(mixture.name)
        title_children = [create_rect_patch(ec=None) for spec in mixture.specimens]
        title_children.insert(0, title)
        title_box = HPacker(children=title_children, align="center", pad=5, sep=3)
        legend_items.append(title_box)

        # Add phase labels & boxes
        for i, (phase, fraction) in enumerate(zip(mixture.phases, mixture.fractions)):
            label_text = "{}: {:>5.1f}".format(phase, fraction * 100.0)
            label = TextArea(label_text)
            phase_children = [
                create_rect_patch(fc=phase.display_color)
                for phase in mixture.phase_matrix[:, i].flat if phase is not None
            ]
            phase_children.insert(0, label)
            legend_items.append(
                HPacker(children=phase_children, align="center", pad=0, sep=3)
            )

        # Add created legend to the list:
        legends.append(
            VPacker(children=legend_items, align="right", pad=0, sep=3)
        )

    # Only add this if there's something to add!
    if legends:
        # Pack legends & plot:
        legend = AnchoredOffsetbox(
            loc=1,
            pad=0.1,
            borderpad=0.1,
            frameon=False,
            child=VPacker(children=legends, align="right", pad=0, sep=5)
        )

        axes.add_artist(legend)
        setattr(project, "__plot_mixture_legend", legend)
Ejemplo n.º 11
0
def make_summary_figure(
    indices_low, indices_high,
    psnr_HR_low, psnr_HR_high,
    psnr_LR_low, psnr_LR_high,
    target_loss_low, target_loss_high,
    training_loss_low, training_loss_high,
    experiment_name,
    psnr_blurred_low=None, psnr_blurred_high=None,
    psnr_downsampled_low=None, psnr_downsampled_high=None):

    if not (psnr_downsampled_high and psnr_downsampled_low):
        nrows = 4
        figsize = (7,14)
    else:
        nrows = 6
        figsize = (7, 21)
    fig, axes = plt.subplots(nrows, 1, sharex=True, gridspec_kw={'hspace': 0}, figsize=figsize, dpi=250)
    fig.suptitle('{}'.format(experiment_name), fontsize=16)


    if len(psnr_HR_low) > 0:
        axes[0].set_ylabel('PSNR HR_Out')
        x_coord = indices_high[np.argmax(psnr_HR_high)]
        y_coord = np.max(psnr_HR_high)
        offsetbox = TextArea("Iteration: {}\nPSNR: {:.2f}".format(x_coord, y_coord), minimumdescent=False)
        ab = AnnotationBbox(offsetbox, (x_coord, y_coord),
                            xybox=(0.02, 0.92),
                            xycoords='data',
                            boxcoords=("axes fraction", "axes fraction"),
                            box_alignment=(0., 0.5),
                            arrowprops=dict(arrowstyle="->"))
        axes[0].add_artist(ab)
        axes[0].plot(indices_low, psnr_HR_low)
        axes[0].scatter(indices_high, psnr_HR_high)
        axes[0].plot(x_coord, y_coord, ".r") 


    axes[1].set_ylabel('PSNR LR_Out')
    x_coord = indices_high[np.argmax(psnr_LR_high)]
    y_coord = np.max(psnr_LR_high)
    offsetbox = TextArea("Iteration: {}\nPSNR: {:.2f}".format(x_coord, y_coord), minimumdescent=False)
    ab = AnnotationBbox(offsetbox, (x_coord, y_coord),
                        xybox=(0.02, 0.92),
                        xycoords='data',
                        boxcoords=("axes fraction", "axes fraction"),
                        box_alignment=(0., 0.5),
                        arrowprops=dict(arrowstyle="->"))
    axes[1].add_artist(ab)
    axes[1].plot(indices_low, psnr_LR_low)
    axes[1].scatter(indices_high, psnr_LR_high)
    axes[1].plot(x_coord, y_coord, ".r") 

    if len(target_loss_low) > 0:
        axes[2].set_ylabel('Target Loss')
        x_coord = indices_high[np.argmin(target_loss_high)]
        y_coord = np.min(target_loss_high)
        offsetbox = TextArea("Iteration: {}\nLoss: {:.2e}".format(x_coord, y_coord), minimumdescent=False)
        ab = AnnotationBbox(offsetbox, (x_coord, y_coord),
                            xybox=(0.02, 0.92),
                            xycoords='data',
                            boxcoords=("axes fraction", "axes fraction"),
                            box_alignment=(0., 0.5),
                            arrowprops=dict(arrowstyle="->"))
        axes[2].add_artist(ab)
        axes[2].plot(indices_low, target_loss_low)
        axes[2].scatter(indices_high, target_loss_high)
        axes[2].plot(x_coord, y_coord, ".r") 

    axes[3].set_ylabel('Training Loss')
    axes[3].set_xlabel('Iterations')
    x_coord = indices_high[np.argmin(training_loss_high)]
    y_coord = np.min(training_loss_high)
    offsetbox = TextArea("Iteration: {}\nLoss: {:.2e}".format(x_coord, y_coord), minimumdescent=False)
    ab = AnnotationBbox(offsetbox, (x_coord, y_coord),
                        xybox=(0.02, 0.92),
                        xycoords='data',
                        boxcoords=("axes fraction", "axes fraction"),
                        box_alignment=(0., 0.5),
                        arrowprops=dict(arrowstyle="->"))
    axes[3].add_artist(ab)
    axes[3].plot(indices_low, training_loss_low)
    axes[3].scatter(indices_high, training_loss_high)
    axes[3].plot(x_coord, y_coord, ".r") 

    if psnr_downsampled_high and psnr_downsampled_low:
        axes[4].set_ylabel('PSNR Downsampled')
        axes[4].set_xlabel('Iterations')
        x_coord = indices_high[np.argmax(psnr_downsampled_high)]
        y_coord = np.max(psnr_downsampled_high)
        offsetbox = TextArea("Iteration: {}\nLoss: {:.2f}".format(x_coord, y_coord), minimumdescent=False)
        ab = AnnotationBbox(offsetbox, (x_coord, y_coord),
                            xybox=(0.02, 0.92),
                            xycoords='data',
                            boxcoords=("axes fraction", "axes fraction"),
                            box_alignment=(0., 0.5),
                            arrowprops=dict(arrowstyle="->"))
        axes[4].add_artist(ab)
        axes[4].plot(indices_low, psnr_downsampled_low)
        axes[4].scatter(indices_high, psnr_downsampled_high)
        axes[4].plot(x_coord, y_coord, ".r") 

        axes[5].set_ylabel('PSNR Blurred')
        axes[5].set_xlabel('Iterations')
        x_coord = indices_high[np.argmax(psnr_blurred_high)]
        y_coord = np.max(psnr_blurred_high)
        offsetbox = TextArea("Iteration: {}\nLoss: {:.2f}".format(x_coord, y_coord), minimumdescent=False)
        ab = AnnotationBbox(offsetbox, (x_coord, y_coord),
                            xybox=(0.02, 0.92),
                            xycoords='data',
                            boxcoords=("axes fraction", "axes fraction"),
                            box_alignment=(0., 0.5),
                            arrowprops=dict(arrowstyle="->"))
        axes[5].add_artist(ab)
        axes[5].plot(indices_low, psnr_blurred_low)
        axes[5].scatter(indices_high, psnr_blurred_high)
        axes[5].plot(x_coord, y_coord, ".r") 

    for ax in axes:
        ax.label_outer()
    plt.savefig('output/{}.png'.format(experiment_name))
Ejemplo n.º 12
0
        imagebox = OffsetImage(pirate, zoom=zoomc)

        # create annotation bbox with image and setup properties
        ab = AnnotationBbox(
            imagebox,
            xy,
            xybox=(-200. * zoomc, 200. * zoomc),
            xycoords='data',
            boxcoords="offset points",
            pad=0.1,
            arrowprops=dict(arrowstyle="->",
                            connectionstyle="angle,angleA=0,angleB=-30,rad=3"))
        ax.add_artist(ab)

        # add text
        no_pirates = TextArea(pirates[x], minimumdescent=False)
        ab = AnnotationBbox(
            no_pirates,
            xy,
            xybox=(50., -25.),
            xycoords='data',
            boxcoords="offset points",
            pad=0.3,
            arrowprops=dict(arrowstyle="->",
                            connectionstyle="angle,angleA=0,angleB=-30,rad=3"))
        ax.add_artist(ab)

    plt.grid(1)
    plt.xlim(1800, 2020)
    plt.ylim(14, 16)
    plt.title(title)
Ejemplo n.º 13
0
    def draw(self, renderer, *args, **kwargs):
        if not self.get_visible():
            return
        if self.dx == 0:
            return

        # Get parameters
        from matplotlib import rcParams  # late import

        def _get_value(attr, default):
            value = getattr(self, attr)
            if value is None:
                value = rcParams.get("scalebar." + attr, default)
            return value

        length_fraction = _get_value("length_fraction", 0.2)
        height_fraction = _get_value("height_fraction", 0.01)
        location = _get_value("location", "upper right")
        if isinstance(location, str):
            location = self._LOCATIONS[location]
        pad = _get_value("pad", 0.2)
        border_pad = _get_value("border_pad", 0.1)
        sep = _get_value("sep", 5)
        frameon = _get_value("frameon", True)
        color = _get_value("color", "k")
        box_color = _get_value("box_color", "w")
        box_alpha = _get_value("box_alpha", 1.0)
        scale_loc = _get_value("scale_loc", "bottom")
        label_loc = _get_value("label_loc", "top")
        font_properties = self.font_properties
        fixed_value = self.fixed_value
        fixed_units = self.fixed_units or self.units

        if font_properties is None:
            textprops = {"color": color}
        else:
            textprops = {"color": color, "fontproperties": font_properties}

        ax = self.axes
        xlim = ax.get_xlim()
        ylim = ax.get_ylim()
        label = self.label

        # Calculate value, units and length
        # Mode 1: Auto
        if self.fixed_value is None:
            length_px = abs(xlim[1] - xlim[0]) * length_fraction
            length_px, value, units = self._calculate_best_length(length_px)

        # Mode 2: Fixed
        else:
            value = fixed_value
            units = fixed_units
            length_px = self._calculate_exact_length(value, units)

        scale_label = self.label_formatter(value,
                                           self.dimension.to_latex(units))

        size_vertical = abs(ylim[1] - ylim[0]) * height_fraction

        # Create size bar
        sizebar = AuxTransformBox(ax.transData)
        sizebar.add_artist(
            Rectangle(
                (0, 0),
                length_px,
                size_vertical,
                fill=True,
                facecolor=color,
                edgecolor="none",
            ))

        txtscale = TextArea(scale_label,
                            minimumdescent=False,
                            textprops=textprops)

        if scale_loc in ["bottom", "right"]:
            children = [sizebar, txtscale]
        else:
            children = [txtscale, sizebar]
        if scale_loc in ["bottom", "top"]:
            Packer = VPacker
        else:
            Packer = HPacker
        boxsizebar = Packer(children=children, align="center", pad=0, sep=sep)

        # Create text area
        if label:
            txtlabel = TextArea(label,
                                minimumdescent=False,
                                textprops=textprops)
        else:
            txtlabel = None

        # Create final offset box
        if txtlabel:
            if label_loc in ["bottom", "right"]:
                children = [boxsizebar, txtlabel]
            else:
                children = [txtlabel, boxsizebar]
            if label_loc in ["bottom", "top"]:
                Packer = VPacker
            else:
                Packer = HPacker
            child = Packer(children=children, align="center", pad=0, sep=sep)
        else:
            child = boxsizebar

        box = AnchoredOffsetbox(loc=location,
                                pad=pad,
                                borderpad=border_pad,
                                child=child,
                                frameon=frameon)

        box.axes = ax
        box.set_figure(self.get_figure())
        box.patch.set_color(box_color)
        box.patch.set_alpha(box_alpha)
        box.draw(renderer)
Ejemplo n.º 14
0
def fig_2_6():
    e_greedy_agents = [
        BanditAgent(k, method='Egreedy', α=0, ε=2**e) for e in range(-7, -1)
    ]
    gradient_agents = [
        BanditAgent(k, method='Gradient', α=2**a, with_baseline=True)
        for a in range(-5, 3)
    ]
    ucb_agents = [
        BanditAgent(k, method='UCB', c=2**c, α=0) for c in range(-4, 3)
    ]
    optim_init_agents = [
        BanditAgent(k, method='Egreedy', α=0.1, q=2**q, ε=0)
        for q in range(-2, 3)
    ]
    agents = e_greedy_agents + gradient_agents + ucb_agents + optim_init_agents
    print(f'[*] Agent ({len(agents)}):')
    for agent in agents:
        print(f' └──{agent}')

    avg_reward_per_step, _, cost_time = run_k_bandit_test(agents)
    avg_reward = avg_reward_per_step.mean(1)
    e_greedy_r = avg_reward[:6]
    gradient_r = avg_reward[6:14]
    ucb_r = avg_reward[14:21]
    optiminit_r = avg_reward[21:]
    print(f'[*] Cost time: {cost_time}')
    print(f'[*] Average reward:')
    print(f'    e-greedy: {e_greedy_r}')
    print(f'    gradient: {gradient_r}')
    print(f'         ucb: {ucb_r}')
    print(f'    opt init: {optiminit_r}')

    plt.figure(figsize=(8, 5))
    ax = plt.subplot()
    data = [('ε-greedy', 'r', range(-7, -1), e_greedy_r, -6, 1.3),
            ('gradient\nbandit', 'g', range(-5, 3), gradient_r, 0, 1.2),
            ('UCB', 'b', range(-4, 3), ucb_r, -2, 1.45),
            ('greedy with\noptimistic\ninitialization\nα=0.1', 'black',
             range(-2, 3), optiminit_r, 1.8, 1.42)]
    for i, (label, color, x, y, px, py) in enumerate(data):
        plt.plot(x, y, color=color, lw=1)
        plt.text(px,
                 py,
                 label,
                 color=color,
                 fontsize=12,
                 horizontalalignment='center',
                 verticalalignment='center')
    plt.ylabel('Average\nreward\nover first\n1000 steps',
               rotation=0,
               labelpad=50,
               fontsize=15,
               verticalalignment='center')
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.set_ylim((0.99, 1.5))
    ax.spines['left'].set_bounds(0.99, 1.5)
    plt.yticks(np.arange(1, 1.51, 0.1))

    from matplotlib.offsetbox import TextArea, HPacker, AnchoredOffsetbox
    # x-axis label
    xbox0 = TextArea(' ' * 20)
    xbox1 = TextArea(r'$\epsilon$', textprops=dict(color='r', fontsize=15))
    xbox2 = TextArea(r'$\alpha$', textprops=dict(color='g', fontsize=15))
    xbox3 = TextArea(r'$c$', textprops=dict(color='b', fontsize=15))
    xbox4 = TextArea(r'$Q_0$', textprops=dict(color='black', fontsize=15))
    xbox = HPacker(children=[xbox0, xbox1, xbox2, xbox3, xbox4],
                   align='center',
                   pad=-20,
                   sep=10)
    anchored_xbox = AnchoredOffsetbox(loc=3,
                                      child=xbox,
                                      pad=0.,
                                      frameon=False,
                                      bbox_to_anchor=(0.3, -0.07),
                                      bbox_transform=ax.transAxes,
                                      borderpad=0.)
    ax.add_artist(anchored_xbox)
    plt.xticks(range(-7, 3))
    ax.set_xticklabels(
        [f'{"1/" if i < 0 else ""}{2**abs(i)}' for i in range(-7, 3)])
    ax.set_xlim((-7.1, 2))
    ax.spines['bottom'].set_bounds(-7.1, 2)

    plt.savefig('fig_2.6_parameter_study_of_various_algorithms.png',
                dpi=300,
                bbox_inches='tight')
    plt.close()
Ejemplo n.º 15
0
    def do_plot(self, wallet, history):
        balance_Val = []
        fee_val = []
        value_val = []
        datenums = []
        unknown_trans = 0
        pending_trans = 0
        counter_trans = 0
        balance = 0
        for item in history:
            tx_hash, confirmations, value, timestamp, balance = item
            if confirmations:
                if timestamp is not None:
                    try:
                        datenums.append(
                            md.date2num(
                                datetime.datetime.fromtimestamp(timestamp)))
                        balance_Val.append(1. * balance / COIN)
                    except [RuntimeError, TypeError, NameError] as reason:
                        unknown_trans += 1
                        pass
                else:
                    unknown_trans += 1
            else:
                pending_trans += 1

            value_val.append(1. * value / COIN)
            if tx_hash:
                label = wallet.get_label(tx_hash)
                label = label.encode('utf-8')
            else:
                label = ""

        f, axarr = plt.subplots(2, sharex=True)

        plt.subplots_adjust(bottom=0.2)
        plt.xticks(rotation=25)
        ax = plt.gca()
        x = 19
        test11 = "Unknown transactions =  " + str(
            unknown_trans) + " Pending transactions =  " + str(
                pending_trans) + " ."
        box1 = TextArea(" Test : Number of pending transactions",
                        textprops=dict(color="k"))
        box1.set_text(test11)

        box = HPacker(children=[box1], align="center", pad=0.1, sep=15)

        anchored_box = AnchoredOffsetbox(
            loc=3,
            child=box,
            pad=0.5,
            frameon=True,
            bbox_to_anchor=(0.5, 1.02),
            bbox_transform=ax.transAxes,
            borderpad=0.5,
        )

        ax.add_artist(anchored_box)

        plt.ylabel('CESC')
        plt.xlabel('Dates')
        xfmt = md.DateFormatter('%Y-%m-%d')
        ax.xaxis.set_major_formatter(xfmt)

        axarr[0].plot(datenums,
                      balance_Val,
                      marker='o',
                      linestyle='-',
                      color='blue',
                      label='Balance')
        axarr[0].legend(loc='upper left')
        axarr[0].set_title('History Transactions')

        xfmt = md.DateFormatter('%Y-%m-%d')
        ax.xaxis.set_major_formatter(xfmt)
        axarr[1].plot(datenums,
                      value_val,
                      marker='o',
                      linestyle='-',
                      color='green',
                      label='Value')

        axarr[1].legend(loc='upper left')
        #   plt.annotate('unknown transaction = %d \n pending transactions = %d' %(unknown_trans,pending_trans),xy=(0.7,0.05),xycoords='axes fraction',size=12)
        plt.show()
Ejemplo n.º 16
0
    def __init__(self,
                 transform,
                 size=0,
                 label=None,
                 horizontal=True,
                 style='dark',
                 loc=4,
                 pad=0.1,
                 borderpad=0.1,
                 sep=2,
                 prop=None,
                 **kwargs):
        """
        Draw a horizontal and/or vertical  bar with the size in data coordinate
        of the give axes. A label will be drawn underneath (center-aligned).

        - transform : the coordinate frame (typically axes.transData)
        - sizex,sizey : width / height of the bar, in data units.
        - label: label for bars; None to omit
        - horizontal: Whether the bar is horizontal (True) or vertical (False)
        - style: Whether the bar is dark ('dark') or bright (anything else)
        - loc : position in containing axes
        - pad, borderpad : padding, in fraction of the legend font size (or prop)
        - sep : separation between labels and bars in points.
        - **kwargs : additional arguments passed to base class constructor
        """
        from matplotlib.offsetbox import AuxTransformBox, VPacker, HPacker, TextArea
        import matplotlib.patches as mpatches

        from matplotlib.font_manager import FontProperties
        fp = FontProperties(size=30.)

        if style == 'dark':
            textcol = 'k'
        else:
            textcol = 'w'
        bars = AuxTransformBox(transform)
        endpt = (size, 0) if horizontal else (0, size)
        art = mpatches.FancyArrowPatch((0, 0),
                                       endpt,
                                       color=textcol,
                                       arrowstyle="|-|",
                                       linewidth=2.5)
        bars.add_artist(art)

        packer = VPacker if horizontal else HPacker
        bars = packer(children=[
            bars,
            TextArea(label,
                     dict(color=textcol, size=20.),
                     minimumdescent=False)
        ],
                      align="center",
                      pad=0,
                      sep=sep)

        AnchoredOffsetbox.__init__(self,
                                   loc,
                                   pad=pad,
                                   borderpad=borderpad,
                                   child=bars,
                                   prop=prop,
                                   frameon=False,
                                   **kwargs)
Ejemplo n.º 17
0
    def _init_legend_box(self, handles, labels, markerfirst=True):
        """
        Initialize 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.
        descent = 0.35 * self._approx_text_height() * (self.handleheight - 0.7)
        # 0.35 and 0.7 are just heuristic numbers and may need to be improved.
        height = self._approx_text_height() * self.handleheight - descent
        # each handle needs to be drawn inside a box of (x, y, w, h) =
        # (0, -descent, width, height).  And their coordinates 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 use its
        # default transform (e.g., Collections), you need to
        # manually set their transform to the self.get_transform().
        legend_handler_map = self.get_legend_handler_map()

        for orig_handle, lab in zip(handles, labels):
            handler = self.get_legend_handler(legend_handler_map, orig_handle)
            if handler is None:
                warnings.warn(
                    "Legend does not support {!r} instances.\nA proxy artist "
                    "may be used instead.\nSee: "
                    "http://matplotlib.org/users/legend_guide.html"
                    "#using-proxy-artist".format(orig_handle))
                # We don't have a handle for this artist, so we just defer
                # to None.
                handle_list.append(None)
            else:
                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)
                handleboxes.append(handlebox)

                # Deprecate the old behaviour of accepting callable
                # legend handlers in favour of the "legend_artist"
                # interface.
                if (not hasattr(handler, 'legend_artist')
                        and callable(handler)):
                    handler.legend_artist = handler.__call__
                    warn_deprecated('1.4',
                                    ('Legend handers must now implement a '
                                     '"legend_artist" method rather than '
                                     'being a callable.'))

                # Create the artist for the legend which represents the
                # original artist/handle.
                handle_list.append(
                    handler.legend_artist(self, orig_handle, fontsize,
                                          handlebox))

        if len(handleboxes) > 0:

            # We calculate number of rows in each column. The first
            # (num_largecol) columns will have (nrows+1) rows, and remaining
            # (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(
                list(xrange(0, num_largecol * (nrows + 1), (nrows + 1))),
                [nrows + 1] * num_largecol)
            smallcol = safezip(
                list(
                    xrange(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] if markerfirst else [t, h],
                        align="baseline") for h, t in handle_label[i0:i0 + di]
            ]
            # minimumdescent=False for the text of the last row of the column
            if markerfirst:
                itemBoxes[-1].get_children()[1].set_minimumdescent(False)
            else:
                itemBoxes[-1].get_children()[0].set_minimumdescent(False)

            # pack columnBox
            if markerfirst:
                alignment = "baseline"
            else:
                alignment = "right"
            columnbox.append(
                VPacker(pad=0,
                        sep=self.labelspacing * fontsize,
                        align=alignment,
                        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.º 18
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.
        """

        # 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.

        # 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 * self.fontsize,
                                    (self.handlelength - 0.3) * self.fontsize,
                                    npoints)
                xdata_marker = xdata
            elif npoints == 1:
                xdata = np.linspace(0, self.handlelength * self.fontsize, 2)
                xdata_marker = [0.5 * self.handlelength * self.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 * self.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 * self.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 * self.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 * self.fontsize,
                        align="baseline",
                        children=itemBoxes))

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

        sep = self.columnspacing * self.fontsize

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

        self.texts = text_list
        self.legendHandles = handle_list
Ejemplo n.º 19
0
def annotate(frame):
    zf = 0.15  #The zoom factor for the image2
    text1 = frame['gt_caption']
    path1 = frame['path']
    words = path1.split('/')
    sim1 = 'class : ' + words[len(words) - 3]
    knn = frame['knn']
    text2 = knn[0]['caption']
    bleu2 = "%.2f" % nltk.translate.bleu_score.sentence_bleu(text1, text2)
    path2 = knn[0]['path']
    words = path2.split('/')
    sim2 = 'class : ' + words[len(words) - 3] + ' Similarity : ' + str(
        knn[0]['similarity']) + ' BLEU :' + str(bleu2)
    text3 = knn[1]['caption']
    bleu3 = "%.2f" % nltk.translate.bleu_score.sentence_bleu(text1, text3)
    path3 = knn[1]['path']
    words = path3.split('/')
    sim3 = 'class : ' + words[len(words) - 3] + ' Similarity: ' + str(
        knn[1]['similarity']) + ' BLEU :' + str(bleu3)
    text4 = knn[2]['caption']
    bleu4 = "%.2f" % nltk.translate.bleu_score.sentence_bleu(text1, text4)
    path4 = knn[2]['path']
    words = path4.split('/')
    sim4 = 'class : ' + words[len(words) - 3] + ' Similarity: ' + str(
        knn[2]['similarity']) + ' BLEU :' + str(bleu4)

    #fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex='col', sharey='row')
    fig, ((ax1, ax2, ax3, ax4)) = plt.subplots(4, 1, sharey='row')

    # Define a 1st position to annotate (display it with a marker)
    xy = (0.5, 0.7)
    ax1.plot(xy[0], xy[1], ".r")

    # Annotate the 1st position with a text box ('Test 1')
    offsetbox = TextArea(text1, minimumdescent=False)

    ab = AnnotationBbox(offsetbox,
                        xy,
                        xybox=(0.5, 5.5),
                        xycoords='data',
                        boxcoords=("axes fraction", "data"))
    ax1.add_artist(ab)

    # Annotate the 1st position with a text box ('Test 1')
    offsetbox = TextArea(sim1, minimumdescent=False)

    ab = AnnotationBbox(offsetbox,
                        xy,
                        xybox=(0.5, -5.5),
                        xycoords='data',
                        boxcoords=("axes fraction", "data"))
    ax1.add_artist(ab)

    # Annotate the 1st position with another text box ('Test')
    offsetbox = TextArea(text2, minimumdescent=False)

    ab = AnnotationBbox(offsetbox,
                        xy,
                        xybox=(0.5, 5.5),
                        xycoords='data',
                        boxcoords=("axes fraction", "data"))
    ax2.add_artist(ab)

    offsetbox = TextArea(sim2, minimumdescent=False)

    ab = AnnotationBbox(offsetbox,
                        xy,
                        xybox=(0.5, -5.5),
                        xycoords='data',
                        boxcoords=("axes fraction", "data"))
    ax2.add_artist(ab)

    offsetbox = TextArea(text3, minimumdescent=False)

    ab = AnnotationBbox(offsetbox,
                        xy,
                        xybox=(0.5, 5.5),
                        xycoords='data',
                        boxcoords=("axes fraction", "data"))
    ax3.add_artist(ab)

    offsetbox = TextArea(sim3, minimumdescent=False)

    ab = AnnotationBbox(offsetbox,
                        xy,
                        xybox=(0.5, -5.5),
                        xycoords='data',
                        boxcoords=("axes fraction", "data"))
    ax3.add_artist(ab)

    offsetbox = TextArea(text4, minimumdescent=False)

    ab = AnnotationBbox(offsetbox,
                        xy,
                        xybox=(0.5, 5.5),
                        xycoords='data',
                        boxcoords=("axes fraction", "data"))

    ax4.add_artist(ab)

    offsetbox = TextArea(sim4, minimumdescent=False)

    ab = AnnotationBbox(offsetbox,
                        xy,
                        xybox=(0.5, -5.5),
                        xycoords='data',
                        boxcoords=("axes fraction", "data"))
    ax4.add_artist(ab)

    xy = (1, 0)

    #arr = plt.imread(path1)
    arr = Image.open(path1)
    arr = arr.resize((480, 360), Image.ANTIALIAS)

    im = OffsetImage(arr, zoom=zf)
    im.image.axes = ax1

    ab = AnnotationBbox(im,
                        xy,
                        xybox=(0.5, 0),
                        xycoords='data',
                        boxcoords=("axes fraction", "data"))

    ax1.add_artist(ab)

    #Adding the second image now
    #arr_img = plt.imread(path2)
    arr_img = Image.open(path2)
    arr_img = arr_img.resize((480, 360), Image.ANTIALIAS)

    imagebox = OffsetImage(arr_img, zoom=zf)
    imagebox.image.axes = ax2

    ab = AnnotationBbox(imagebox,
                        xy,
                        xybox=(0.5, 0),
                        xycoords='data',
                        boxcoords=("axes fraction", "data"))

    ax2.add_artist(ab)

    #arr_img = plt.imread(path3)
    arr_img = Image.open(path3)
    arr_img = arr_img.resize((480, 360), Image.ANTIALIAS)

    imagebox = OffsetImage(arr_img, zoom=zf)
    imagebox.image.axes = ax2

    ab = AnnotationBbox(imagebox,
                        xy,
                        xybox=(0.5, 0),
                        xycoords='data',
                        boxcoords=("axes fraction", "data"))

    ax3.add_artist(ab)

    #arr_img = plt.imread(path4)
    arr_img = Image.open(path4)
    arr_img = arr_img.resize((480, 360), Image.ANTIALIAS)

    imagebox = OffsetImage(arr_img, zoom=zf)
    imagebox.image.axes = ax2

    ab = AnnotationBbox(imagebox,
                        xy,
                        xybox=(0.5, 0),
                        xycoords='data',
                        boxcoords=("axes fraction", "data"))

    ax4.add_artist(ab)

    # Fix the display limits to see everything
    ax1.set_ylim(-5, 5)
    ax1.set_xlim(-3, 3)
    ax1.axis('off')
    ax2.set_ylim(-5, 5)
    ax2.set_xlim(-3, 3)
    ax2.axis('off')
    ax3.set_ylim(-5, 5)
    ax3.set_xlim(-3, 3)
    ax3.axis('off')
    ax4.set_ylim(-5, 5)
    ax4.set_xlim(-3, 3)
    ax4.axis('off')
    figure = plt.gcf()  # get current figure
    names = path1.split('/')
    name = str(names[len(names) - 2]) + str(names[len(names) - 1])
    plt.savefig(name + '.png', bbox_inches='tight', dpi=600)
    plt.close()
    im = Image.open(name + '.png')
    os.remove(name + '.png')  #Removing this file as we don't need it
    return im
Ejemplo n.º 20
0
def make_title(title):
    title = title.title()
    return TextArea(" %s " % title,
                    textprops=dict(color="k", fontweight="bold"))
Ejemplo n.º 21
0
    def __init__(self, transform, size, label, loc,
                 pad=0.1, borderpad=0.1, sep=2,
                 frameon=True, size_vertical=0, color='black',
                 label_top=False, fontproperties=None, fill_bar=None,
                 **kwargs):
        """
        Draw a horizontal scale bar with a center-aligned label underneath.

        Parameters
        ----------
        transform : `matplotlib.transforms.Transform`
            The transformation object for the coordinate system in use, i.e.,
            :attr:`matplotlib.axes.Axes.transData`.

        size : float
            Horizontal length of the size bar, given in coordinates of
            *transform*.

        label : str
            Label to display.

        loc : int
            Location of this size bar. Valid location codes are::

                'upper right'  : 1,
                'upper left'   : 2,
                'lower left'   : 3,
                'lower right'  : 4,
                'right'        : 5,
                'center left'  : 6,
                'center right' : 7,
                'lower center' : 8,
                'upper center' : 9,
                'center'       : 10

        pad : float, default: 0.1
            Padding around the label and size bar, in fraction of the font
            size.

        borderpad : float, default: 0.1
            Border padding, in fraction of the font size.

        sep : float, default: 2
            Separation between the label and the size bar, in points.

        frameon : bool, default: True
            If True, draw a box around the horizontal bar and label.

        size_vertical : float, default: 0
            Vertical length of the size bar, given in coordinates of
            *transform*.

        color : str, default: 'black'
            Color for the size bar and label.

        label_top : bool, default: False
            If True, the label will be over the size bar.

        fontproperties : `matplotlib.font_manager.FontProperties`, optional
            Font properties for the label text.

        fill_bar : bool, optional
            If True and if size_vertical is nonzero, the size bar will
            be filled in with the color specified by the size bar.
            Defaults to True if *size_vertical* is greater than
            zero and False otherwise.

        **kwargs
            Keyworded arguments to pass to
            :class:`matplotlib.offsetbox.AnchoredOffsetbox`.

        Attributes
        ----------
        size_bar : `matplotlib.offsetbox.AuxTransformBox`
            Container for the size bar.

        txt_label : `matplotlib.offsetbox.TextArea`
            Container for the label of the size bar.

        Notes
        -----
        If *prop* is passed as a keyworded argument, but *fontproperties* is
        not, then *prop* is be assumed to be the intended *fontproperties*.
        Using both *prop* and *fontproperties* is not supported.

        Examples
        --------
        >>> import matplotlib.pyplot as plt
        >>> import numpy as np
        >>> from mpl_toolkits.axes_grid1.anchored_artists import (
        ...     AnchoredSizeBar)
        >>> fig, ax = plt.subplots()
        >>> ax.imshow(np.random.random((10, 10)))
        >>> bar = AnchoredSizeBar(ax.transData, 3, '3 data units', 4)
        >>> ax.add_artist(bar)
        >>> fig.show()

        Using all the optional parameters

        >>> import matplotlib.font_manager as fm
        >>> fontprops = fm.FontProperties(size=14, family='monospace')
        >>> bar = AnchoredSizeBar(ax.transData, 3, '3 units', 4, pad=0.5,
        ...                       sep=5, borderpad=0.5, frameon=False,
        ...                       size_vertical=0.5, color='white',
        ...                       fontproperties=fontprops)
        """
        if fill_bar is None:
            fill_bar = size_vertical > 0

        self.size_bar = AuxTransformBox(transform)
        self.size_bar.add_artist(Rectangle((0, 0), size, size_vertical,
                                           fill=fill_bar, facecolor=color,
                                           edgecolor=color))

        if fontproperties is None and 'prop' in kwargs:
            fontproperties = kwargs.pop('prop')

        if fontproperties is None:
            textprops = {'color': color}
        else:
            textprops = {'color': color, 'fontproperties': fontproperties}

        self.txt_label = TextArea(label, textprops=textprops)

        if label_top:
            _box_children = [self.txt_label, self.size_bar]
        else:
            _box_children = [self.size_bar, self.txt_label]

        self._box = VPacker(children=_box_children,
                            align="center",
                            pad=0, sep=sep)

        super().__init__(loc, pad=pad, borderpad=borderpad, child=self._box,
                         prop=fontproperties, frameon=frameon, **kwargs)
Ejemplo n.º 22
0
    def draw(self):
        """
        Draw guide

        Returns
        -------
        out : matplotlib.offsetbox.Offsetbox
            A drawing of this legend
        """
        obverse = slice(0, None)
        reverse = slice(None, None, -1)
        width = self.barwidth
        height = self.barheight
        nbars = len(self.bar)
        length = height
        direction = self.direction
        colors = self.bar['color'].tolist()
        labels = self.key['label'].tolist()
        themeable = self.theme.figure._themeable

        # When there is more than one guide, we keep
        # record of all of them using lists
        if 'legend_title' not in themeable:
            themeable['legend_title'] = []
        if 'legend_text_colorbar' not in themeable:
            themeable['legend_text_colorbar'] = []

        # .5 puts the ticks in the middle of the bars when
        # raster=False. So when raster=True the ticks are
        # in between interpolation points and the matching is
        # close though not exactly right.
        _from = self.bar['value'].min(), self.bar['value'].max()
        tick_locations = rescale(self.key['value'],
                                 (.5, nbars - .5), _from) * length / nbars

        if direction == 'horizontal':
            width, height = height, width
            length = width

        if self.reverse:
            colors = colors[::-1]
            labels = labels[::-1]
            tick_locations = length - tick_locations[::-1]

        # title #
        title_box = TextArea(self.title, textprops=dict(color='black'))
        themeable['legend_title'].append(title_box)

        # colorbar and ticks #
        da = DrawingArea(width, height, 0, 0)
        if self.raster:
            add_interpolated_colorbar(da, colors, direction)
        else:
            add_segmented_colorbar(da, colors, direction)

        if self.ticks:
            _locations = tick_locations
            if not self.draw_ulim:
                _locations = _locations[:-1]

            if not self.draw_llim:
                _locations = _locations[1:]

            add_ticks(da, _locations, direction)

        # labels #
        if self.label:
            labels_da, legend_text = create_labels(da, labels, tick_locations,
                                                   direction)
            themeable['legend_text_colorbar'].extend(legend_text)
        else:
            labels_da = DrawingArea(0, 0)

        # colorbar + labels #
        if direction == 'vertical':
            packer, align = HPacker, 'bottom'
            align = 'center'
        else:
            packer, align = VPacker, 'right'
            align = 'center'
        slc = obverse if self.label_position == 'right' else reverse
        if self.label_position in ('right', 'bottom'):
            slc = obverse
        else:
            slc = reverse
        main_box = packer(children=[da, labels_da][slc],
                          sep=self._label_margin,
                          align=align,
                          pad=0)

        # title + colorbar(with labels) #
        lookup = {
            'right': (HPacker, reverse),
            'left': (HPacker, obverse),
            'bottom': (VPacker, reverse),
            'top': (VPacker, obverse)
        }
        packer, slc = lookup[self.title_position]
        children = [title_box, main_box][slc]
        box = packer(children=children,
                     sep=self._title_margin,
                     align=self._title_align,
                     pad=0)
        return box
Ejemplo n.º 23
0
def word_group_visualization(
    transformed_word_embeddings: np.ndarray,
    words: np.ndarray,
    word_groups: dict,
    xlabel: str,
    ylabel: str,
    emphasis_words: list = None,
    alpha: float = 1,
    non_group_words_color: str = "#ccc",
    scatter_set_rasterized: bool = False,
    rasterization_threshold: int = 1000,
    ax: plt.axis = None,
    show_plot: bool = True,
) -> None:
    """
    Visualizes one or more word groups by plotting its word embeddings in 2D.

    Parameters
    ----------
    transformed_word_embeddings : np.ndarray
        Transformed word embeddings.
    words : np.ndarray
        Numpy array containing all words from vocabulary.
    word_groups : dict
        Dictionary containing word groups to visualize.
    xlabel : str
        X-axis label.
    ylabel : str
        Y-axis label.
    emphasis_words : list, optional
        List representing words to emphasize in the visualization (defaults to None).
        Entries can be either be strings (words) or tuples, consisting of the word, x-offset
        and y-offset.
    alpha : float
        Scatter plot alpha value (defaults to 1).
    non_group_words_color : str
        Color for words outside groups (defaults to #ccc).
    scatter_set_rasterized : bool
        Whether or not to enable rasterization on scatter plotting (defaults to False).
    rasterization_threshold : int
        The least number of data points to enable rasterization, given that
        `scatter_set_rasterized` is set to True (defaults to 1000).
    ax : plt.axis
        Axis (defaults to None).
    show_plot : bool
        Whether or not to call plt.show() (defaults to True).
    """
    # Filter and restrict words in word groups
    word_group_words_restricted = {}
    for group_key, group_data in word_groups.items():
        group_words = group_data["words"]
        group_words = np.array([word for word in group_words if word in words])
        group_words_indices = np.array(
            [np.where(words == word)[0][0] for word in group_words])
        group_word_embeddings = transformed_word_embeddings[
            group_words_indices]
        boundaries = group_data.get("boundaries", {})
        if boundaries.get("xmin") is None:
            boundaries["xmin"] = group_word_embeddings[:, 0].min()
        if boundaries.get("xmax") is None:
            boundaries["xmax"] = group_word_embeddings[:, 0].max()
        if boundaries.get("ymin") is None:
            boundaries["ymin"] = group_word_embeddings[:, 1].min()
        if boundaries.get("ymax") is None:
            boundaries["ymax"] = group_word_embeddings[:, 1].max()

        group_word_embeddings_boundaries_mask = [
            (boundaries["xmin"] <= word_vec[0] <= boundaries["xmax"])
            and (boundaries["ymin"] <= word_vec[1] <= boundaries["ymax"])
            for i, word_vec in enumerate(group_word_embeddings)
        ]
        word_group_words_restricted[group_key] = group_words[
            group_word_embeddings_boundaries_mask]

    # Find words not in groups
    words_not_in_groups_mask = [
        i for i, word in enumerate(words)
        for group_words in word_group_words_restricted.values()
        if word not in group_words
    ]

    if ax is None:
        _, ax = plt.subplots(figsize=(12, 7))
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)

    # Plot non-group words
    non_grp_scatter_handle = ax.scatter(
        x=transformed_word_embeddings[words_not_in_groups_mask][:, 0],
        y=transformed_word_embeddings[words_not_in_groups_mask][:, 1],
        s=10,
        alpha=alpha,
        c=non_group_words_color,
    )
    if (scatter_set_rasterized
            and len(words_not_in_groups_mask) >= rasterization_threshold):
        non_grp_scatter_handle.set_rasterized(True)

    # Plot group words
    for group_key, group_words in word_group_words_restricted.items():
        group_words_indices = np.array(
            [np.where(words == word)[0][0] for word in group_words])
        group_word_embeddings = transformed_word_embeddings[
            group_words_indices]

        grp_scatter_handle = ax.scatter(
            x=group_word_embeddings[:, 0],
            y=group_word_embeddings[:, 1],
            s=15,
            alpha=alpha,
            c=word_groups[group_key]["color"],
            label=word_groups[group_key]["label"],
        )
        if (scatter_set_rasterized
                and len(group_word_embeddings) >= rasterization_threshold):
            grp_scatter_handle.set_rasterized(True)

    # Visualize emphasized words
    if emphasis_words is not None:
        emphasis_words = [(entry, 0, 0) if type(entry) == str else entry
                          for entry in emphasis_words]
        for emphasis_word, x_offset, y_offset in emphasis_words:
            word_group_key = None
            for group_key, group_data in word_groups.items():
                if emphasis_word in group_data["words"]:
                    word_group_key = group_key
                    break
            if word_group_key is None:
                word_color = non_group_words_color
            else:
                word_color = word_groups[group_key]["color"]

            word_idx = [
                i for i, word in enumerate(words) if word == emphasis_word
            ][0]
            emphasis_scatter_handle = ax.scatter(
                x=transformed_word_embeddings[word_idx, 0],
                y=transformed_word_embeddings[word_idx, 1],
                s=40,
                alpha=alpha,
                c=word_color,
            )
            if (scatter_set_rasterized
                    and len(emphasis_words) >= rasterization_threshold):
                emphasis_scatter_handle.set_rasterized(True)

            # Annotate emphasis word with a text box
            offsetbox = TextArea(emphasis_word)
            ab = AnnotationBbox(
                offsetbox,
                tuple(transformed_word_embeddings[word_idx]),
                xybox=(x_offset, 40 + y_offset),
                xycoords="data",
                boxcoords="offset points",
                arrowprops=dict(arrowstyle="->", color="black", linewidth=2),
            )
            ax.add_artist(ab)

    ax.legend()
    if show_plot:
        plt.show()
Ejemplo n.º 24
0
    def summarizePerformance(self, test_data_set, learning_algo, *args, **kwargs):
        """ Plot of the low-dimensional representation of the environment built by the model
        """

        all_possib_inp=[] # Will store all possible inputs (=observation) for the CRAR agent
        labels_maze=[]
        self.create_map()
        for y_a in range(self._size_maze):
            for x_a in range(self._size_maze):                
                state=copy.deepcopy(self._map)
                state[self._size_maze//2,self._size_maze//2]=0
                if(state[x_a,y_a]==0):
                    if(self._higher_dim_obs==True):
                        all_possib_inp.append(self.get_higher_dim_obs([[x_a,y_a]],[self._pos_goal]))
                    else:
                        state[x_a,y_a]=0.5
                        all_possib_inp.append(state)
                    
                    ## labels
                    #if(y_a<self._size_maze//2):
                    #    labels_maze.append(0.)
                    #elif(y_a==self._size_maze//2):
                    #    labels_maze.append(1.)
                    #else:
                    #    labels_maze.append(2.)
        
        #arr=np.array(all_possib_inp)
        #if(self._higher_dim_obs==False):
        #    arr=arr.reshape(arr.shape[0],-1)
        #else:
        #    arr=arr.reshape(arr.shape[0],-1)
        #    
        #np.savetxt('tsne_python/mazesH_X.txt',arr.reshape(arr.shape[0],-1))
        #np.savetxt('tsne_python/mazesH_labels.txt',np.array(labels_maze))
        
        all_possib_inp=np.expand_dims(np.array(all_possib_inp,dtype='float'),axis=1)

        all_possib_abs_states=learning_algo.encoder.predict(all_possib_inp)
        if(all_possib_abs_states.ndim==4):
            all_possib_abs_states=np.transpose(all_possib_abs_states, (0, 3, 1, 2))    # data_format='channels_last' --> 'channels_first'
        
        n=1000
        historics=[]
        for i,observ in enumerate(test_data_set.observations()[0][0:n]):
            historics.append(np.expand_dims(observ,axis=0))
        historics=np.array(historics)

        abs_states=learning_algo.encoder.predict(historics)
        if(abs_states.ndim==4):
            abs_states=np.transpose(abs_states, (0, 3, 1, 2))    # data_format='channels_last' --> 'channels_first'

        actions=test_data_set.actions()[0:n]
        
        if self.inTerminalState() == False:
            self._mode_episode_count += 1
        print("== Mean score per episode is {} over {} episodes ==".format(self._mode_score / (self._mode_episode_count+0.0001), self._mode_episode_count))
                
        
        m = cm.ScalarMappable(cmap=cm.jet)
        
        x = np.array(abs_states)[:,0]
        y = np.array(abs_states)[:,1]
        if(self.intern_dim>2):
            z = np.array(abs_states)[:,2]
                    
        fig = plt.figure()
        if(self.intern_dim==2):
            ax = fig.add_subplot(111)
            ax.set_xlabel(r'$X_1$')
            ax.set_ylabel(r'$X_2$')
        else:
            ax = fig.add_subplot(111,projection='3d')
            ax.set_xlabel(r'$X_1$')
            ax.set_ylabel(r'$X_2$')
            ax.set_zlabel(r'$X_3$')
                    
        # Plot the estimated transitions
        for i in range(n-1):
            predicted1=learning_algo.transition.predict([abs_states[i:i+1],np.array([[1,0,0,0]])])
            predicted2=learning_algo.transition.predict([abs_states[i:i+1],np.array([[0,1,0,0]])])
            predicted3=learning_algo.transition.predict([abs_states[i:i+1],np.array([[0,0,1,0]])])
            predicted4=learning_algo.transition.predict([abs_states[i:i+1],np.array([[0,0,0,1]])])
            if(self.intern_dim==2):
                ax.plot(np.concatenate([x[i:i+1],predicted1[0,:1]]), np.concatenate([y[i:i+1],predicted1[0,1:2]]), color="0.9", alpha=0.75)
                ax.plot(np.concatenate([x[i:i+1],predicted2[0,:1]]), np.concatenate([y[i:i+1],predicted2[0,1:2]]), color="0.65", alpha=0.75)
                ax.plot(np.concatenate([x[i:i+1],predicted3[0,:1]]), np.concatenate([y[i:i+1],predicted3[0,1:2]]), color="0.4", alpha=0.75)
                ax.plot(np.concatenate([x[i:i+1],predicted4[0,:1]]), np.concatenate([y[i:i+1],predicted4[0,1:2]]), color="0.15", alpha=0.75)
            else:
                ax.plot(np.concatenate([x[i:i+1],predicted1[0,:1]]), np.concatenate([y[i:i+1],predicted1[0,1:2]]), np.concatenate([z[i:i+1],predicted1[0,2:3]]), color="0.9", alpha=0.75)
                ax.plot(np.concatenate([x[i:i+1],predicted2[0,:1]]), np.concatenate([y[i:i+1],predicted2[0,1:2]]), np.concatenate([z[i:i+1],predicted2[0,2:3]]), color="0.65", alpha=0.75)
                ax.plot(np.concatenate([x[i:i+1],predicted3[0,:1]]), np.concatenate([y[i:i+1],predicted3[0,1:2]]), np.concatenate([z[i:i+1],predicted3[0,2:3]]), color="0.4", alpha=0.75)
                ax.plot(np.concatenate([x[i:i+1],predicted4[0,:1]]), np.concatenate([y[i:i+1],predicted4[0,1:2]]), np.concatenate([z[i:i+1],predicted4[0,2:3]]), color="0.15", alpha=0.75)            
        
        # Plot the dots at each time step depending on the action taken
        length_block=[[0,18],[18,19],[19,31]]
        for i in range(3):
            colors=['blue','orange','green']
            if(self.intern_dim==2):
                line3 = ax.scatter(all_possib_abs_states[length_block[i][0]:length_block[i][1],0], all_possib_abs_states[length_block[i][0]:length_block[i][1],1], c=colors[i], marker='x', edgecolors='k', alpha=0.5, s=100)
            else:
                line3 = ax.scatter(all_possib_abs_states[length_block[i][0]:length_block[i][1],0], all_possib_abs_states[length_block[i][0]:length_block[i][1],1] ,all_possib_abs_states[length_block[i][0]:length_block[i][1],2], marker='x', depthshade=True, edgecolors='k', alpha=0.5, s=50)

        if(self.intern_dim==2):
            axes_lims=[ax.get_xlim(),ax.get_ylim()]
        else:
            axes_lims=[ax.get_xlim(),ax.get_ylim(),ax.get_zlim()]
        
        # Plot the legend for transition estimates
        box1b = TextArea(" Estimated transitions (action 0, 1, 2 and 3): ", textprops=dict(color="k"))
        box2b = DrawingArea(90, 20, 0, 0)
        el1b = Rectangle((5, 10), 15,2, fc="0.9", alpha=0.75)
        el2b = Rectangle((25, 10), 15,2, fc="0.65", alpha=0.75) 
        el3b = Rectangle((45, 10), 15,2, fc="0.4", alpha=0.75)
        el4b = Rectangle((65, 10), 15,2, fc="0.15", alpha=0.75) 
        box2b.add_artist(el1b)
        box2b.add_artist(el2b)
        box2b.add_artist(el3b)
        box2b.add_artist(el4b)
        
        boxb = HPacker(children=[box1b, box2b],
                      align="center",
                      pad=0, sep=5)
        
        anchored_box = AnchoredOffsetbox(loc=3,
                                         child=boxb, pad=0.,
                                         frameon=True,
                                         bbox_to_anchor=(0., 0.98),
                                         bbox_transform=ax.transAxes,
                                         borderpad=0.,
                                         )        
        ax.add_artist(anchored_box)
        
        
        #plt.show()
        plt.savefig('fig_base'+str(learning_algo.update_counter)+'.pdf')


#        # Plot the Q_vals
#        c = learning_algo.Q.predict(np.concatenate((np.expand_dims(x,axis=1),np.expand_dims(y,axis=1),np.expand_dims(z,axis=1)),axis=1))
#        #print "actions,C"
#        #print actions
#        #print c
#        #c=np.max(c,axis=1)
#        m1=ax.scatter(x, y, z+zrange/20, c=c[:,0], vmin=-1., vmax=1., cmap=plt.cm.RdYlGn)
#        m2=ax.scatter(x, y, z+3*zrange/40, c=c[:,1], vmin=-1., vmax=1., cmap=plt.cm.RdYlGn)
#        
#        #plt.colorbar(m3)
#        ax2 = fig.add_axes([0.85, 0.15, 0.025, 0.7])
#        cmap = matplotlib.cm.RdYlGn
#        norm = matplotlib.colors.Normalize(vmin=-1, vmax=1)
#
#        # ColorbarBase derives from ScalarMappable and puts a colorbar
#        # in a specified axes, so it has everything needed for a
#        # standalone colorbar.  There are many more kwargs, but the
#        # following gives a basic continuous colorbar with ticks
#        # and labels.
#        cb1 = matplotlib.colorbar.ColorbarBase(ax2, cmap=cmap,norm=norm,orientation='vertical')
#        cb1.set_label('Estimated expected return')
#
#        #plt.show()
#        plt.savefig('fig_w_V'+str(learning_algo.update_counter)+'.pdf')
#
#
#        # fig_visuV
#        fig = plt.figure()
#        ax = fig.add_subplot(111, projection='3d')
#        
#        x = np.array([i for i in range(5) for jk in range(25)])/4.*(axes_lims[0][1]-axes_lims[0][0])+axes_lims[0][0]
#        y = np.array([j for i in range(5) for j in range(5) for k in range(5)])/4.*(axes_lims[1][1]-axes_lims[1][0])+axes_lims[1][0]
#        z = np.array([k for i in range(5) for j in range(5) for k in range(5)])/4.*(axes_lims[2][1]-axes_lims[2][0])+axes_lims[2][0]
#
#        c = learning_algo.Q.predict(np.concatenate((np.expand_dims(x,axis=1),np.expand_dims(y,axis=1),np.expand_dims(z,axis=1)),axis=1))
#        c=np.max(c,axis=1)
#        #print "c"
#        #print c
#        
#        m=ax.scatter(x, y, z, c=c, vmin=-1., vmax=1., cmap=plt.hot())
#        #plt.colorbar(m)
#        fig.subplots_adjust(right=0.8)
#        ax2 = fig.add_axes([0.875, 0.15, 0.025, 0.7])
#        cmap = matplotlib.cm.hot
#        norm = matplotlib.colors.Normalize(vmin=-1, vmax=1)
#
#        # ColorbarBase derives from ScalarMappable and puts a colorbar
#        # in a specified axes, so it has everything needed for a
#        # standalone colorbar.  There are many more kwargs, but the
#        # following gives a basic continuous colorbar with ticks
#        # and labels.
#        cb1 = matplotlib.colorbar.ColorbarBase(ax2, cmap=cmap,norm=norm,orientation='vertical')
#        cb1.set_label('Estimated expected return')
#
#        #plt.show()
#        plt.savefig('fig_visuV'+str(learning_algo.update_counter)+'.pdf')
#
#
#        # fig_visuR
#        fig = plt.figure()
#        ax = fig.add_subplot(111, projection='3d')
#        
#        x = np.array([i for i in range(5) for jk in range(25)])/4.*(axes_lims[0][1]-axes_lims[0][0])+axes_lims[0][0]
#        y = np.array([j for i in range(5) for j in range(5) for k in range(5)])/4.*(axes_lims[1][1]-axes_lims[1][0])+axes_lims[1][0]
#        z = np.array([k for i in range(5) for j in range(5) for k in range(5)])/4.*(axes_lims[2][1]-axes_lims[2][0])+axes_lims[2][0]
#
#        coords=np.concatenate((np.expand_dims(x,axis=1),np.expand_dims(y,axis=1),np.expand_dims(z,axis=1)),axis=1)
#        repeat_nactions_coord=np.repeat(coords,self.nActions(),axis=0)
#        identity_matrix = np.diag(np.ones(self.nActions()))
#        tile_identity_matrix=np.tile(identity_matrix,(5*5*5,1))
#
#        c = learning_algo.R.predict([repeat_nactions_coord,tile_identity_matrix])
#        c=np.max(np.reshape(c,(125,self.nActions())),axis=1)
#        #print "c"
#        #print c
#        #mini=np.min(c)
#        #maxi=np.max(c)
#        
#        m=ax.scatter(x, y, z, c=c, vmin=-1., vmax=1., cmap=plt.hot())
#        #plt.colorbar(m)
#        fig.subplots_adjust(right=0.8)
#        ax2 = fig.add_axes([0.875, 0.15, 0.025, 0.7])
#        cmap = matplotlib.cm.hot
#        norm = matplotlib.colors.Normalize(vmin=-1, vmax=1)
#
#        # ColorbarBase derives from ScalarMappable and puts a colorbar
#        # in a specified axes, so it has everything needed for a
#        # standalone colorbar.  There are many more kwargs, but the
#        # following gives a basic continuous colorbar with ticks
#        # and labels.
#        cb1 = matplotlib.colorbar.ColorbarBase(ax2, cmap=cmap,norm=norm,orientation='vertical')
#        cb1.set_label('Estimated expected return')
#
#        #plt.show()
#        plt.savefig('fig_visuR'+str(learning_algo.update_counter)+'.pdf')

        matplotlib.pyplot.close("all") # avoids memory leaks
Ejemplo n.º 25
0
    def __init__(self,
                 transform,
                 sizex=0,
                 sizey=0,
                 labelx=None,
                 labely=None,
                 loc=4,
                 pad=0.1,
                 borderpad=0.1,
                 sep=2,
                 prop=None,
                 barcolor="black",
                 barwidth=0.4,
                 **kwargs):
        """
        Draw a horizontal and/or vertical  bar with the size in data coordinate
        of the give axes. A label will be drawn underneath (center-aligned).
        - transform : the coordinate frame (typically axes.transData)
        - sizex,sizey : width of x,y bar, in data units. 0 to omit
        - labelx,labely : labels for x,y bars; None to omit
        - loc : position in containing axes
        - pad, borderpad : padding, in fraction of the legend font size (or prop)
        - sep : separation between labels and bars in points.
        - **kwargs : additional arguments passed to base class constructor
        """
        bars = AuxTransformBox(transform)
        if sizex:
            arr = FancyArrowPatch(
                (0, 0),
                (sizex, 0),
                shrinkA=0,
                shrinkB=0,
                ec=barcolor,
                lw=barwidth,
                fc="none",
                arrowstyle="|-|",
            )
            arr.set_capstyle("butt")

            bars.add_artist(arr)

        if sizey:
            bars.add_artist(
                Rectangle((0, 0),
                          0,
                          sizey,
                          ec=barcolor,
                          lw=barwidth,
                          fc="none"))

        if sizex and labelx:
            self.xlabel = TextArea(labelx, minimumdescent=False)
            bars = VPacker(children=[bars, self.xlabel],
                           align="center",
                           pad=0,
                           sep=sep)
        if sizey and labely:
            self.ylabel = TextArea(labely)
            bars = HPacker(children=[self.ylabel, bars],
                           align="center",
                           pad=0,
                           sep=sep)

        AnchoredOffsetbox.__init__(self,
                                   loc,
                                   pad=pad,
                                   borderpad=borderpad,
                                   child=bars,
                                   prop=prop,
                                   frameon=False,
                                   **kwargs)
Ejemplo n.º 26
0
    def draw(self):
        """
        Draw guide

        Returns
        -------
        out : matplotlib.offsetbox.Offsetbox
            A drawing of this legend
        """
        obverse = slice(0, None)
        reverse = slice(None, None, -1)
        nbreak = len(self.key)
        themeable = self.theme.figure._themeable

        # When there is more than one guide, we keep
        # record of all of them using lists
        if 'legend_title' not in themeable:
            themeable['legend_title'] = []
        if 'legend_text_legend' not in themeable:
            themeable['legend_key'] = []
            themeable['legend_text_legend'] = []

        # title
        title_box = TextArea(self.title, textprops=dict(color='black'))
        themeable['legend_title'].append(title_box)

        # labels
        labels = []
        for item in self.key['label']:
            if isinstance(item, np.float) and np.float.is_integer(item):
                item = np.int(item)  # 1.0 to 1
            va = 'center' if self.label_position == 'top' else 'baseline'
            ta = TextArea(item, textprops=dict(color='black', va=va))
            labels.append(ta)
            themeable['legend_text_legend'].extend(labels)

        # Drawings
        drawings = []
        for i in range(nbreak):
            da = ColoredDrawingArea(self._keywidth[i],
                                    self._keyheight[i],
                                    0,
                                    0,
                                    color='white')
            # overlay geoms
            for gl in self.glayers:
                data = gl.data.iloc[i]
                data.is_copy = None
                da = gl.geom.draw_legend(data, da, gl.layer)
            drawings.append(da)
        themeable['legend_key'].append(drawings)

        # Match Drawings with labels to create the entries
        lookup = {
            'right': (HPacker, reverse),
            'left': (HPacker, obverse),
            'bottom': (VPacker, reverse),
            'top': (VPacker, obverse)
        }
        packer, slc = lookup[self.label_position]
        entries = []
        for d, l in zip(drawings, labels):
            e = packer(children=[l, d][slc],
                       sep=self._label_margin,
                       align='center',
                       pad=0)
            entries.append(e)

        # Put the entries together in rows or columns
        # A chunk is either a row or a column of entries
        # for a single legend
        if self.byrow:
            chunk_size, packers = self.ncol, [HPacker, VPacker]
            sep1 = self._legend_entry_spacing_x
            sep2 = self._legend_entry_spacing_y
        else:
            chunk_size, packers = self.nrow, [VPacker, HPacker]
            sep1 = self._legend_entry_spacing_y
            sep2 = self._legend_entry_spacing_x

        if self.reverse:
            entries = entries[::-1]
        chunks = []
        for i in range(len(entries)):
            start = i * chunk_size
            stop = start + chunk_size
            s = islice(entries, start, stop)
            chunks.append(list(s))
            if stop >= len(entries):
                break

        chunk_boxes = []
        for chunk in chunks:
            d1 = packers[0](
                children=chunk,
                align='left',
                sep=sep1,
                pad=0,
            )
            chunk_boxes.append(d1)

        # Put all the entries (row & columns) together
        entries_box = packers[1](children=chunk_boxes,
                                 align='baseline',
                                 sep=sep2,
                                 pad=0)

        # Put the title and entries together
        packer, slc = lookup[self.title_position]
        children = [title_box, entries_box][slc]
        box = packer(children=children,
                     sep=self._title_margin,
                     align=self._title_align,
                     pad=self._legend_margin)

        return box
Ejemplo n.º 27
0
import numpy as np

from matplotlib.patches import Circle
from matplotlib.offsetbox import (TextArea, DrawingArea, OffsetImage,
                                  AnnotationBbox)
from matplotlib.cbook import get_sample_data


fig, ax = plt.subplots()

# Define a 1st position to annotate (display it with a marker)
xy = (0.5, 0.7)
ax.plot(xy[0], xy[1], ".r")

# Annotate the 1st position with a text box ('Test 1')
offsetbox = TextArea("Test 1", minimumdescent=False)

ab = AnnotationBbox(offsetbox, xy,
                    xybox=(-20, 40),
                    xycoords='data',
                    boxcoords="offset points",
                    arrowprops=dict(arrowstyle="->"))
ax.add_artist(ab)

# Annotate the 1st position with another text box ('Test')
offsetbox = TextArea("Test", minimumdescent=False)

ab = AnnotationBbox(offsetbox, xy,
                    xybox=(1.02, xy[1]),
                    xycoords='data',
                    boxcoords=("axes fraction", "data"),
Ejemplo n.º 28
0
              label=r'Causal precursors ($\alpha=$' + f' {alpha_CI})')
# ax0.set_xticks()
# ax0.set_xticklabels(df_test.index.year,
ax0.set_ylabel('Standardized Soy Yield', fontsize=fontsize)
ax0.tick_params(labelsize=fontsize)
ax0.axhline(y=0, color='black', lw=1)
ax0.legend(fontsize=fontsize)

df_scores = df_test_m.loc[0]['Prediction']
Texts1 = []
Texts2 = []
textprops = dict(color='black', fontsize=fontsize + 4, family='serif')
rename_met = {'RMSE': 'RMSE-SS', 'corrcoef': 'Corr. Coeff.', 'MAE': 'MAE-SS'}
for k, label in rename_met.items():
    val = round(df_scores[k], 2)
    Texts1.append(TextArea(f'{label}', textprops=textprops))
    Texts2.append(TextArea(f'{val}', textprops=textprops))
texts_vbox1 = VPacker(children=Texts1, pad=0, sep=4)
texts_vbox2 = VPacker(children=Texts2, pad=0, sep=4)

ann1 = AnnotationBbox(texts_vbox1, (.02, .15),
                      xycoords=ax0.transAxes,
                      box_alignment=(0, .5),
                      bboxprops=dict(facecolor='white',
                                     boxstyle='round',
                                     edgecolor='white'))
ann2 = AnnotationBbox(texts_vbox2, (.21, .15),
                      xycoords=ax0.transAxes,
                      box_alignment=(0, .5),
                      bboxprops=dict(facecolor='white',
                                     boxstyle='round',
Ejemplo n.º 29
0
    def _init_legend_box(self, handles, labels, markerfirst=True):
        """
        Initialize 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 a HPacker packed with:
        # - handlebox: a DrawingArea which contains the legend handle.
        # - labelbox: a TextArea which contains the legend text.

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

        # The approximate height and descent of text. These values are
        # only used for plotting the legend handle.
        descent = 0.35 * fontsize * (self.handleheight - 0.7)  # heuristic.
        height = fontsize * self.handleheight - descent
        # each handle needs to be drawn inside a box of (x, y, w, h) =
        # (0, -descent, width, height).  And their coordinates should
        # be given in the display coordinates.

        # The transformation of each handle will be automatically set
        # to self.get_transform(). If the artist does not use its
        # default transform (e.g., Collections), you need to
        # manually set their transform to the self.get_transform().
        legend_handler_map = self.get_legend_handler_map()

        for orig_handle, label in zip(handles, labels):
            handler = self.get_legend_handler(legend_handler_map, orig_handle)
            if handler is None:
                _api.warn_external(
                             "Legend does not support handles for {0} "
                             "instances.\nA proxy artist may be used "
                             "instead.\nSee: https://matplotlib.org/"
                             "stable/tutorials/intermediate/legend_guide.html"
                             "#controlling-the-legend-entries".format(
                                 type(orig_handle).__name__))
                # No handle for this artist, so we just defer to None.
                handle_list.append(None)
            else:
                textbox = TextArea(label, multilinebaseline=True,
                                   textprops=dict(
                                       verticalalignment='baseline',
                                       horizontalalignment='left',
                                       fontproperties=self.prop))
                handlebox = DrawingArea(width=self.handlelength * fontsize,
                                        height=height,
                                        xdescent=0., ydescent=descent)

                text_list.append(textbox._text)
                # Create the artist for the legend which represents the
                # original artist/handle.
                handle_list.append(handler.legend_artist(self, orig_handle,
                                                         fontsize, handlebox))
                handles_and_labels.append((handlebox, textbox))

        columnbox = []
        # array_split splits n handles_and_labels into ncol columns, with the
        # first n%ncol columns having an extra entry.  filter(len, ...) handles
        # the case where n < ncol: the last ncol-n columns are empty and get
        # filtered out.
        for handles_and_labels_column \
                in filter(len, np.array_split(handles_and_labels, self._ncol)):
            # pack handlebox and labelbox into itembox
            itemboxes = [HPacker(pad=0,
                                 sep=self.handletextpad * fontsize,
                                 children=[h, t] if markerfirst else [t, h],
                                 align="baseline")
                         for h, t in handles_and_labels_column]
            # pack columnbox
            alignment = "baseline" if markerfirst else "right"
            columnbox.append(VPacker(pad=0,
                                     sep=self.labelspacing * fontsize,
                                     align=alignment,
                                     children=itemboxes))

        mode = "expand" if self._mode == "expand" else "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._legend_box.axes = self.axes
        self.texts = text_list
        self.legendHandles = handle_list
Ejemplo n.º 30
0
 def __init__(self, s, loc, pad=0.4, borderpad=0.5, prop=None, frameon=True):
     self.txt = TextArea(s, minimumdescent=False)
     super(AnchoredText, self).__init__(loc, pad=pad, borderpad=borderpad, child=self.txt, prop=prop, frameon=frameon)