DEPRECATED, use `Plot.colorbar` instead
432394
def add_colorbar(self, *args, **kwargs):
        
        warnings.warn(
            "{0}.add_colorbar was renamed {0}.colorbar, this warnings will "
            "result in an error in the future".format(type(self).__name__),
            DeprecationWarning)
        return self.colorbar(*args, **kwargs)
846703
def _set_all_axis_color(self, axis, color):
        """"""
        for prop in ['ticks', 'axis', 'major_ticks', 'minor_ticks', 'title',
                     'labels']:
            prop_set = getattr(axis.properties, prop)
            if color and prop in ['title', 'labels']:
                prop_set.fill = ValueRef(value=color)
            elif color and prop in ['axis', 'major_ticks', 'minor_ticks',
                                    'ticks']:
                prop_set.stroke = ValueRef(value=color)
605447
def _find_associated_colorbar(obj):
    
    for child in obj.get_children():
        try:
            cbar = child.colorbar
        except AttributeError:
            continue
        if cbar is not None:  # really necessary?
            # if fetch was successful, cbar contains
            # (reference to colorbar,
            #   reference to axis containing colorbar)
            return cbar
    return None
273997
def palettebar(height, length, colormap):
    
    cbar = np.tile(np.arange(length) * 1.0 / (length - 1), (height, 1))
    cbar = (cbar * (colormap.values.max() + 1 - colormap.values.min())
            + colormap.values.min())

    return colormap.palettize(cbar)
912290
def plot_ratio(cid, ax, plotman, title, alpha, vmin, vmax,
               xmin, xmax, zmin, zmax, xunit, cbtiks, elecs):
    '''
    '''
    # handle options
    cblabel = 'anisotropy ratio'
    zlabel = 'z [' + xunit + ']'
    xlabel = 'x [' + xunit + ']'
    # cm = 'brg'
    cm = 'RdYlGn'
    xmin, xmax, zmin, zmax, vmin, vmax = check_minmax(
            plotman,
            cid,
            xmin, xmax,
            zmin, zmax,
            vmin, vmax,
            )
    # plot
    fig, ax, cnorm, cmap, cb, scalarMap = plotman.plot_elements_to_ax(
            cid=cid,
            ax=ax,
            xmin=xmin,
            xmax=xmax,
            zmin=zmin,
            zmax=zmax,
            cblabel=cblabel,
            cbnrticks=cbtiks,
            title=title,
            zlabel=zlabel,
            xlabel=xlabel,
            plot_colorbar=True,
            cmap_name=cm,
            no_elecs=elecs,
            cbmin=vmin,
            cbmax=vmax,
            )
    return fig, ax, cnorm, cmap, cb
1229434
def bar(self, counts, phenotype_to_color=None, ax=None, percentages=True):
        
        if percentages:
            counts = 100 * (counts.T / counts.T.sum()).T

        # with sns.set(style='whitegrid'):
        if ax is None:
            ax = plt.gca()

        full_width = 0.8
        width = full_width / counts.shape[0]
        for i, (group, series) in enumerate(counts.iterrows()):
            left = np.arange(len(self.modality_order)) + i * width
            height = [series[i] if i in series else 0
                      for i in self.modality_order]
            color = phenotype_to_color[group]
            ax.bar(left, height, width=width, color=color, label=group,
                   linewidth=.5, edgecolor='k')
        ylabel = 'Percentage of events' if percentages else 'Number of events'
        ax.set_ylabel(ylabel)
        ax.set_xticks(np.arange(len(self.modality_order)) + full_width / 2)
        ax.set_xticklabels(self.modality_order)
        ax.set_xlabel('Splicing modality')
        ax.set_xlim(0, len(self.modality_order))
        ax.legend(loc='best')
        ax.grid(axis='y', linestyle='-', linewidth=0.5)
        sns.despine()
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
1291646
def get_plot(self, xlim=None, ylim=None):
        

        plt = pretty_plot(12, 8)
        base = 0.0
        i = 0
        for key, sp in self._spectra.items():
            if not self.stack:
                plt.plot(sp.x, sp.y + self.yshift * i, color=self.colors[i],
                         label=str(key), linewidth=3)
            else:
                plt.fill_between(sp.x, base, sp.y + self.yshift * i,
                                 color=self.colors[i],
                                 label=str(key), linewidth=3)
                base = sp.y + base
            plt.xlabel(sp.XLABEL)
            plt.ylabel(sp.YLABEL)
            i += 1

        if xlim:
            plt.xlim(xlim)
        if ylim:
            plt.ylim(ylim)

        plt.legend()
        leg = plt.gca().get_legend()
        ltext = leg.get_texts()  # all the text.Text instance in the legend
        plt.setp(ltext, fontsize=30)
        plt.tight_layout()
        return plt
320445
def fill_between(self, canvas, X, lower, upper, color=None, label=None, **kwargs):
        
        raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library")
896776
function Toolbar() {
		var buttons = {};

		/*jslint unparam: true*//* allow the unused param title until Toolbar rewrite*/
		function add(id, text, title, fn) {
			if (!buttons[id]) {
				var button = renderer.text(
					text,
					0,
					0
				)
				.css(options.toolbar.itemStyle)
				.align({
					align: 'right',
					x: -marginRight - 20,
					y: plotTop + 30
				})
				.on('click', fn)
				/*.on('touchstart', function(e) {
					e.stopPropagation(); // don't fire the container event
					fn();
				})*/
				.attr({
					align: 'right',
					zIndex: 20
				})
				.add();
				buttons[id] = button;
			}
		}
		/*jslint unparam: false*/

		function remove(id) {
			discardElement(buttons[id].element);
			buttons[id] = null;
		}

		// public
		return {
			add: add,
			remove: remove
		};
	}
436247
def plot_lightness(saveplot=False):
    '''

    '''

    from colorspacious import cspace_converter

    dc = 1.
    x = np.linspace(0.0, 1.0, 256)
    locs = []  # locations for text labels

    fig = plt.figure(figsize=(16, 5))
    ax = fig.add_subplot(111)
    fig.subplots_adjust(left=0.03, right=0.97)
    ax.set_xlim(-0.1, len(cm.cmap_d)/2. + 0.1)
    ax.set_ylim(0, 100)
    ax.set_xlabel('Lightness for each colormap', fontsize=14)

    for j, cmapname in enumerate(cm.cmapnames):

        if '_r' in cmapname:  # skip reversed versions for plot
            continue

        cmap = cm.cmap_d[cmapname]  # get the colormap instance
        rgb = cmap(x)[np.newaxis, :, :3]
        lab = cspace_converter("sRGB1", "CAM02-UCS")(rgb)
        L = lab[0, :, 0]
        if L[-1] > L[0]:
            ax.scatter(x+j*dc, L, c=x, cmap=cmap, s=200, linewidths=0.)
        else:
            ax.scatter(x+j*dc, L[::-1], c=x[::-1], cmap=cmap, s=200, linewidths=0.)
        locs.append(x[-1]+j*dc)  # store locations for colormap labels

    # Set up labels for colormaps
    ax.xaxis.set_ticks_position('top')
    ticker = mpl.ticker.FixedLocator(locs)
    ax.xaxis.set_major_locator(ticker)
    formatter = mpl.ticker.FixedFormatter([cmapname for cmapname in cm.cmapnames])
    ax.xaxis.set_major_formatter(formatter)
    labels = ax.get_xticklabels()
    for label in labels:
        label.set_rotation(60)

    if saveplot:
        fig.savefig('figures/lightness.png', bbox_inches='tight')
        fig.savefig('figures/lightness.pdf', bbox_inches='tight')

    plt.show()
311513
def _colorize_bars(self, cmap, bars, element, main_range, dim):
        
        cmap_range = main_range[1] - main_range[0]
        lower_bound = main_range[0]
        colors = np.array(element.dimension_values(dim))
        colors = (colors - lower_bound) / (cmap_range)
        for c, bar in zip(colors, bars):
            bar.set_facecolor(cmap(c))
            bar.set_clip_on(False)
698570
def refresh_styles(self):
        """"""
        import matplotlib.pyplot as plt

        self.colours = {}
        for style in plt.style.available:
            try:
                style_colours = plt.style.library[style]['axes.prop_cycle']
                self.colours[style] = [c['color'] for c in list(style_colours)]
            except KeyError:
                continue

        self.colours['km3pipe'] = [
            "#ff7869", "#4babe1", "#96ad3e", "#e4823d", "#5d72b2", "#e2a3c2",
            "#fd9844", "#e480e7"
        ]
1349906
def plot_gallery(saveplot=False):
    '''

    '''

    from colorspacious import cspace_converter

    gradient = np.linspace(0, 1, 256)
    gradient = np.vstack((gradient, gradient))
    x = np.linspace(0.0, 1.0, 256)

    fig, axes = plt.subplots(nrows=int(len(cm.cmap_d)/2), ncols=1, figsize=(6, 12))
    fig.subplots_adjust(top=0.99, bottom=0.01, left=0.2, right=0.99, wspace=0.05)

    for ax, cmapname in zip(axes, cm.cmapnames):

        if '_r' in cmapname:  # skip reversed versions for plot
            continue

        cmap = cm.cmap_d[cmapname]  # get the colormap instance

        rgb = cmap(x)[np.newaxis, :, :3]

        # Find a good conversion to grayscale
        jch = cspace_converter("sRGB1", "CAM02-UCS")(rgb)  # Not sure why to use JCh instead so using this.
        L = jch[0, :, 0]
        L = np.float32(np.vstack((L, L, L)))

        ax.imshow(gradient, aspect='auto', cmap=cmap)

        pos1 = ax.get_position()  # get the original position
        pos2 = [pos1.x0, pos1.y0,  pos1.width, pos1.height / 3.0]
        axbw = fig.add_axes(pos2)  # colorbar axes
        axbw.set_axis_off()
        axbw.imshow(L, aspect='auto', cmap=cm.gray, vmin=0, vmax=100.)
        pos = list(ax.get_position().bounds)
        x_text = pos[0] - 0.01
        y_text = pos[1] + pos[3]/2.
        fig.text(x_text, y_text, cmap.name, va='center', ha='right')

    # Turn off *all* ticks & spines, not just the ones with colormaps.
    for ax in axes:
        ax.set_axis_off()

    if saveplot:
        fig.savefig('figures/gallery.pdf', bbox_inches='tight')
        fig.savefig('figures/gallery.png', bbox_inches='tight')

    plt.show()
397081
def terminal_sexy_to_wal(data):
    """"""
    data["colors"] = {}
    data["special"] = {
        "foreground": data["foreground"],
        "background": data["background"],
        "cursor": data["color"][9]
    }

    for i, color in enumerate(data["color"]):
        data["colors"]["color%s" % i] = color

    return data
785603
function DrawBars() {

    if ($this->data_type != "text-data") {
      $this->DrawError('Bar plots must be text-data: use function SetDataType("text-data")');
    }

    $xadjust = ($this->records_per_group * $this->record_bar_width )/4;

    reset($this->data_values);
    while (list($j, $row) = each($this->data_values)) {

      $color_index = 0;
      $colbarcount = 0;
      $x_now = $this->xtr($j+.5);

      while (list($k, $v) = each($row)) {
        if ($k == 0) {
          //Draw Data Labels
          $xlab = SubStr($v,0,$this->x_datalabel_maxlength);
          $this->DrawXDataLabel($xlab,$x_now);
        } else {
          // Draw Bars ($v)
          $x1 = $x_now - $this->data_group_space + ($k-1)*$this->record_bar_width;
          $x2 = $x1 + $this->record_bar_width*$this->bar_width_adjust;

          if ($v < $this->x_axis_position) {
            $y1 = $this->ytr($this->x_axis_position);
            $y2 = $this->ytr($v);
          } else {
            $y1 = $this->ytr($v);
            $y2 = $this->ytr($this->x_axis_position);
          }

          if ($color_index >= count($this->ndx_data_color)) $color_index=0;
          if ($colbarcount >= count($this->ndx_data_border_color)) $colbarcount=0;
          $barcol = $this->ndx_data_color[$color_index];
          $bordercol = $this->ndx_data_border_color[$colbarcount];

          if ((strval($v) != "") ) {   //Allow for missing Y data
            if ($this->shading > 0) {
              for($i=0;$i<($this->shading);$i++) {
              //Shading set in SetDefaultColors
              ImageFilledRectangle($this->img, $x1+$i, $y1-$i, $x2+$i, $y2-$i, $this->ndx_i_light);
              }
            }

            ImageFilledRectangle($this->img, $x1, $y1, $x2, $y2, $barcol);
            ImageRectangle($this->img, $x1, $y1, $x2, $y2, $bordercol);
            if ($this->draw_data_labels == '1') {  //ajo
              $y1 = $this->ytr($this->label_scale_position * $v);
              //$this->DrawDataLabel($v,$j + .5,$v*$this->label_scale_position);
              $this->DrawText($this->small_font, $this->x_label_angle,
                $x1+$this->record_bar_width/2, $y1, $this->ndx_label_color, $this->x_label_ttffont_size, $v,'center','top');
            }
          }

          $color_index++;
          $colbarcount++;
        }
      }
    }
  }
471630
protected void plotUncolored(SVGPlot plot, Element parent, double x, double y, double size) {
    Element marker = plot.svgCircle(x, y, size * .5);
    SVGUtil.setStyle(marker, SVGConstants.CSS_FILL_PROPERTY + ":" + dotcolor);
    parent.appendChild(marker);
  }