Beispiel #1
0
    def __init__(self, transform, size, label, loc,
                 pad=0.1, borderpad=0.1, sep=2, prop=None, frameon=True):
        """
        Draw a horizontal bar with the size in data coordinate of the give axes.
        A label will be drawn underneath (center-aligned).

        pad, borderpad in fraction of the legend font size (or prop)
        sep in points.
        loc:
            '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
        """
        self.size_bar = AuxTransformBox(transform)
        self.size_bar.add_artist(Rectangle((0, 0), size, 0, fc='none', color='white', lw=3))

        self.txt_label = TextArea(label, dict(color='white', size='x-large', weight='normal'),
                                  minimumdescent=False)

        self._box = VPacker(children=[self.size_bar, self.txt_label],
                            align="center",
                            pad=0, sep=sep)

        AnchoredOffsetbox.__init__(self, loc, pad=pad, borderpad=borderpad,
                                   child=self._box,
                                   prop=prop,
                                   frameon=frameon)
Beispiel #2
0
def generate_title(d_min, d_max, ax):
    '''This generates the title box artist to be added to the top of the map.
    If the title needs to be changed, this is where to do it.

    The dates d_min and d_max should be years.

    If the title location needs to be adjusted, this is where that happens
    (bbox_to_anchor).
    '''
    title = TextArea("Cruises for the U.S. Global Ocean Carbon and Repeat "
            "Hydrography Program, {0}-{1}".format(d_min, d_max), textprops=dict(size=9))
    subtitle_size = 8
    subt1 = TextArea("(", textprops=dict(size=subtitle_size))
    subt2 = TextArea("red italic", textprops=dict(color="r",style="italic",size=subtitle_size))
    subt3 = TextArea("indicates pending cruise;", textprops=dict(size=subtitle_size))
    subt4 = TextArea("grey", textprops=dict(color="grey",size=subtitle_size))
    subt5 = TextArea("indicates completed cruises; black indicates funded cruises)",
            textprops=dict(size=subtitle_size))
    
    subt = HPacker(children=[subt1,subt2,subt3,subt4,subt5], align="center", pad=0,
            sep=2)
    title = VPacker(children=[title,subt], align="center", pad=0, sep=8)
    t = AnchoredOffsetbox(loc=3, child=title, pad=0, bbox_to_anchor=(-0.02, 1.02),
            bbox_transform=ax.transAxes, borderpad=0, frameon=False)
    return t
    def __init__(self,
                 transform,
                 size,
                 label,
                 loc,
                 pad=0.1,
                 borderpad=0.1,
                 sep=2,
                 prop=None,
                 frameon=True):
        """
        Draw a horizontal bar with the size in data coordinate of the given
        axes. A label will be drawn underneath (center-aligned).

        pad, borderpad in fraction of the legend font size (or prop)
        sep in points.
        """
        self.size_bar = AuxTransformBox(transform)
        self.size_bar.add_artist(Line2D([0, size], [0, 0], color="black"))
        self.txt_label = TextArea(label)
        self._box = VPacker(children=[self.size_bar, self.txt_label],
                            align="center",
                            pad=0,
                            sep=sep)
        super().__init__(loc,
                         pad=pad,
                         borderpad=borderpad,
                         child=self._box,
                         prop=prop,
                         frameon=frameon)
Beispiel #4
0
def make_title(title):
    title = title.title()
    area = TextArea(" %s " % title,
                    textprops=dict(color="k", fontweight="bold"))
    viz = DrawingArea(20, 10, 0, 0)
    packed = VPacker(children=[area, viz], align="center", pad=0, sep=0)
    return packed
Beispiel #5
0
def set_ylabel_multicolor(
    ax,
    strings,
    colors,
    anchorpad=0.,
    **kwargs,
):
    """Use multiple colors in the ylabel

    :ax:        (matplotlib.axes) axis to set ylabel
    :strings:   (list of strings) strings for the label
    :colors:    (list of strings) name of colors for the label
    :ancharpad: (float) Pad between the text and the frame as fraction of the font size

    """
    from matplotlib.offsetbox import AnchoredOffsetbox, TextArea, HPacker, VPacker
    boxes = [
        TextArea(text,
                 textprops=dict(color=color,
                                ha='left',
                                va='bottom',
                                rotation=90,
                                **kwargs))
        for text, color in zip(strings[::-1], colors[::-1])
    ]
    ybox = VPacker(children=boxes, align="center", pad=0, sep=5)
    anchored_ybox = AnchoredOffsetbox(loc=3,
                                      child=ybox,
                                      pad=anchorpad,
                                      frameon=False,
                                      bbox_to_anchor=(-0.15, -0.05),
                                      bbox_transform=ax.transAxes,
                                      borderpad=0.)
    ax.add_artist(anchored_ybox)
Beispiel #6
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, frameon=False, **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"))
        if sizey:
            bars.add_artist(Rectangle((0,0), 0, sizey, fc="none"))

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

        res = AnchoredOffsetbox.__init__(self, loc, pad=pad, borderpad=borderpad,
                                   child=bars, prop=prop, frameon=frameon, **kwargs)
        return res
Beispiel #7
0
    def __init__(self,
                 transform,
                 size,
                 label,
                 loc,
                 pad=0.1,
                 borderpad=0.1,
                 sep=2,
                 prop=None,
                 frameon=True):
        """
        Draw a horizontal bar with the size in data coordinate of the give axes.
        A label will be drawn underneath (center-aligned).

        pad, borderpad in fraction of the legend font size (or prop)
        sep in points.
        """
        self.size_bar = AuxTransformBox(transform)
        self.size_bar.add_artist(Rectangle((0, 0), size, 0, fc="none"))

        self.txt_label = TextArea(label, minimumdescent=False)

        self._box = VPacker(children=[self.size_bar, self.txt_label],
                            align="center",
                            pad=0,
                            sep=sep)

        AnchoredOffsetbox.__init__(self,
                                   loc,
                                   pad=pad,
                                   borderpad=borderpad,
                                   child=self._box,
                                   prop=prop,
                                   frameon=frameon)
Beispiel #8
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=None,
        label_kwa={},
        **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).

        Parameters
        ----------
        - 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.offsetbox import AuxTransformBox, HPacker, TextArea, VPacker
        from matplotlib.patches import Rectangle

        bars = AuxTransformBox(transform)
        rect_kwa = {"ec": barcolor, "lw": barwidth, "fc": "none"}
        if sizex:
            bars.add_artist(Rectangle((0, 0), sizex, 0, **rect_kwa))
        if sizey:
            bars.add_artist(Rectangle((0, 0), 0, sizey, **rect_kwa))

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

        AnchoredOffsetbox.__init__(
            self,
            loc,
            pad=pad,
            borderpad=borderpad,
            child=bars,
            prop=prop,
            frameon=False,
            **kwargs,
        )
Beispiel #9
0
def draw_legend(ax, legend, legend_type, legend_title, ith_legend):
    children = []
    children.append(make_title(legend_title))
    viz_handler = legend_viz[legend_type]
    legend_items = sorted(legend.items(), key=operator.itemgetter(1))
    children += [viz_handler(str(lab), col) for col, lab in legend_items]
    box = VPacker(children=children, align="left", pad=0, sep=5)

    # TODO: The vertical spacing between the legends isn't consistent. Should be
    # padded consistently
    anchored_box = AnchoredOffsetbox(
        loc=6,
        child=box,
        pad=0.,
        frameon=False,
        #bbox_to_anchor=(0., 1.02),
        # Spacing goes here
        bbox_to_anchor=(1, 0.8 - 0.35 * ith_legend),
        bbox_transform=ax.transAxes,
        borderpad=1.,
    )
    # Workaround for a bug in matplotlib up to 1.3.1
    # https://github.com/matplotlib/matplotlib/issues/2530
    anchored_box.set_clip_on(False)
    return anchored_box
Beispiel #10
0
def make_gui(img, dataset_name, **kwargs):
    global alphabet
    fig = plt.figure(figsize=kwargs["figsize"])
    from matplotlib import rcParams
    rcParams['axes.linewidth'] = 2
    rcParams['axes.edgecolor'] = 'k'

    plt.imshow(img)

    label_category = cv_label_category if dataset_name == "camvid" else voc_label_category
    alphabet = alphabet_cv if dataset_name == "camvid" else alphabet_voc

    vpacker_children = [TextArea("{} - {}".format(alphabet[l], cat), textprops={"weight": 'bold', "size": 10})
                        for l, cat in sorted(label_category.items(), key=lambda x: x[1])]
    box = VPacker(children=vpacker_children, align="left", pad=5, sep=5)

    # display the texts on the right side of image
    anchored_box = AnchoredOffsetbox(loc="center left",
                                     child=box,
                                     pad=0.,
                                     frameon=True,
                                     bbox_to_anchor=(1.04, 0.5),
                                     bbox_transform=plt.gca().transAxes,
                                     borderpad=0.)
    anchored_box.patch.set_linewidth(2)
    anchored_box.patch.set_facecolor('gray')
    anchored_box.patch.set_alpha(0.2)

    anchored_box.patch.set_boxstyle("round,pad=0.5, rounding_size=0.2")
    plt.gca().add_artist(anchored_box)

    # create texts for "Enter a label for the current marker"
    box1 = TextArea("Enter a label for the current marker",
                    textprops={"weight": 'bold', "size": 12})
    box2 = DrawingArea(5, 10, 0, 0)
    box2.add_artist(mpatches.Circle((5, 5), radius=5, fc=np.array((1, 0, 0)), edgecolor="k", lw=1.5))
    box = HPacker(children=[box1, box2], align="center", pad=5, sep=5)

    # anchored_box creates the text box outside of the plot
    anchored_box = AnchoredOffsetbox(loc="lower center",
                                     child=box,
                                     pad=0.,
                                     frameon=False,
                                     bbox_to_anchor=(0.5, -0.1),  # ( 0.5, -0.1)
                                     bbox_transform=plt.gca().transAxes,
                                     borderpad=0.)
    plt.gca().add_artist(anchored_box)
    plt.xticks([])
    plt.yticks([])
    plt.tight_layout(pad=2)

    buf = io.BytesIO()
    fig.savefig(buf, format="jpg", dpi=80)
    buf.seek(0)
    img_arr = np.frombuffer(buf.getvalue(), dtype=np.uint8)
    buf.close()
    im = cv2.imdecode(img_arr, 1)
    plt.close()
    return im
Beispiel #11
0
 def __init__(self, fields):
     """
     """
     lines = []
     for key, value in fields.items():
         lines.append(
             TextArea(key.upper(), textprops={'color': 'lightgray'}))
         lines.append(
             TextArea('    {}                       '.format(value)))
     pack = VPacker(children=lines, pad=0., sep=2.)
     super().__init__(4, child=pack, borderpad=0.)
     plt.gca().add_artist(self)
def multicolor_ylabel(ax,
                      list_of_strings,
                      list_of_colors,
                      axis='x',
                      anchorpad=0,
                      **kw):
    """this function creates axes labels with multiple colors
    ax specifies the axes object where the labels should be drawn
    list_of_strings is a list of all of the text items
    list_if_colors is a corresponding list of colors for the strings
    axis='x', 'y', or 'both' and specifies which label(s) should be drawn"""
    from matplotlib.offsetbox import AnchoredOffsetbox, TextArea, HPacker, VPacker

    # x-axis label
    if axis == 'x' or axis == 'both':
        boxes = [
            TextArea(text,
                     textprops=dict(color=color, ha='left', va='bottom', **kw))
            for text, color in zip(list_of_strings, list_of_colors)
        ]
        xbox = HPacker(children=boxes, align="center", pad=0, sep=5)
        anchored_xbox = AnchoredOffsetbox(loc=3,
                                          child=xbox,
                                          pad=anchorpad,
                                          frameon=False,
                                          bbox_to_anchor=(0.2, -0.09),
                                          bbox_transform=ax.transAxes,
                                          borderpad=0.)
        ax.add_artist(anchored_xbox)

    # y-axis label
    if axis == 'y' or axis == 'both':
        boxes = [
            TextArea(text,
                     textprops=dict(color=color,
                                    ha='left',
                                    va='bottom',
                                    rotation=90,
                                    **kw))
            for text, color in zip(list_of_strings[::-1], list_of_colors[::-1])
        ]
        ybox = VPacker(children=boxes, align="center", pad=0, sep=5)
        anchored_ybox = AnchoredOffsetbox(loc=3,
                                          child=ybox,
                                          pad=anchorpad,
                                          frameon=False,
                                          bbox_to_anchor=(-0.25, 0.2),
                                          bbox_transform=ax.transAxes,
                                          borderpad=0.)
        ax.add_artist(anchored_ybox)

    return
Beispiel #13
0
def plot_twiss(
    ax,
    twiss,
    *,
    twiss_functions=("beta_x", "beta_y", "eta_x"),
    scales={
        "eta_x": 10,
        "eta_x_dds": 10
    },
    line_style="solid",
    line_width=1.3,
    alpha=1.0,
    show_ylabels=False,
):
    if scales is None:
        scales = {}

    text_areas = []
    for i, function in enumerate(twiss_functions):
        value = getattr(twiss, function)
        label, color = OPTICAL_FUNCTIONS[function]
        scale = scales.get(function)
        if scale is not None:
            label = f"{scale} {label}"
            value = scale * value

        ax.plot(
            twiss.s,
            value,
            color=color,
            linewidth=line_width,
            linestyle=line_style,
            alpha=alpha,
            zorder=10 - i,
            label=label,
        )
        text_areas.insert(
            0, TextArea(label, textprops=dict(color=color, rotation=90)))

    ax.set_xlabel("Orbit Position $s$ / m")
    if show_ylabels:
        ax.add_artist(
            AnchoredOffsetbox(
                child=VPacker(children=text_areas,
                              align="bottom",
                              pad=0,
                              sep=20),
                loc="center left",
                bbox_to_anchor=(-0.125, 0, 1.125, 1),
                bbox_transform=ax.transAxes,
                frameon=False,
            ))
Beispiel #14
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)
Beispiel #15
0
def _plot_val_sens_specif_auc(validation_aucs,
                              validation_recalls,
                              validation_specifs):
    """ Plots training and validation auc roc score in same figure.

        Args:
            validation_aucs (list)
            validation_recalls (list)
            validation_specifs (list)
    """
    color = 'tab:red'
    num_val_aucs = np.arange(0, len(validation_aucs), 1)

    fig, ax1 = plt.subplots()
    fig.set_size_inches(12, 6)
    ax1.set_xlabel('Epochs')
    ax1.set_ylabel('Validation AUC', color=color)
    ax1.plot(num_val_aucs, validation_aucs, color=color)
    ax1.tick_params(axis='y', labelcolor=color)
    ax1.set_ylim([0.0, 1.1])

    ax2 = ax1.twinx()
    ax2.set_ylim([0.0, 1.1])


    ybox1 = TextArea("Sensitivity ", textprops=dict(color='tab:blue',
                                                    rotation=90, ha='left',
                                                    va='bottom'))
    ybox2 = TextArea("and ", textprops=dict(color="k", rotation=90, ha='left',
                                            va='bottom'))
    ybox3 = TextArea("Specificity ", textprops=dict(color='xkcd:azure',
                                                    rotation=90, ha='left',
                                                    va='bottom'))

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

    anchored_ybox = AnchoredOffsetbox(loc=8, child=ybox, pad=0., frameon=False,
                                      bbox_to_anchor=(1.13, 0.25),
                                      bbox_transform=ax2.transAxes, borderpad=0.)

    ax2.add_artist(anchored_ybox)

    color = 'tab:blue'
    ax2.plot(num_val_aucs, validation_recalls, color=color)
    ax2.plot(num_val_aucs, validation_specifs, color='xkcd:azure')

    ax2.tick_params(axis='y', labelcolor=color)

    fig.tight_layout()
    plt.show()
Beispiel #16
0
    def _set_annotation_box(self):
        """pack the HPackers of each row vertically into a VPacker and create an AnnotationBBox"""
        self._vpacker = VPacker(children=self._hpackers,
                                pad=self._vpad,
                                sep=self._vsep,
                                align=self._text_align)
        self.annotation_bbox = AnnotationBbox(self._vpacker,
                                              (self._x, self._y),
                                              xybox=self._xybox,
                                              box_alignment=self.box_alignment,
                                              **self._annotationbbox_kw)

        if self._add_artist:
            self.ax.add_artist(self.annotation_bbox)
            self.set_renderer()
Beispiel #17
0
def draw_som_clusters():
    global som_data
    global som_table
    global annot_ticks
    global som_headers
    if(grid_type.lower()=="rectangular"):
        for i in range(0,len(som_data)): 
            som_table[int(som_data[i][0])][int(som_data[i][1])]=som_data[i][len(som_data[0])-1]
        ax = sns.heatmap(som_table.transpose(), cmap=discrete_cmap, linewidth=0, vmin=-0.5, vmax=clusters-0.5, center=clusters/2-0.5, cbar_kws=dict(ticks=cluster_ticks), annot=annot_ticks.transpose(), fmt = '')
    else:
        hits=som_data[:,len(som_data[0])-1]
        mpl.rcParams.update({'font.size': 30})
        ax = plot_hexa(grid, hits,colmap=discrete_cmap_2, ptype='grid')
    ax.set_title(som_headers[len(som_headers)-1])
    ax.figure.savefig(working_dir+'/Som/somplot_' + str(len(som_data[0])-2) + '.png')
    plt.clf()
    plt.cla()
    plt.close()
    mpl.rcParams.update({'font.size': 12})  
    if(labelIndex!="-2"):
        fig = plt.figure()
        ax1 = fig.add_subplot(211) # Creates another plot image and turns visibility of the axes off
        ax1.axis('off')
        children=[]
        for text in annot_strings:
            children.append(TextArea(annot_strings[text], textprops=dict(color="red")))
            #print(annot_strings[text])
        box = VPacker(children=children, align="left", pad=5, sep=5)

        # anchored_box creates the text box outside of the plot
        anchored_box = AnchoredOffsetbox(loc=3,
                                            child=box, pad=0.,
                                            frameon=True,
                                            bbox_to_anchor=(0.01, 0.01),
                                            bbox_transform=ax.transAxes,
                                            borderpad=0.,
                                            )
        ax1.add_artist(anchored_box)
        ax1.figure.savefig(working_dir+'/Som/somplot_' + str(len(som_data[0])-1) + '.png')
        plt.clf()
        plt.cla()
        plt.close()
        df = pd.DataFrame(annot_data)
        headers = ["label", "som", "datapoint"]
        df.to_csv(working_dir+'/labels.csv', index=False, header=headers)
Beispiel #18
0
def multicolor_label(ax,
                     list_of_strings,
                     list_of_colors,
                     axis='x',
                     anchorpad=0,
                     bbox_to_anchor=(0, 0),
                     **kw):
    from matplotlib.offsetbox import AnchoredOffsetbox, TextArea, HPacker, VPacker

    # x-axis label
    if axis == 'x' or axis == 'both':
        boxes = [
            TextArea(text,
                     textprops=dict(color=color, ha='left', va='bottom', **kw))
            for text, color in zip(list_of_strings, list_of_colors)
        ]
        xbox = HPacker(children=boxes, align="center", pad=0, sep=5)
        anchored_xbox = AnchoredOffsetbox(loc='center left',
                                          child=xbox,
                                          pad=anchorpad,
                                          frameon=False,
                                          bbox_to_anchor=bbox_to_anchor,
                                          bbox_transform=ax.transAxes,
                                          borderpad=0.)
        ax.add_artist(anchored_xbox)

    # y-axis label
    if axis == 'y' or axis == 'both':
        boxes = [
            TextArea(text,
                     textprops=dict(color=color, ha='left', va='center', **kw))
            for text, color in zip(list_of_strings[::-1], list_of_colors)
        ]
        ybox = VPacker(children=boxes, align='center', pad=0, sep=5)
        anchored_ybox = AnchoredOffsetbox(loc='center left',
                                          child=ybox,
                                          pad=anchorpad,
                                          frameon=False,
                                          bbox_to_anchor=bbox_to_anchor,
                                          bbox_transform=ax.transAxes,
                                          borderpad=0.)
        ax.add_artist(anchored_ybox)
Beispiel #19
0
def draw_legend_group(legends, column_name, ith_group):
    labels = get_legend_labels(legends)
    colors, has_color = get_colors(legends)
    alphas, has_alpha = get_alphas(legends)
    legend_title = make_title(column_name)
    legend_labels = [make_label(l) for l in labels]
    none_dict = defaultdict(lambda: None)
    legend_cols = []

    # Draw shapes if any (discs for sizes)
    if "shape" in legends or "size" in legends:
        shapes = legends["shape"] if "shape" in legends else none_dict
        sizes = legends["size"] if "size" in legends else none_dict
        line = lambda l: make_shape(colors[l], shapes[l], sizes[l], alphas[l])
        legend_shapes = [line(label) for label in labels]
        legend_cols.append(legend_shapes)

    # Draw lines if any
    if "linetype" in legends:
        linetypes = legends["linetype"]
        legend_lines = [
            make_line(colors[l], linetypes[l], alphas[l]) for l in labels
        ]
        legend_cols.append(legend_lines)

    # If we don't have lines, legends or sizes, indicate color with a rectangle
    already_drawn = set(["linetype", "shape", "size"])
    if (len(already_drawn.intersection(legends)) == 0
            and (has_color or has_alpha)):
        legend_rects = [make_rect(colors[l], alphas[l]) for l in labels]
        legend_cols.append(legend_rects)

    # Concatenate columns and compile rows
    legend_cols.append(legend_labels)
    row = lambda l: HPacker(
        children=l, height=25, align='center', pad=5, sep=0)
    legend_rows = [row(legend_items) for legend_items in zip(*legend_cols)]

    # Vertically align items and anchor in plot
    rows = [legend_title] + legend_rows
    box = VPacker(children=rows, align="left", pad=0, sep=-10)
    return box, len(rows)
Beispiel #20
0
def plot_ylabel(ax, list_of_strings, list_of_colors, **kw):
    from matplotlib.offsetbox import AnchoredOffsetbox, TextArea, HPacker, VPacker
    bbox_anchor = (-0.07, 0.05) if len(list_of_strings) == 2 else (-0.07, 0.25)
    boxes = [
        TextArea(text,
                 textprops=dict(color=color,
                                ha='left',
                                va='bottom',
                                rotation=90,
                                **kw))
        for text, color in zip(list_of_strings, list_of_colors)
    ]
    ybox = VPacker(children=boxes, align="center", pad=0, sep=5)
    anchored_ybox = AnchoredOffsetbox(loc=3,
                                      child=ybox,
                                      pad=0,
                                      frameon=False,
                                      bbox_to_anchor=bbox_anchor,
                                      bbox_transform=ax.transAxes,
                                      borderpad=0)
    ax.add_artist(anchored_ybox)
Beispiel #21
0
def draw_legend(ax, legend, legend_type, ith_legend):
    children = []
    children.append(make_title(legend_type))
    viz_handler = legend_viz[legend_type]
    legend_items = sorted(legend.iteritems(), key=operator.itemgetter(1))
    children += [viz_handler(lab, col) for col, lab in legend_items]
    box = VPacker(children=children, align="left", pad=0, sep=5)

    # TODO: The vertical spacing between the legends isn't consistent. Should be
    # padded consistently
    anchored_box = AnchoredOffsetbox(
        loc=6,
        child=box,
        pad=0.,
        frameon=True,
        #bbox_to_anchor=(0., 1.02),
        # Spacing goes here
        bbox_to_anchor=(1, 0.8 - 0.35 * ith_legend),
        bbox_transform=ax.transAxes,
        borderpad=1.,
    )
    return anchored_box
Beispiel #22
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, **kwargs):
     
     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"))
     if sizey:
         bars.add_artist(Rectangle((0,0), 0, sizey, fc="none"))
     
     if sizex and labelx:
         bars = VPacker(children=[bars, TextArea(labelx, minimumdescent=False)],
                        align="center", pad=0, sep=sep)
     if sizey and labely:
         bars = HPacker(children=[TextArea(labely), bars],
                         align="center", pad=0, sep=sep)
     
     AnchoredOffsetbox.__init__(self, loc, pad=pad, borderpad=borderpad,
                                child=bars, prop=prop, frameon=False, **kwargs)
Beispiel #23
0
    def _init_legend_box(self, handles, labels):
        """
        Initiallize the legend_box. The legend_box is an instance of
        the OffsetBox, which is packed with legend handles and
        texts. Once packed, their location is calculated during the
        drawing time.
        """

        fontsize = self.fontsize

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

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

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

        labelboxes = []

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

        handleboxes = []

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

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

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

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

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

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

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

                handle_list.append(legline)

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

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

            elif isinstance(handle, RegularPolyCollection):

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

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

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

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

            else:
                handle_list.append(None)

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

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

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

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

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

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

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

        sep = self.columnspacing * fontsize

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

        self._legend_box.set_figure(self.figure)

        self.texts = text_list
        self.legendHandles = handle_list
Beispiel #24
0
    def draw(self, renderer, *args, **kwargs):
        if not self.get_visible():
            return
        if not self.get_mappable():
            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('colorbar.' + attr, default)
            return value

        orientation = _get_value('orientation', 'vertical')
        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, 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)
        font_properties = self.font_properties
        ticklocation = _get_value('ticklocation', 'auto')
        if ticklocation == 'auto':
            ticklocation = 'bottom' if orientation == 'horizontal' else 'right'

        mappable = self.mappable
        cmap = self.mappable.get_cmap()
        norm = self.mappable.norm
        label = self.label
        ticks = self.ticks
        ticklabels = self.ticklabels

        ax = self.axes

        # Calculate
        calculator = ColorbarCalculator(mappable,
                                        ticks=ticks,
                                        ticklabels=ticklabels)

        X, Y, C = calculator.calculate_colorbar()
        X *= width_fraction
        Y *= length_fraction
        widths = np.diff(X, axis=1)[:, 0]
        heights = np.diff(Y[:, 0])
        if orientation == 'horizontal':
            X, Y = Y, X
            widths, heights = heights, widths

        ticks, ticklabels, offset_string = calculator.calculate_ticks()
        ticks *= length_fraction

        # Create colorbar
        colorbarbox = AuxTransformBox(ax.transAxes)

        patches = []
        for x0, y0, width, height in zip(X[:-1, 0], Y[:-1, 0], widths,
                                         heights):
            patch = Rectangle((x0, y0), width, height)
            patches.append(patch)

        edgecolors = 'none'  #if self.drawedges else 'none'
        #FIXME: drawedge property
        #FIXME: Filled property
        col = PatchCollection(patches,
                              cmap=cmap,
                              edgecolors=edgecolors,
                              norm=norm)
        col.set_array(C[:, 0])
        colorbarbox.add_artist(col)

        # Create outline
        if orientation == 'horizontal':
            outline = Rectangle((0, 0),
                                length_fraction,
                                width_fraction,
                                fill=False,
                                ec=color)
        else:
            outline = Rectangle((0, 0),
                                width_fraction,
                                length_fraction,
                                fill=False,
                                ec=color)
        colorbarbox.add_artist(outline)

        # Create ticks and tick labels
        w10th = width_fraction / 10.0
        ticklines = []
        ticktexts = []
        for tick, ticklabel in zip(ticks, ticklabels):
            if ticklocation == 'bottom':
                x0 = x1 = xtext = tick
                y0 = w10th
                y1 = -w10th
                ytext = -2 * w10th
                ha = 'center'
                va = 'top'
            elif ticklocation == 'top':
                x0 = x1 = xtext = tick
                y0 = width_fraction - w10th
                y1 = width_fraction + w10th
                ytext = width_fraction + 2 * w10th
                ha = 'center'
                va = 'bottom'
            elif ticklocation == 'left':
                x0 = w10th
                x1 = -w10th
                xtext = -2 * w10th
                y0 = y1 = ytext = tick
                ha = 'right'
                va = 'center'
            elif ticklocation == 'right':
                x0 = width_fraction - w10th
                x1 = width_fraction + w10th
                xtext = width_fraction + 2 * w10th
                y0 = y1 = ytext = tick
                ha = 'left'
                va = 'center'

            ticklines.append([(x0, y0), (x1, y1)])

            ticklabel = offset_string + ticklabel
            ticktext = Text(xtext,
                            ytext,
                            ticklabel,
                            color=color,
                            fontproperties=font_properties,
                            horizontalalignment=ha,
                            verticalalignment=va)
            ticktexts.append(ticktext)

        col = LineCollection(ticklines, color=color)
        colorbarbox.add_artist(col)

        for ticktext in ticktexts:
            colorbarbox.add_artist(ticktext)

        # Create label
        if label:
            labelbox = AuxTransformBox(ax.transAxes)

            va = 'baseline' if orientation == 'horizontal' else 'center'
            text = Text(0,
                        0,
                        label,
                        fontproperties=font_properties,
                        verticalalignment=va,
                        rotation=orientation,
                        color=color)
            labelbox.add_artist(text)
        else:
            labelbox = None

        # Create final offset box
        if ticklocation == 'bottom':
            children = [colorbarbox, labelbox] if labelbox else [colorbarbox]
            child = VPacker(children=children, align='center', pad=0, sep=sep)
        elif ticklocation == 'top':
            children = [labelbox, colorbarbox] if labelbox else [colorbarbox]
            child = VPacker(children=children, align='center', pad=0, sep=sep)
        elif ticklocation == 'left':
            children = [labelbox, colorbarbox] if labelbox else [colorbarbox]
            child = HPacker(children=children, align='center', pad=0, sep=sep)
        elif ticklocation == 'right':
            children = [colorbarbox, labelbox] if labelbox else [colorbarbox]
            child = HPacker(children=children, align='center', pad=0, sep=sep)


#
        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)
Beispiel #25
0
def plot_cell(show=True, save=False):
    """Makes total cell"""

    # Get the angles
    t_c, t_ld, t_sd, t_d, t_f = get_angles()

    # Get the distances - cosmetic
    r0 = 0.3
    r1 = 0.5

    # Define the fig and axes for the graph
    fig = plt.figure()
    ax = fig.add_subplot(projection='polar')
    ax.set_thetamin(0)
    ax.set_thetamax(60)
    ax.grid(axis='y')
    ax.set_title("Layout of KURRI Main Ring", fontsize=16)
    t_ticks = [0, 5, 10, 15, 20, 25, 30]
    plt.xticks(
        np.array(t_ticks) * TO_RAD * 2, [fr'${t}\degree$' for t in t_ticks])
    plt.yticks([])
    ax.set_ylim(0, r1 + 0.1)

    # Make wedge to contain the entire cell
    #plot_segment(ax, 0, r1+0.1, 0, 0, ls='--', lw=1.5)
    #plot_segment(ax, 0, r1+0.1, t_c, t_c, ls='--', lw=1.5)

    # Make the F and D magnets
    t_d1_start = t_ld
    t_f_start = t_d1_start + t_d + t_sd
    t_d2_start = t_f_start + t_f + t_sd
    plot_wedge(ax,
               r0,
               r1,
               t_d1_start,
               t_d1_start + t_d,
               col='royalblue',
               label='D Magnet')  # First D magnet
    plot_wedge(ax,
               r0,
               r1,
               t_f_start,
               t_f_start + t_f,
               col='firebrick',
               label='F Magnet')  # F magnet
    plot_wedge(ax, r0, r1, t_d2_start, t_d2_start + t_d,
               col='royalblue')  # Second D magnet

    # Plot arrows to show dimensions
    plot_ang_arrow(ax, 0.1, 0, t_c, r'$\theta_{C}$', headsize=0)
    r_arr = r1 + 0.025
    plot_ang_arrow(ax, r_arr, 0, t_ld, r'$\theta_{LD}$')
    plot_ang_arrow(ax, r_arr, t_d1_start, t_d1_start + t_d, r'$\theta_{D}$')
    plot_ang_arrow(ax, r_arr, t_d1_start + t_d, t_d1_start + t_d + t_sd,
                   r'$\theta_{SD}$')
    plot_ang_arrow(ax, r_arr, t_f_start, t_f_start + t_f / 2,
                   r'$\theta_{F}/2$')

    plot_rad_arrow(ax, 0, r0, t_d2_start + t_d, r'$r_0$')
    plot_rad_arrow(ax, 0, r1, t_d2_start + t_d, r'$r_1$')

    # Write in the values of angles and lengths using artists
    text = [
        fr'$\theta_C$', fr'$\theta_{"{LD}"}$', fr'$\theta_D$',
        fr'$\theta_{"{SD}"}$', fr'$\theta_F$'
    ]
    val = [rf'$= {v}\degree$' for v in [t_c, t_ld, t_d, t_sd, t_f]]
    Texts = [TextArea(t) for t in text]
    Vals = [TextArea(v) for v in val]
    textbox = VPacker(children=Texts, pad=0.1, sep=0.1)
    valsbox = VPacker(children=Vals, pad=0.1,
                      sep=2.4)  # This 'sep' is fine-tuned to make boxes align!
    totbox = HPacker(children=[textbox, valsbox], pad=0.1, sep=0.1)
    ann = AnnotationBbox(totbox, (0.05, 0.8),
                         xycoords=ax.transAxes,
                         box_alignment=(0.05, 0.8),
                         bboxprops=dict(facecolor='wheat',
                                        boxstyle='round',
                                        color='black'))
    ann.set_figure(fig)
    fig.artists.append(ann)

    text2 = [r'$r_0$', r'$r_1$']
    val2 = [r'$= 4.3$m', r'$= 5.4$m']
    Texts2 = [TextArea(t) for t in text2]
    Vals2 = [TextArea(v) for v in val2]
    textbox2 = VPacker(children=Texts2, pad=0.1, sep=0.1)
    valsbox2 = VPacker(children=Vals2, pad=0.1,
                       sep=1)  # This 'sep' is fine-tuned to make boxes align!
    totbox2 = HPacker(children=[textbox2, valsbox2], pad=0.1, sep=0.1)
    ann2 = AnnotationBbox(totbox2, (0.05, 0.5),
                          xycoords=ax.transAxes,
                          box_alignment=(0.05, 0.5),
                          bboxprops=dict(facecolor='wheat',
                                         boxstyle='round',
                                         color='black'))
    ann2.set_figure(fig)
    fig.artists.append(ann2)

    # Legend
    ax.legend(loc=(0.75, 0.8), facecolor='lavenderblush', edgecolor='k')

    #Misc
    fig.tight_layout()
    if save:
        fig.savefig('figs/KURRI_layout.png')
        fig.savefig('figs/KURRI_layout.pdf')
    if show:
        fig.show()

    return fig, ax
    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, optional, default: 0.1
            Padding around the label and size bar, in fraction of the font
            size.

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

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

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

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

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

        label_top : bool, optional, 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,
                                  minimumdescent=False,
                                  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)

        AnchoredOffsetbox.__init__(self,
                                   loc,
                                   pad=pad,
                                   borderpad=borderpad,
                                   child=self._box,
                                   prop=fontproperties,
                                   frameon=frameon,
                                   **kwargs)
Beispiel #27
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 {!r} instances.\nA proxy artist "
                    "may be used instead.\nSee: "
                    "https://matplotlib.org/users/legend_guide.html"
                    "#creating-artists-specifically-for-adding-to-the-legend-"
                    "aka-proxy-artists".format(orig_handle))
                # 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
Beispiel #28
0
def cornertext(text, loc=2, color=None, frameon=False, axes=None, **kwargs):
    """
    Conveniently places text in a corner of a plot.

    Parameters
    ----------
    text: string or tuple of strings
      Text to be placed in the plot. May be a tuple of strings to get
      several lines of text.
    loc: integer or string
      Location of text, same as in legend(...).
    frameon: boolean (optional)
      Whether to draw a border around the text. Default is False.
    axes: Axes (optional, default: None)
      Axes object which houses the text (defaults to the current axes).
    fontproperties: matplotlib.font_manager.FontProperties object
      Change the font style.

    Other keyword arguments are forwarded to the text instance.

    Authors
    -------
    Hans Dembinski <*****@*****.**>
    """

    from matplotlib.offsetbox import AnchoredOffsetbox, VPacker, TextArea
    from matplotlib import rcParams
    from matplotlib.font_manager import FontProperties
    import warnings

    if axes is None:
        from matplotlib import pyplot as plt
        axes = plt.gca()

    locTranslate = {
        '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
    }

    if isinstance(loc, str):
        if loc in locTranslate:
            loc = locTranslate[loc]
        else:
            message = ('Unrecognized location "{0:s}". Falling back on ' +
                       '"upper left"; valid locations are\n\t{1:s}').format(
                           loc, '\n\t'.join(locTranslate.keys()))
            warnings.warn(message)
            loc = 2

    if "borderpad" in kwargs:
        borderpad = kwargs["borderpad"]
    else:
        borderpad = rcParams["legend.borderpad"]

    if "borderaxespad" in kwargs:
        borderaxespad = kwargs["borderaxespad"]
    else:
        borderaxespad = rcParams["legend.borderaxespad"]

    if "handletextpad" in kwargs:
        handletextpad = kwargs["handletextpad"]
    else:
        handletextpad = rcParams["legend.handletextpad"]

    if "fontproperties" in kwargs:
        fontproperties = kwargs["fontproperties"]  # @UnusedVariable
        del kwargs["fontproperties"]
    else:
        if "size" in kwargs:
            size = kwargs["size"]
            del kwargs["size"]
        elif "fontsize" in kwargs:
            size = kwargs["fontsize"]
            del kwargs["fontsize"]
        else:
            size = rcParams["legend.fontsize"]
    fontproperties = FontProperties(size=size)

    texts = [text] if isinstance(text, str) else text

    colors = [color for t in texts] if (isinstance(color, str)
                                        or color is None) else color

    tas = []
    for t, c in zip(texts, colors):
        ta = TextArea(t,
                      textprops={
                          "color": c,
                          "fontproperties": fontproperties
                      },
                      multilinebaseline=True,
                      minimumdescent=True,
                      **kwargs)
        tas.append(ta)

    vpack = VPacker(children=tas, pad=0, sep=handletextpad)

    aob = AnchoredOffsetbox(loc,
                            child=vpack,
                            pad=borderpad,
                            borderpad=borderaxespad,
                            frameon=frameon)

    axes.add_artist(aob)
    return aob
Beispiel #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 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)

                # 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
Beispiel #30
0
    def __init__(self,
                 ax,
                 transform,
                 width,
                 height,
                 zorder,
                 xlabel,
                 fc,
                 ylabels=None,
                 loc=4,
                 fontsize=5,
                 pad=0.1,
                 borderpad=0.1,
                 sep=2,
                 prop=None,
                 add_ruler=False,
                 ruler_unit='Km',
                 ruler_unit_fontsize=7,
                 ruler_fontweight='bold',
                 tick_fontweight='light',
                 **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
        """

        if ruler_unit_fontsize is None:
            ruler_unit_fontsize = fontsize * 1.5

        Rect = Rectangle(
            (0, 0),
            width,
            height,
            fc=fc,
            edgecolor='k',
            zorder=zorder,
        )

        ATB = AuxTransformBox(transform)

        ATB.add_artist(Rect)

        Txt_xlabel = TextArea(xlabel,
                              textprops=dict(fontsize=fontsize,
                                             fontweight=tick_fontweight),
                              minimumdescent=True)

        # vertically packing a single stripe with respective label

        child = VPacker(children=[Txt_xlabel, ATB],
                        align="right",
                        pad=5,
                        sep=0)

        if add_ruler:

            Text = TextArea(ruler_unit,
                            textprops=dict(fontsize=ruler_unit_fontsize,
                                           fontweight=ruler_fontweight))

            child = VPacker(children=[child, Text],
                            align="center",
                            pad=5,
                            sep=0)

        else:

            Text = TextArea('', textprops=dict(fontsize=ruler_unit_fontsize))

            child = VPacker(children=[child, Text],
                            align="right",
                            pad=5,
                            sep=0)

        # horizontally packing all child packs in a single offsetBox

        AnchoredOffsetbox.__init__(self,
                                   loc='center left',
                                   borderpad=borderpad,
                                   child=child,
                                   prop=prop,
                                   frameon=False,
                                   **kwargs)