Example #1
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)
def test_offsetbox_clipping():
    # - create a plot
    # - put an AnchoredOffsetbox with a child DrawingArea
    #   at the center of the axes
    # - give the DrawingArea a gray background
    # - put a black line across the bounds of the DrawingArea
    # - see that the black line is clipped to the edges of
    #   the DrawingArea.
    fig, ax = plt.subplots()
    size = 100
    da = DrawingArea(size, size, clip=True)
    bg = mpatches.Rectangle((0, 0),
                            size,
                            size,
                            facecolor='#CCCCCC',
                            edgecolor='None',
                            linewidth=0)
    line = mlines.Line2D([-size * .5, size * 1.5], [size / 2, size / 2],
                         color='black',
                         linewidth=10)
    anchored_box = AnchoredOffsetbox(loc='center',
                                     child=da,
                                     pad=0.,
                                     frameon=False,
                                     bbox_to_anchor=(.5, .5),
                                     bbox_transform=ax.transAxes,
                                     borderpad=0.)

    da.add_artist(bg)
    da.add_artist(line)
    ax.add_artist(anchored_box)
    ax.set_xlim((0, 1))
    ax.set_ylim((0, 1))
Example #3
0
    def draw(self, x=None, y=None):
        """
        Docstring
        """
        # https://stackoverflow.com/questions/33159134/matplotlib-y-axis-label-with-multiple-colors

        if x is None:
            x = self.x
        if y is None:
            y = self.y
        if (x is None) and (y is None):
            raise Exception('No x,y arguments passed!')

        xy_px = self._get_xy_px(x, y)
        y_incr_px = self._get_y_increment()
        boxes = self.boxes

        for box in boxes[::-1]:
            x, y = self.transform.inverted().transform(xy_px)
            anchored_xbox = AnchoredOffsetbox(loc=3,
                                              child=box,
                                              pad=0,
                                              frameon=False,
                                              bbox_to_anchor=(x, y),
                                              bbox_transform=self.transform,
                                              borderpad=0)
            self.parent.add_artist(anchored_xbox)
            xy_px[1] += y_incr_px

        self.children = [
            textarea.get_children() for box in boxes
            for textarea in box.get_children()
        ]

        return self.children
Example #4
0
    def add_image_inset(self, filename, loc=4, zoom=1, transpose=False):
        """
        Add a raster image to the plot, according to the legend location loc.
        :param filename: image's file name
        :param loc: an integer specifying the location.
        The 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,
        :param zoom: scaling factor of the image
        :param transpose: Transpose the image.

        """
        arr_eps = plt.imread(filename)
        if transpose:
            arr_eps = arr_eps.transpose((1, 0, 2))
        imagebox = OffsetImage(arr_eps, zoom=zoom)
        ab = AnchoredOffsetbox(loc=loc, child=imagebox, frameon=False)
        self._ax.add_artist(ab)
Example #5
0
def add_offsetboxes(ax, size=10, margin=.1, color='black'):
    """
    Surround ax with OffsetBoxes
    """
    m, mp = margin, 1 + margin
    anchor_points = [(-m, -m), (-m, .5), (-m, mp), (mp, .5), (.5, mp),
                     (mp, mp), (.5, -m), (mp, -m), (.5, -m)]
    for point in anchor_points:
        da = DrawingArea(size, size)
        background = Rectangle((0, 0),
                               width=size,
                               height=size,
                               facecolor=color,
                               edgecolor='None',
                               linewidth=0,
                               antialiased=False)
        da.add_artist(background)

        anchored_box = AnchoredOffsetbox(loc='center',
                                         child=da,
                                         pad=0.,
                                         frameon=False,
                                         bbox_to_anchor=point,
                                         bbox_transform=ax.transAxes,
                                         borderpad=0.)
        ax.add_artist(anchored_box)
    return anchored_box
def multicolor_xlabel(ax,
                      list_of_strings,
                      list_of_colors,
                      h=0.0,
                      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

    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="bottom", pad=0, sep=5)
    anchored_xbox = AnchoredOffsetbox(loc=3,
                                      child=xbox,
                                      pad=anchorpad,
                                      frameon=False,
                                      bbox_to_anchor=(0, h),
                                      bbox_transform=ax.transAxes,
                                      borderpad=0.)
    ax.add_artist(anchored_xbox)
Example #7
0
def multicolor_label(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="bottom", pad=0, sep=20)
        anchored_xbox = AnchoredOffsetbox(
            loc="center",
            child=xbox,
            pad=anchorpad,
            frameon=False,
            bbox_to_anchor=(0.5, -0.12),
            bbox_transform=ax.transAxes,
            borderpad=0.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)
        ]
        ybox = VPacker(children=boxes, align="center", pad=0, sep=20)
        anchored_ybox = AnchoredOffsetbox(
            loc=3,
            child=ybox,
            pad=anchorpad,
            frameon=False,
            bbox_to_anchor=(-0.12, 0.5),
            bbox_transform=ax.transAxes,
            borderpad=0.0,
        )
        ax.add_artist(anchored_ybox)
Example #8
0
def draw_circles(ax):
    """Draw circles in axes coordinates."""
    area = DrawingArea(40, 20, 0, 0)
    area.add_artist(Circle((10, 10), 10, fc="tab:blue"))
    area.add_artist(Circle((30, 10), 5, fc="tab:red"))
    box = AnchoredOffsetbox(
        child=area, loc="upper right", pad=0, frameon=False)
    ax.add_artist(box)
Example #9
0
def logo_box(x, y):
	
	logo_offset_image = OffsetImage(read_png(get_sample_data(logo_location, asfileobj=False)), zoom=0.31, resample=1, dpi_cor=1)
	text_box = TextArea(logo_text, textprops=dict(color='#444444', fontsize=73, weight='bold'))

	logo_and_text_box = HPacker(children=[logo_offset_image, text_box], align="center", pad=0, sep=25)

	anchored_box = AnchoredOffsetbox(loc=2, child=logo_and_text_box, pad=0.8, frameon=False, borderpad=0., bbox_to_anchor=[x, y], bbox_transform = plt.gcf().transFigure)

	return anchored_box
Example #10
0
    def logo_box(self):
        
        logo_offset_image = OffsetImage(read_png(get_sample_data(logo_location, asfileobj=False)), zoom=0.27, resample=1, dpi_cor=1)
        text_box = TextArea("Preliminary (10 \%)", textprops=dict(color='#444444', fontsize=60, weight='bold'))
        #print(text_box)
        logo_and_text_box = HPacker(children=[logo_offset_image, text_box], align="center", pad=0, sep=15)

        anchored_box = AnchoredOffsetbox(loc=2, child=logo_and_text_box, pad=0.8, frameon=False, borderpad=0., bbox_to_anchor=[0.159, 1.0], bbox_transform = plt.gcf().transFigure)

        return anchored_box
Example #11
0
def export_panel(plitem, ax):
    """
    export_panel recreates the contents of one pyqtgraph PlotItem into a specified
    matplotlib axis item.
    Handles PlotItem types of PlotCurveItem, PlotDataItem, BarGraphItem, and ScatterPlotItem
    :param plitem: The PlotItem holding a single plot
    :param ax: the matplotlib axis to put the result into
    :return: Nothing
    """
    # get labels from the pyqtgraph PlotItems
    xlabel = plitem.axes['bottom']['item'].label.toPlainText()
    ylabel = plitem.axes['left']['item'].label.toPlainText()
    title = remove_html_markup(plitem.titleLabel.text)
    label = remove_html_markup(plitem.plotLabel.text)
    fontsize = 12
    fn = pg.functions
    ax.clear()
    cleanAxes(ax)  # make a "nice" plot
    ax.set_title(title)  # add the plot title here
    for item in plitem.items:  # was .curves, but let's handle all items
        # dispatch do different routines depending on what we need to plot
        if isinstance(item, pg.graphicsItems.PlotCurveItem.PlotCurveItem):
            export_curve(fn, ax, item)
        elif isinstance(item, pg.graphicsItems.PlotDataItem.PlotDataItem):
            export_curve(fn, ax, item)
        elif isinstance(item, pg.graphicsItems.BarGraphItem.BarGraphItem):
            export_bargraph(fn, ax, item)
        elif isinstance(item,
                        pg.graphicsItems.ScatterPlotItem.ScatterPlotItem):
            export_scatterplot(fn, ax, item)
        else:
            print 'unknown item encountered : ', item
            continue
    xr, yr = plitem.viewRange()
    # now clean up the matplotlib/pylab plot and annotations
    ax.set_xbound(*xr)
    ax.set_ybound(*yr)
    at = TextArea(label,
                  textprops=dict(color="k",
                                 verticalalignment='bottom',
                                 weight='bold',
                                 horizontalalignment='right',
                                 fontsize=fontsize,
                                 family='sans-serif'))
    box = HPacker(children=[at], align="left", pad=0, sep=2)
    ab = AnchoredOffsetbox(loc=3,
                           child=box,
                           pad=0.,
                           frameon=False,
                           bbox_to_anchor=(-0.08, 1.1),
                           bbox_transform=ax.transAxes,
                           borderpad=0.)
    ax.add_artist(ab)
    ax.set_xlabel(xlabel)  # place the axis labels.
    ax.set_ylabel(ylabel)
Example #12
0
def draw_figure(popularity, data):
  # init figure
  fig, ax = plt.subplots(constrained_layout=True, figsize=(7,7))
  # pie plot
  wedges,_,texts = ax.pie([p for p,_ in data], 
    startangle=90, counterclock=False,
    autopct="", pctdistance=0.75,
    wedgeprops={'width':0.5,'linewidth':1,'edgecolor':'k','antialiased': True},
    colors="w")
  # matrix plot
  nbMen, nbWomen = popularity.shape
  """
  axmat = inset_axes(ax, "20%", "20%", loc="center")
  axmat.xaxis.tick_top()
  xticks, yticks = list(range(1,1+nbWomen)), list(range(1,1+nbMen))
  axmat.set_xticks(xticks)
  axmat.set_yticks(yticks)
  axmat.set_xticklabels("$w_{%d}$" % i for i in xticks)
  axmat.set_yticklabels("$m_{%d}$" % i for i in yticks)
  axmat.imshow(popularity,
    norm=LogNorm(vmin=0.01,vmax=1000), cmap="gray_r", 
    extent=(0.5, nbWomen+0.5, nbMen+0.5, 0.5))
  for idMan in range(nbMen):
    for idWoman in range(nbWomen):
      axmat.text(1+idWoman, 1+idMan, str(popularity[idMan, idWoman]))
  """
  # angles
  anglesB = [(w.theta2 - w.theta1)/2. + w.theta1 for w in wedges]
  anglesA = best_angles(anglesB)
  # plot matchings
  plt.rc('mathtext', fontset='stix')
  ax.set_xlim(-1.6, 1.6)
  ax.set_ylim(-1.6, 1.6)
  matchings = [ (p,m,w,t) for (p,m),w,t in zip(data, wedges, texts)]
  for i, (p, m, w, t) in enumerate(matchings):
    radius = 1.25
    if abs(w.theta2 - w.theta1) >= 10:
      t.set_text("$\\frac{%d}{%d}$" % (p.numerator, p.denominator))
      t.set_size(22)
    angA, angB = anglesA[i], anglesB[i]
    xA = radius * np.cos(np.deg2rad(angA))
    yA = radius * np.sin(np.deg2rad(angA))
    xB = np.cos(np.deg2rad(angB))
    yB = np.sin(np.deg2rad(angB))
    box = AnchoredOffsetbox(
      child=draw_matching(m, nbMen, nbWomen),
      loc='center', frameon=True,
      bbox_to_anchor=(xA, yA),
      bbox_transform=ax.transData,
      pad=0., borderpad=0.)
    ax.add_artist(box)
    con = ConnectionPatch(
      xyA = (xA,yA), xyB = (xB,yB),
      coordsA="data", coordsB="data")
    ax.add_artist(con)
Example #13
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)
Example #14
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,
            ))
Example #15
0
def anchor_legend(ax, box, row, col):
    anchored = AnchoredOffsetbox(
        loc=2,
        child=box,
        pad=0.,
        frameon=False,
        bbox_to_anchor=(1 + 0.25 * col, 1 - 0.054 * row),
        bbox_transform=ax.transAxes,
    )
    # Workaround for a bug in matplotlib up to 1.3.1
    # https://github.com/matplotlib/matplotlib/issues/2530
    anchored.set_clip_on(False)
    ax.add_artist(anchored)
Example #16
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()
Example #17
0
def AddTraceScaleBar(xunit, yunit, color='k',linewidth=None,\
                         fontsize=None, ax=None, xscale=None, yscale=None,
                         loc=5, bbox_to_anchor=None):
        """Add scale bar on trace. Specifically designed for voltage /
        current / stimulus vs. time traces.
        xscale, yscale: add the trace bar to the specified window of x and y.
        """
        if ax is None: ax=plt.gca()
        def scalebarlabel(x, unitstr):
            x = int(x)
            if unitstr.lower()[0] == 'm':
                return(str(x)+" " + unitstr if x<1000 else str(int(x/1000))+ " " +
                        unitstr.replace('m',''))
            elif unitstr.lower()[0] == 'p':
                return(str(x)+" "+ unitstr if x<1000 else str(int(x/1000))+ " " +
                        unitstr.replace('p','n'))
            else: # no prefix
                return(str(x)+" " + unitstr)

        ax.set_axis_off() # turn off axis
        X = np.ptp(ax.get_xlim()) if xscale is None else xscale
        Y = np.ptp(ax.get_ylim()) if yscale is None else yscale
        # calculate scale bar unit length
        X, Y = roundto125(X/5), roundto125(Y/(5 if Y<1200 else 10))
        # Parse scale bar labels
        xlab, ylab = scalebarlabel(X, xunit), scalebarlabel(Y, yunit)
        # Get color of the scalebar
        if color is None:
            color = ax.get_lines()[0]
        if 'matplotlib.lines.Line2D' in str(type(color)):
            color = color.get_color()
        if linewidth is None:
            try:
                linewidth = ax.get_lines()[0]
            except:
                linewidth=0.70
                #raise(AttributeError('Did not find any line in this axis. Please explicitly specify the linewidth'))
        if 'matplotlib.lines.Line2D' in str(type(linewidth)):
            linewidth = linewidth.get_linewidth()
        # print(linewidth)
        if fontsize is None:
            fontsize = ax.yaxis.get_major_ticks()[2].label.get_fontsize()
        scalebarBox = AuxTransformBox(ax.transData)
        scalebarBox.add_artist(matplotlib.patches.Rectangle((0, 0), X, 0, fc="none", edgecolor='k', linewidth=linewidth, joinstyle='miter', capstyle='projecting')) #TODO capstyle
        scalebarBox.add_artist(matplotlib.patches.Rectangle((X, 0), 0, Y, fc="none", edgecolor='k', linewidth=linewidth, joinstyle='miter', capstyle='projecting'))
        scalebarBox.add_artist(matplotlib.text.Text(X/2, -Y/20, xlab, va='top', ha='center', color='k'))
        scalebarBox.add_artist(matplotlib.text.Text(X+X/20, Y/2, ylab, va='center', ha='left', color='k'))
        anchored_box = AnchoredOffsetbox(loc=loc, pad=-9, child=scalebarBox, frameon=False, bbox_to_anchor=bbox_to_anchor)
        ax.add_artist(anchored_box)
        return(anchored_box)
Example #18
0
def watermark(fig, ax, loc=2, downscale=8):
    # print(os.getcwd())
    img = Image.open('../references/tu_delft_logo.png')
    width, height = ax.figure.get_size_inches() * fig.dpi
    wm_width = int(width /
                   downscale)  # make the watermark 1/4 of the figure size
    scaling = (wm_width / float(img.size[0]))
    wm_height = int(float(img.size[1]) * float(scaling))
    img = img.resize((wm_width, wm_height), Image.ANTIALIAS)

    imagebox = OffsetImage(img, zoom=1, alpha=0.5)
    imagebox.image.axes = ax

    ao = AnchoredOffsetbox(loc=loc, pad=0.01, borderpad=0, child=imagebox)
    ao.patch.set_alpha(0)
    ax.add_artist(ao)
Example #19
0
def offset_text(ax, txt, loc, bbox_to_anchor=(-.03, .65)):
    box1 = TextArea(txt, textprops=dict(color="k", size='10'))

    box = HPacker(children=[box1], align="center", pad=2, sep=5)

    anchored_box = AnchoredOffsetbox(
        loc=loc,
        child=box,
        pad=0.,
        frameon=False,
        prop=dict(size=5),
        bbox_to_anchor=bbox_to_anchor,
        bbox_transform=ax.transAxes,
        borderpad=0.1,
    )
    ax.add_artist(anchored_box)
Example #20
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)
Example #21
0
def multicolor_xlabel(ax, list_of_strings, anchorpad=0, **kw):
    # code from: https://stackoverflow.com/a/33162465
    from matplotlib.offsetbox import AnchoredOffsetbox, TextArea, HPacker, VPacker
    boxes = [
        TextArea(text,
                 textprops=dict(color='C{}'.format(i),
                                ha='left',
                                va='bottom',
                                **kw))
        for i, text in enumerate(list_of_strings)
    ]
    xbox = HPacker(children=boxes, align='center', pad=0, sep=5)
    anchored_xbox = AnchoredOffsetbox(loc='lower center',
                                      child=xbox,
                                      pad=anchorpad,
                                      frameon=False,
                                      bbox_transform=ax.transAxes,
                                      borderpad=0.0)
    ax.add_artist(anchored_xbox)
Example #22
0
def test_offsetbox_loc_codes():
    # Check that valid string location codes all work with an AnchoredOffsetbox
    codes = {'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,
             }
    fig, ax = plt.subplots()
    da = DrawingArea(100, 100)
    for code in codes:
        anchored_box = AnchoredOffsetbox(loc=code, child=da)
        ax.add_artist(anchored_box)
    fig.canvas.draw()
Example #23
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)
Example #24
0
def printNode(node):


    fig, ax = plt.subplots()

    infoBox = TextArea("        -- Node -- " + \
    					"\n · Placed: " + str(node.buildingType.name) + \
    					"\n · At cell " + str(node.buildingPosition) + \
					    "\n · Node weight: " + str(node.nodeWeight) + \
					    "\n · Expanded "+ str(node.getSearchLevel()) + " levels" + \
					    "\n · Contains " + str((node.getRegressedMatrix()).findUnbiltHolesRounded()) + " holes")
    
    box = HPacker(children=[infoBox],
              align="center",
              pad=5, sep=5)

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

    matrix = node.getRegressedMatrix().matrixMap
    ax.matshow(matrix)

    ax.add_artist(anchored_box)
    fig.subplots_adjust(right=0.9)
    fig.subplots_adjust(top=0.97)
    fig.subplots_adjust(bottom=0.02)

    for x in range(matrix.shape[0]):
        for y in range(matrix.shape[1]):
            c = matrix[x,y]
            #if not math.isinf(c) and  c != float("inf") and c != float("-inf"):
            #    c = int(c)
            ax.text(y,x, str(int(c)), va='center', ha='center')

    plt.show()
Example #25
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
Example #26
0
def add_igp_logo(ax, loc, image_bg="transparent", zoom=1, **kwargs):
    """
    Add the IGP logo to a figure.

    (a clone of MetPy package's _add_logo() function)

    Logo credit: Andrew Elvidge

    Arguments
    ----------
    ax : matplotlib axes
       The `axes` instance used for plotting
    loc : int or str
       Location of logo within the axes
    image_bg : str
       Logo background (white|transparent)
    zoom : float
       Size of logo to be used.
    kwargs : keyword arguments
        kwargs passed to `matplotlib.offsetbox.AnchoredOffsetbox`,
        except for `frameon` and `loc`
    """
    logodir = Path("_static")
    # fname_suffix = {'S': '75x75',
    #                 'M': '150x150',
    #                 'L': '300x300'}
    fname_prefix = {"transparent": "t", "white": "w"}
    try:
        fname = "igp_logo_{}_300x300.png".format(fname_prefix[image_bg])
        fpath = logodir / fname
    except KeyError:
        raise ValueError("Unknown logo size or background")

    logo = imread(str(fpath))
    imagebox = OffsetImage(logo, zoom=zoom)
    ao = AnchoredOffsetbox(loc=loc, child=imagebox, frameon=False, **kwargs)
    ax.add_artist(ao)
Example #27
0
def offset_text(ax,
                txt,
                loc,
                bbox_to_anchor=(-.03, .65),
                text_props={
                    "color": "k",
                    "size": "13"
                }):
    """This function is a copy of the one in draw.py"""
    box1 = TextArea(txt, textprops=text_props)

    box = HPacker(children=[box1], align="center", pad=2, sep=5)

    anchored_box = AnchoredOffsetbox(
        loc=loc,
        child=box,
        pad=0.,
        frameon=False,
        prop=dict(size=5),
        bbox_to_anchor=bbox_to_anchor,
        bbox_transform=ax.transAxes,
        borderpad=0.1,
    )
    ax.add_artist(anchored_box)
Example #28
0
def sbs_to_patch(sbs,
                 transform,
                 unit,
                 padding=2,
                 bbox_transform='axes fraction',
                 bbox_to_anchor=(0.2, 0.3)):

    # First create a single Patch for all Sbs
    of1 = HPacker(width=2,
                  height=1,
                  pad=1,
                  sep=0,
                  align="center",
                  mode="expand",
                  children=sbs)

    t = AnchoredOffsetbox("upper left",
                          pad=0.4,
                          frameon=False,
                          bbox_transform=bbox_transform,
                          bbox_to_anchor=bbox_to_anchor,
                          child=of1)

    return t
Example #29
0
    def logo_box(self):

        logo_offset_image = OffsetImage(read_png(
            get_sample_data(logo_location, asfileobj=False)),
                                        zoom=0.25,
                                        resample=1,
                                        dpi_cor=1)
        text_box = TextArea(logo_text,
                            textprops=dict(color='#444444',
                                           fontsize=50,
                                           weight='bold'))

        logo_and_text_box = HPacker(children=[logo_offset_image, text_box],
                                    align="center",
                                    pad=0,
                                    sep=25)

        anchored_box = AnchoredOffsetbox(loc=2,
                                         child=logo_and_text_box,
                                         pad=0.8,
                                         frameon=False,
                                         borderpad=0.)

        return anchored_box
    def plot_rectangle(self, figure, axis):
        '''
        plots the legend rectangle above the left corner of the figure
        :param figure: figure on which to add the label
        :param axis: axis on which to add the label
        :return: -
        '''

        box1 = TextArea(" True: \n False: \n NaN: ",
                        textprops=dict(color="k", size=10))

        # box2 = DrawingArea(20, 27.5, 0, 0)
        # el1 = Rectangle((5, 15), width=10, height=10, angle=0, fc="g")
        # el2 = Rectangle((5, 2.5), width=10, height=10, angle=0, fc="r")
        box2 = DrawingArea(20, 45, 0, 0)
        el1 = Rectangle((5, 30), width=10, height=10, angle=0, fc="g")
        el2 = Rectangle((5, 18.5), width=10, height=10, angle=0, fc="r")
        el3 = Rectangle((5, 7), width=10, height=10, angle=0, fc='#d3d3d3')
        box2.add_artist(el1)
        box2.add_artist(el2)
        box2.add_artist(el3)

        box = HPacker(children=[box1, box2], align="center", pad=0, sep=5)

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

        axis.add_artist(anchored_box)
        figure.subplots_adjust(top=0.8)