Handles the optional labelling of the plot with relevant quantities
        Args:
            plt (plt): Plot of the locpot vs c axis
            label_fontsize (float): Fontsize of labels
        Returns Labelled plt
157
def get_labels(self, plt, label_fontsize=10):
        

        # center of vacuum and bulk region
        if len(self.slab_regions) > 1:
            label_in_vac = (self.slab_regions[0][1] + self.slab_regions[1][0])/2
            if abs(self.slab_regions[0][0]-self.slab_regions[0][1]) > \
                    abs(self.slab_regions[1][0]-self.slab_regions[1][1]):
                label_in_bulk = self.slab_regions[0][1]/2
            else:
                label_in_bulk = (self.slab_regions[1][1] + self.slab_regions[1][0]) / 2
        else:
            label_in_bulk = (self.slab_regions[0][0] + self.slab_regions[0][1])/2
            if self.slab_regions[0][0] > 1-self.slab_regions[0][1]:
                label_in_vac = self.slab_regions[0][0] / 2
            else:
                label_in_vac = (1 + self.slab_regions[0][1]) / 2

        plt.plot([0, 1], [self.vacuum_locpot]*2, 'b--', zorder=-5, linewidth=1)
        xy = [label_in_bulk, self.vacuum_locpot+self.ave_locpot*0.05]
        plt.annotate(r"$V_{vac}=%.2f$" %(self.vacuum_locpot), xy=xy,
                     xytext=xy, color='b', fontsize=label_fontsize)

        # label the fermi energy
        plt.plot([0, 1], [self.efermi]*2, 'g--',
                 zorder=-5, linewidth=3)
        xy = [label_in_bulk, self.efermi+self.ave_locpot*0.05]
        plt.annotate(r"$E_F=%.2f$" %(self.efermi), xytext=xy,
                     xy=xy, fontsize=label_fontsize, color='g')

        # label the bulk-like locpot
        plt.plot([0, 1], [self.ave_bulk_p]*2, 'r--', linewidth=1., zorder=-1)
        xy = [label_in_vac, self.ave_bulk_p + self.ave_locpot * 0.05]
        plt.annotate(r"$V^{interior}_{slab}=%.2f$" % (self.ave_bulk_p),
                     xy=xy, xytext=xy, color='r', fontsize=label_fontsize)

        # label the work function as a barrier
        plt.plot([label_in_vac]*2, [self.efermi, self.vacuum_locpot],
                 'k--', zorder=-5, linewidth=2)
        xy = [label_in_vac, self.efermi + self.ave_locpot * 0.05]
        plt.annotate(r"$\Phi=%.2f$" %(self.work_function),
                     xy=xy, xytext=xy, fontsize=label_fontsize)

        return plt
1308961
def use(style):
        
        def valid(value):  # checks if json'able
            return isinstance(value, six.string_types)

        def translate(mplstyle):
            style = {}
            mapping = [
                ['figure.facecolor', 'background-color'],
                ['xtick.color', 'axes.x.color'],  # TODO: is this the right thing?
                ['xtick.color', 'axes.z.color'],  # map x to z as well
                ['ytick.color', 'axes.y.color'],
                ['axes.labelcolor', 'axes.label.color'],
                ['text.color', 'color'],
                ['axes.edgecolor', 'axes.color'],
            ]
            for from_name, to_name in mapping:
                if from_name in mplstyle:
                    value = mplstyle[from_name]
                    if "color" in from_name:
                        try:  # threejs doesn't like a color like '.13', so try to convert to proper format
                            value = float(value) * 255
                            value = "rgb(%d, %d, %d)" % (value, value, value)
                        except:
                            pass

                    utils.nested_setitem(style, to_name, value)
            return style

        if isinstance(style, six.string_types + (dict,)):
            styles = [style]
        else:
            styles = style
        fig = gcf()
        totalstyle = utils.dict_deep_update({}, fig.style)
        for style in styles:
            if isinstance(style, six.string_types):
                if hasattr(ipyvolume.styles, style):
                    style = getattr(ipyvolume.styles, style)
                else:
                    # lets see if we can copy matplotlib's style
                    # we assume now it's a matplotlib style, get all properties that we understand
                    cleaned_style = {
                        key: value for key, value in dict(matplotlib.style.library[style]).items() if valid(value)
                    }
                    style = translate(cleaned_style)
                    # totalstyle.update(cleaned_style)
            else:
                # otherwise assume it's a dict
                pass
            totalstyle = utils.dict_deep_update(totalstyle, style)

        fig = gcf()
        fig.style = totalstyle
375654
def _init_glyph(self, plot, mapping, properties):
        
        properties = mpl_to_bokeh(properties)
        plot_method = self._plot_methods.get('batched' if self.batched else 'single')
        if isinstance(plot_method, tuple):
            # Handle alternative plot method for flipped axes
            plot_method = plot_method[int(self.invert_axes)]
        renderer = getattr(plot, plot_method)(**dict(properties, **mapping))
        return renderer, renderer.glyph
539809
def OnLabelSizeIntCtrl(self, event):
        """"""

        self.attrs["labelsize"] = event.GetValue()

        post_command_event(self, self.DrawChartMsg)
1360699
def plot(self, size=1):
        
        n = len(self)
        fig, ax = plt.subplots(1, 1, figsize=(n * size, size))
        ax.imshow(np.arange(n).reshape(1,n),
                  cmap=mpl.colors.ListedColormap(list(self)),
                  interpolation="nearest", aspect="auto")
        ax.set_xticks(np.arange(n) - .5)
        ax.set_yticks([-.5, .5])
        ax.set_xticklabels([])
        ax.set_yticklabels([])
740266
def labels(self, value):
        
        if value is not None:
            assert type(value) is tuple, "'{0}' attribute: '{1}' type is not 'tuple'!".format("labels", value)
            assert len(value) == 2, "'{0}' attribute: '{1}' length should be '2'!".format("labels", value)
            for index in range(len(value)):
                assert type(value[index]) is unicode, \
                    "'{0}' attribute element '{1}': '{2}' type is not 'unicode'!".format("labels", index, value)
        self.__labels = value
401324
def plot_scales(self, titles=None, fig_kwargs={}, **kwargs):
        
        from ..plotting import plotting_library as pl

        if titles is None:
            titles = [r'${}$'.format(name) for name in self.names]

        M = len(self.bgplvms)
        fig = pl().figure(rows=1, cols=M, **fig_kwargs)
        for c in range(M):
            canvas = self.bgplvms[c].kern.plot_ARD(title=titles[c], figure=fig, col=c+1, **kwargs)
        return canvas
99024
def get_label_scale(self, min_val, max_val, size):
        """"""
        if size < self.SCALE_DENSITY:
            label_cnt = 1
        else:
            label_cnt = int(size / self.SCALE_DENSITY)
        try:
            if max_val >= 100:
                label = [int((min_val + i * (max_val - min_val) / label_cnt))
                         for i in range(label_cnt + 1)]
            else:
                label = [round((min_val + i *
                                (max_val - min_val) / label_cnt), 1)
                         for i in range(label_cnt + 1)]
            return label
        except ZeroDivisionError:
            logging.debug("Side label creation divided by 0")
            return ""
1073023
def plot(self, cavas, X, Y, Z=None, color=None, label=None, **kwargs):
        
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")
1169891
def title(label, style=None):
    
    fig = current_figure()
    fig.title = label
    if style is not None:
        fig.title_style = style
895210
def _plot_generic(self, filename=None):
        
        #Since the filename is being passed directly from the argument, check its validity.
        if filename == "":
            filename = None

        if "x" not in self.curargs["labels"]:
            #Set a default x-label since we know what variable is being plotted.
            self.curargs["labels"]["x"] = "Value of '{}' (unknown units)".format(self.curargs["independent"])
        args = self.curargs
        a = self.tests[self.active]
        self._make_fits()
        
        #Before we can pass the markers in, we need to translate from keys to values so
        #that matplotlib understands.
        markdict = self._get_matplot_dict("markers", "marker", self._possible_markers)
        linedict = self._get_matplot_dict("lines", "style", self._possible_linestyles)

        #Set the remaining arguments to have the right keyword name.
        args["savefile"] = filename
        args["markers"] = markdict
        args["lines"] = linedict
        
        a.plot(**args)
624255
def _maketicks(self, plt):
        
        ticks = self.get_ticks()
        # Sanitize only plot the uniq values
        uniq_d = []
        uniq_l = []
        temp_ticks = list(zip(ticks['distance'], ticks['label']))
        for i in range(len(temp_ticks)):
            if i == 0:
                uniq_d.append(temp_ticks[i][0])
                uniq_l.append(temp_ticks[i][1])
                logger.debug("Adding label {l} at {d}".format(
                    l=temp_ticks[i][0], d=temp_ticks[i][1]))
            else:
                if temp_ticks[i][1] == temp_ticks[i - 1][1]:
                    logger.debug("Skipping label {i}".format(
                        i=temp_ticks[i][1]))
                else:
                    logger.debug("Adding label {l} at {d}".format(
                        l=temp_ticks[i][0], d=temp_ticks[i][1]))
                    uniq_d.append(temp_ticks[i][0])
                    uniq_l.append(temp_ticks[i][1])

        logger.debug("Unique labels are %s" % list(zip(uniq_d, uniq_l)))
        plt.gca().set_xticks(uniq_d)
        plt.gca().set_xticklabels(uniq_l)

        for i in range(len(ticks['label'])):
            if ticks['label'][i] is not None:
                # don't print the same label twice
                if i != 0:
                    if ticks['label'][i] == ticks['label'][i - 1]:
                        logger.debug("already print label... "
                                     "skipping label {i}".format(
                            i=ticks['label'][i]))
                    else:
                        logger.debug("Adding a line at {d}"
                                     " for label {l}".format(
                            d=ticks['distance'][i], l=ticks['label'][i]))
                        plt.axvline(ticks['distance'][i], color='k')
                else:
                    logger.debug("Adding a line at {d} for label {l}".format(
                        d=ticks['distance'][i], l=ticks['label'][i]))
                    plt.axvline(ticks['distance'][i], color='k')
        return plt
106052
def combiplot(self, fontsize=8, **kwargs):
        
        ax_list = None
        for i, (label, cycle) in enumerate(self.items()):
            fig = cycle.plot(ax_list=ax_list, label=label, fontsize=fontsize,
                             lw=2.0, marker="o", linestyle="-", show=False)
            ax_list = fig.axes

        return fig
699833
def p_else_part_label(p):
    
    lbl = make_label(p[1], p.lineno(1))
    p[0] = [make_block(lbl, p[3]), p[4]]
99901
def p_label_line_co(p):
    
    lbl = make_label(p[1], p.lineno(1))
    p[0] = make_block(lbl, p[2]) if len(p) == 3 else lbl
1182599
def _get_2d_plot(self, label_stable=True, label_unstable=True,
                     ordering=None, energy_colormap=None, vmin_mev=-60.0,
                     vmax_mev=60.0, show_colorbar=True,
                     process_attributes=False, plt=None):
        
        if plt is None:
            plt = pretty_plot(8, 6)
        from matplotlib.font_manager import FontProperties
        if ordering is None:
            (lines, labels, unstable) = self.pd_plot_data
        else:
            (_lines, _labels, _unstable) = self.pd_plot_data
            (lines, labels, unstable) = order_phase_diagram(
                _lines, _labels, _unstable, ordering)
        if energy_colormap is None:
            if process_attributes:
                for x, y in lines:
                    plt.plot(x, y, "k-", linewidth=3, markeredgecolor="k")
                # One should think about a clever way to have "complex"
                # attributes with complex processing options but with a clear
                # logic. At this moment, I just use the attributes to know
                # whether an entry is a new compound or an existing (from the
                #  ICSD or from the MP) one.
                for x, y in labels.keys():
                    if labels[(x, y)].attribute is None or \
                                    labels[(x, y)].attribute == "existing":
                        plt.plot(x, y, "ko", **self.plotkwargs)
                    else:
                        plt.plot(x, y, "k*", **self.plotkwargs)
            else:
                for x, y in lines:
                    plt.plot(x, y, "ko-", **self.plotkwargs)
        else:
            from matplotlib.colors import Normalize, LinearSegmentedColormap
            from matplotlib.cm import ScalarMappable
            for x, y in lines:
                plt.plot(x, y, "k-", markeredgecolor="k")
            vmin = vmin_mev / 1000.0
            vmax = vmax_mev / 1000.0
            if energy_colormap == 'default':
                mid = - vmin / (vmax - vmin)
                cmap = LinearSegmentedColormap.from_list(
                    'my_colormap', [(0.0, '#005500'), (mid, '#55FF55'),
                                    (mid, '#FFAAAA'), (1.0, '#FF0000')])
            else:
                cmap = energy_colormap
            norm = Normalize(vmin=vmin, vmax=vmax)
            _map = ScalarMappable(norm=norm, cmap=cmap)
            _energies = [self._pd.get_equilibrium_reaction_energy(entry)
                         for coord, entry in labels.items()]
            energies = [en if en < 0.0 else -0.00000001 for en in _energies]
            vals_stable = _map.to_rgba(energies)
            ii = 0
            if process_attributes:
                for x, y in labels.keys():
                    if labels[(x, y)].attribute is None or \
                                    labels[(x, y)].attribute == "existing":
                        plt.plot(x, y, "o", markerfacecolor=vals_stable[ii],
                                 markersize=12)
                    else:
                        plt.plot(x, y, "*", markerfacecolor=vals_stable[ii],
                                 markersize=18)
                    ii += 1
            else:
                for x, y in labels.keys():
                    plt.plot(x, y, "o", markerfacecolor=vals_stable[ii],
                             markersize=15)
                    ii += 1

        font = FontProperties()
        font.set_weight("bold")
        font.set_size(24)

        # Sets a nice layout depending on the type of PD. Also defines a
        # "center" for the PD, which then allows the annotations to be spread
        # out in a nice manner.
        if len(self._pd.elements) == 3:
            plt.axis("equal")
            plt.xlim((-0.1, 1.2))
            plt.ylim((-0.1, 1.0))
            plt.axis("off")
            center = (0.5, math.sqrt(3) / 6)
        else:
            all_coords = labels.keys()
            miny = min([c[1] for c in all_coords])
            ybuffer = max(abs(miny) * 0.1, 0.1)
            plt.xlim((-0.1, 1.1))
            plt.ylim((miny - ybuffer, ybuffer))
            center = (0.5, miny / 2)
            plt.xlabel("Fraction", fontsize=28, fontweight='bold')
            plt.ylabel("Formation energy (eV/fu)", fontsize=28,
                       fontweight='bold')

        for coords in sorted(labels.keys(), key=lambda x: -x[1]):
            entry = labels[coords]
            label = entry.name

            # The follow defines an offset for the annotation text emanating
            # from the center of the PD. Results in fairly nice layouts for the
            # most part.
            vec = (np.array(coords) - center)
            vec = vec / np.linalg.norm(vec) * 10 if np.linalg.norm(vec) != 0 \
                else vec
            valign = "bottom" if vec[1] > 0 else "top"
            if vec[0] < -0.01:
                halign = "right"
            elif vec[0] > 0.01:
                halign = "left"
            else:
                halign = "center"
            if label_stable:
                if process_attributes and entry.attribute == 'new':
                    plt.annotate(latexify(label), coords, xytext=vec,
                                 textcoords="offset points",
                                 horizontalalignment=halign,
                                 verticalalignment=valign,
                                 fontproperties=font,
                                 color='g')
                else:
                    plt.annotate(latexify(label), coords, xytext=vec,
                                 textcoords="offset points",
                                 horizontalalignment=halign,
                                 verticalalignment=valign,
                                 fontproperties=font)

        if self.show_unstable:
            font = FontProperties()
            font.set_size(16)
            energies_unstable = [self._pd.get_e_above_hull(entry)
                                 for entry, coord in unstable.items()]
            if energy_colormap is not None:
                energies.extend(energies_unstable)
                vals_unstable = _map.to_rgba(energies_unstable)
            ii = 0
            for entry, coords in unstable.items():
                ehull = self._pd.get_e_above_hull(entry)
                if ehull < self.show_unstable:
                    vec = (np.array(coords) - center)
                    vec = vec / np.linalg.norm(vec) * 10 \
                        if np.linalg.norm(vec) != 0 else vec
                    label = entry.name
                    if energy_colormap is None:
                        plt.plot(coords[0], coords[1], "ks", linewidth=3,
                                 markeredgecolor="k", markerfacecolor="r",
                                 markersize=8)
                    else:
                        plt.plot(coords[0], coords[1], "s", linewidth=3,
                                 markeredgecolor="k",
                                 markerfacecolor=vals_unstable[ii],
                                 markersize=8)
                    if label_unstable:
                        plt.annotate(latexify(label), coords, xytext=vec,
                                     textcoords="offset points",
                                     horizontalalignment=halign, color="b",
                                     verticalalignment=valign,
                                     fontproperties=font)
                    ii += 1
        if energy_colormap is not None and show_colorbar:
            _map.set_array(energies)
            cbar = plt.colorbar(_map)
            cbar.set_label(
                'Energy [meV/at] above hull (in red)\nInverse energy ['
                'meV/at] above hull (in green)',
                rotation=-90, ha='left', va='center')
            ticks = cbar.ax.get_yticklabels()
            # cbar.ax.set_yticklabels(['${v}$'.format(
            #     v=float(t.get_text().strip('$'))*1000.0) for t in ticks])
        f = plt.gcf()
        f.set_size_inches((8, 6))
        plt.subplots_adjust(left=0.09, right=0.98, top=0.98, bottom=0.07)
        return plt
973002
def get_axis_properties(axis):
    """"""
    props = {}
    label1On = axis._major_tick_kw.get('label1On', True)

    if isinstance(axis, matplotlib.axis.XAxis):
        if label1On:
            props['position'] = "bottom"
        else:
            props['position'] = "top"
    elif isinstance(axis, matplotlib.axis.YAxis):
        if label1On:
            props['position'] = "left"
        else:
            props['position'] = "right"
    else:
        raise ValueError("{0} should be an Axis instance".format(axis))

    # Use tick values if appropriate
    locator = axis.get_major_locator()
    props['nticks'] = len(locator())
    if isinstance(locator, ticker.FixedLocator):
        props['tickvalues'] = list(locator())
    else:
        props['tickvalues'] = None

    # Find tick formats
    formatter = axis.get_major_formatter()
    if isinstance(formatter, ticker.NullFormatter):
        props['tickformat'] = ""
    elif isinstance(formatter, ticker.FixedFormatter):
        props['tickformat'] = list(formatter.seq)
    elif not any(label.get_visible() for label in axis.get_ticklabels()):
        props['tickformat'] = ""
    else:
        props['tickformat'] = None

    # Get axis scale
    props['scale'] = axis.get_scale()

    # Get major tick label size (assumes that's all we really care about!)
    labels = axis.get_ticklabels()
    if labels:
        props['fontsize'] = labels[0].get_fontsize()
    else:
        props['fontsize'] = None

    # Get associated grid
    props['grid'] = get_grid_style(axis)

    return props