Add net values next to an existing vertical stacked bar chart

    Parameters
    ----------
    axs : matplotlib.Axes or list thereof
    color : str, optional, default: black
        the color of the bars to add
343780
def add_net_values_to_bar_plot(axs, color='k'):
    
    axs = axs if isinstance(axs, Iterable) else [axs]
    for ax in axs:
        box_args = _get_boxes(ax)
        for x, args in box_args.items():
            rect = mpatches.Rectangle(*args, color=color)
            ax.add_patch(rect)
868209
def _axis_properties(self, axis, key, plot, dimension=None,
                         ax_mapping={'x': 0, 'y': 1}):
        
        # need to copy dictionary by calling dict() on it
        axis_props = dict(theme_attr_json(self.renderer.theme, 'Axis'))

        if ((axis == 'x' and self.xaxis in ['bottom-bare', 'top-bare', 'bare']) or
            (axis == 'y' and self.yaxis in ['left-bare', 'right-bare', 'bare'])):
            axis_props['axis_label_text_font_size'] = value('0pt')
            axis_props['major_label_text_font_size'] = value('0pt')
            axis_props['major_tick_line_color'] = None
            axis_props['minor_tick_line_color'] = None
        else:
            labelsize = self._fontsize('%slabel' % axis).get('fontsize')
            if labelsize:
                axis_props['axis_label_text_font_size'] = labelsize
            ticksize = self._fontsize('%sticks' % axis, common=False).get('fontsize')
            if ticksize:
                axis_props['major_label_text_font_size'] = value(ticksize)
            rotation = self.xrotation if axis == 'x' else self.yrotation
            if rotation:
                axis_props['major_label_orientation'] = np.radians(rotation)
            ticker = self.xticks if axis == 'x' else self.yticks
            if isinstance(ticker, Ticker):
                axis_props['ticker'] = ticker
            elif isinstance(ticker, int):
                axis_props['ticker'] = BasicTicker(desired_num_ticks=ticker)
            elif isinstance(ticker, (tuple, list)):
                if all(isinstance(t, tuple) for t in ticker):
                    ticks, labels = zip(*ticker)
                    # Ensure floats which are integers are serialized as ints
                    # because in JS the lookup fails otherwise
                    ticks = [int(t) if isinstance(t, float) and t.is_integer() else t
                             for t in ticks]
                    labels = [l if isinstance(l, util.basestring) else str(l)
                              for l in labels]
                    axis_props['ticker'] = FixedTicker(ticks=ticks)
                    axis_props['major_label_overrides'] = dict(zip(ticks, labels))
                else:
                    axis_props['ticker'] = FixedTicker(ticks=ticker)

        formatter = self.xformatter if axis == 'x' else self.yformatter
        if formatter:
            if isinstance(formatter, TickFormatter):
                pass
            elif isinstance(formatter, FunctionType):
                msg = ('%sformatter could not be '
                       'converted to tick formatter. ' % axis)
                jsfunc = py2js_tickformatter(formatter, msg)
                if jsfunc:
                    formatter = FuncTickFormatter(code=jsfunc)
                else:
                    formatter = None
            else:
                formatter = PrintfTickFormatter(format=formatter)
            if formatter is not None:
                axis_props['formatter'] = formatter
        elif FuncTickFormatter is not None and ax_mapping and isinstance(dimension, Dimension):
            formatter = None
            if dimension.value_format:
                formatter = dimension.value_format
            elif dimension.type in dimension.type_formatters:
                formatter = dimension.type_formatters[dimension.type]
            if formatter:
                msg = ('%s dimension formatter could not be '
                       'converted to tick formatter. ' % dimension.name)
                jsfunc = py2js_tickformatter(formatter, msg)
                if jsfunc:
                    formatter = FuncTickFormatter(code=jsfunc)
                    axis_props['formatter'] = formatter

        if axis == 'x':
            axis_obj = plot.xaxis[0]
        elif axis == 'y':
            axis_obj = plot.yaxis[0]

        if self.geographic and self.projection == 'mercator':
            dimension = 'lon' if axis == 'x' else 'lat'
            axis_props['ticker'] = MercatorTicker(dimension=dimension)
            axis_props['formatter'] = MercatorTickFormatter(dimension=dimension)
            box_zoom = self.state.select(type=tools.BoxZoomTool)
            if box_zoom:
                box_zoom[0].match_aspect = True
        elif isinstance(axis_obj, CategoricalAxis):
            for key in list(axis_props):
                if key.startswith('major_label'):
                    # set the group labels equal to major (actually minor)
                    new_key = key.replace('major_label', 'group')
                    axis_props[new_key] = axis_props[key]

            # major ticks are actually minor ticks in a categorical
            # so if user inputs minor ticks sizes, then use that;
            # else keep major (group) == minor (subgroup)
            msize = self._fontsize('minor_{0}ticks'.format(axis),
                common=False).get('fontsize')
            if msize is not None:
                axis_props['major_label_text_font_size'] = msize

        return axis_props
712146
def add(self, point, value):
        
        # check range
        for p, r in zip(point, self.range):
            if p < r[0] or p > r[1]:
                return
        # check nan
        if isnan(value):
            return

        refs = self.opts['references']
        # for all neighbour points (1, if antialiasting=False):
        for position, intensity in self.sortMethod.getPositionsIntensities(
                point):
            position = tuple(position)
            if self.mean is not None:
                old_value = self.values[position]
                if not np.isnan(old_value):
                    anz_values = self.density[position]
                    mean = old_value + intensity * (
                        ((value - old_value) / (anz_values + intensity)))
                    self.mean[position] = mean

                    if self.variance is not None:
                        self.variance[
                            position] += (abs(value - mean) / (
                                anz_values + intensity))

            if self.mergeMethod(self.values, position, intensity, value):
                for a in refs:
                    a.mergeMethod(a, position, intensity, value)
            if self.density is not None:
                self.density[position] += intensity
353907
def mpl_outside_legend(ax, **kwargs):
    
    box = ax.get_position()
    ax.set_position([box.x0, box.y0, box.width * 0.75, box.height])
    # Put a legend to the right of the current axis
    ax.legend(loc='upper left', bbox_to_anchor=(1, 1), **kwargs)
912380
def stack_plot(self, *args, **kwargs):
        
        df = self.as_pandas(with_metadata=True)
        ax = plotting.stack_plot(df, *args, **kwargs)
        return ax
1114493
def add_chart(chart_type, options={})
      TwoCellAnchor.new(self, options)
      @anchors.last.add_chart(chart_type, options)
    end
1338251
def _add_ticks(xaxis: go.layout.XAxis, histogram: HistogramBase, kwargs: dict):
    """"""
    ticks = kwargs.pop("ticks", None)
    tick_handler = kwargs.pop("tick_handler", None)

    if tick_handler:
        if ticks:
            raise ValueError("Cannot specify both tick and tick_handler")
        ticks, labels = tick_handler(histogram, histogram.min_edge, histogram.max_edge)

        xaxis.tickvals = ticks
        xaxis.ticktext = labels

    elif ticks == "center":
        xaxis.tickvals = histogram.bin_centers
    elif ticks == "edge":
        xaxis.tickvals = histogram.bin_left_edges
    else:
        xaxis.tickvals = ticks
656273
def _meanvalueattr(self,v):
        
        sug = self.layout
        if not self.prevlayer(): return sug.grx[v].bar
        bars = [sug.grx[x].bar for x in self._neighbors(v)]
        return sug.grx[v].bar if len(bars)==0 else float(sum(bars))/len(bars)
585659
function StackedBarChart(opts) {
      var me, _base2, _ref21, _ref22, _ref23, _ref24, _ref25, _ref26, _ref27, _ref28;

      me = this;
      StackedBarChart.__super__.constructor.call(this, opts);
      me.styles = (_ref21 = opts.styles) != null ? _ref21 : '';
      me.colors = (_ref22 = opts.colors) != null ? _ref22 : [];
      me.titles = (_ref23 = opts.titles) != null ? _ref23 : ['', '', '', '', ''];
      me.values = (_ref24 = opts.values) != null ? _ref24 : [];
      me.width = (_ref25 = opts.width) != null ? _ref25 : 17;
      me.height = (_ref26 = opts.height) != null ? _ref26 : 30;
      me["class"] = (_ref27 = opts["class"]) != null ? _ref27 : 'barchart';
      if ((_ref28 = (_base2 = Raphael.fn).drawStackedBarChart) == null) {
        _base2.drawStackedBarChart = drawStackedBars;
      }
    }
1289863
def draw_multi_dispersion_chart(self, nan_locs):
        
        for index, nan_values in enumerate(nan_locs):
            label, nan_locations = nan_values

            # if features passed in then, label as such
            if self.classes_ is not None:
                label = self.classes_[index]

            color = self.colors[index]

            x_, y_ = list(zip(*nan_locations))
            self.ax.scatter(x_, y_, alpha=self.alpha, marker=self.marker, color=color, label=label)
1153153
def draw_stacked_bar(self, nan_col_counts):
        
        for index, nan_values in enumerate(nan_col_counts):
            label, nan_col_counts = nan_values

            if index == 0:
                # first draw should be at zero
                bottom_chart = np.zeros(nan_col_counts.shape)

            # if features passed in then, label as such
            if self.classes_ is not None:
                label = self.classes_[index]

            color = self.colors[index]

            self.ax.barh(self.ind - self.width / 2, nan_col_counts, self.width,
                        color=color, label=label, left=bottom_chart)

            # keep track of counts to build on stacked
            bottom_chart = nan_col_counts
1061612
def add_text(self, coords, text, color=(0, 0, 0)):
        
        source = vtk.vtkVectorText()
        source.SetText(text)
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(source.GetOutputPort())
        follower = vtk.vtkFollower()
        follower.SetMapper(mapper)
        follower.GetProperty().SetColor(color)
        follower.SetPosition(coords)
        follower.SetScale(0.5)
        self.ren.AddActor(follower)
        follower.SetCamera(self.ren.GetActiveCamera())
17247
def _add_legend_or_colorbar(adata, ax, cax, categorical, value_to_plot, legend_loc,
                            scatter_array, legend_fontweight, legend_fontsize,
                            groups, multi_panel):
    
    # add legends or colorbars
    if categorical is True:
        # add legend to figure
        categories = list(adata.obs[value_to_plot].cat.categories)
        colors = adata.uns[value_to_plot + '_colors']

        if multi_panel is True:
            # Shrink current axis by 10% to fit legend and match
            # size of plots that are not categorical
            box = ax.get_position()
            ax.set_position([box.x0, box.y0, box.width * 0.91, box.height])

        if groups is not None:
            # only label groups with the respective color
            colors = [colors[categories.index(x)] for x in groups]
            categories = groups

        if legend_loc == 'right margin':
            for idx, label in enumerate(categories):
                color = colors[idx]
                # use empty scatter to set labels
                ax.scatter([], [], c=color, label=label)
            ax.legend(
                frameon=False, loc='center left',
                bbox_to_anchor=(1, 0.5),
                ncol=(1 if len(categories) <= 14
                      else 2 if len(categories) <= 30 else 3),
                fontsize=legend_fontsize)

        if legend_loc == 'on data':
            # identify centroids to put labels
            all_pos = np.zeros((len(categories), 2))
            for ilabel, label in enumerate(categories):
                _scatter = scatter_array[adata.obs[value_to_plot] == label, :]
                x_pos, y_pos = np.median(_scatter, axis=0)

                ax.text(x_pos, y_pos, label,
                        weight=legend_fontweight,
                        verticalalignment='center',
                        horizontalalignment='center',
                        fontsize=legend_fontsize)

                all_pos[ilabel] = [x_pos, y_pos]
            # this is temporary storage for access by other tools
            utils._tmp_cluster_pos = all_pos
    else:
        # add colorbar to figure
        pl.colorbar(cax, ax=ax, pad=0.01, fraction=0.08, aspect=30)
1086914
def apply_plot_params(plot_params,ax):
    """"""
    
    import matplotlib.pyplot as plt

    if plot_params['xlim'] is not None: 
        ax.set_xlim(plot_params['xlim'])
        
        if plot_params['reverse_x'] and plot_params['xlim'][0] < plot_params['xlim'][1]:
            ax.invert_xaxis()            
            
    elif plot_params['reverse_x']:
        ax.invert_xaxis()
    
    if plot_params['ylim'] is not None: ax.set_ylim(plot_params['ylim'])
        
    ax.grid(plot_params['grid'])
    ax.set_title(plot_params['title'],fontsize=plot_params['fontsize'],y=1.02)
    ax.set_xlabel(plot_params['xlabel'],fontsize=plot_params['tick_fontsize'])
    ax.set_ylabel(plot_params['ylabel'],fontsize=plot_params['tick_fontsize'])
    ax.set_axis_bgcolor(plot_params['axis_bg_color'])
    
    # Apply some properties to the line(s)
    line_handles = ax.get_lines()
    plt.setp(line_handles, lw=plot_params['line_width'], ls=plot_params['line_style'],
             marker=plot_params['marker'])
    
    if plot_params['line_color'] is not 'default':
        plt.setp(line_handles,'color', plot_params['line_color'])

    
    # Autoscale data on the y-axis to reflect changes to the x-axis
    if plot_params['autoscale_y']:
        ax = autoscale_y(ax,margin=0.05)
    
    if plot_params['use_sci_format_yaxis']:
        # Use scientific notation for the y-axis labels
        ax.ticklabel_format(axis='y',style='sci',scilimits=(-2,2))
    
    if plot_params['use_sci_format_xaxis']:
        # Use scientific notation for the x-axis labels
        ax.ticklabel_format(axis='x',style='sci',scilimits=(-2,2))
    
    ax.tick_params(labelsize=plot_params['tick_fontsize'])
        
    return ax
695064
def finalize(self, **kwargs):
        
        # Set the title
        self.set_title(
            'Parallel Coordinates for {} Features'.format(len(self.features_))
        )

        # Add the vertical lines
        # TODO: Make an independent function for override!
        if self.show_vlines:
            for idx in self._increments:
                self.ax.axvline(idx, **self.vlines_kwds)

        # Set the limits
        self.ax.set_xticks(self._increments)
        self.ax.set_xticklabels(self.features_)
        self.ax.set_xlim(self._increments[0], self._increments[-1])

        # Add the legend sorting classes by name
        labels = sorted(list(self._colors.keys()))
        colors = [self._colors[lbl] for lbl in labels]
        manual_legend(self, labels, colors, loc='best', frameon=True)

        # Add the grid view
        self.ax.grid()
1294583
def vertical(x, ymin=0, ymax=1, color=None, width=None, dash=None, opacity=None):
    
    lineattr = {}
    if color:
        lineattr['color'] = color
    if width:
        lineattr['width'] = width
    if dash:
        lineattr['dash'] = dash

    layout = dict(
        shapes=[dict(type='line', x0=x, x1=x, y0=ymin, y1=ymax, opacity=opacity, line=lineattr)]
    )
    return Chart(layout=layout)
1020920
def setup_axes(
        ax=None,
        panels='blue',
        colorbars=[False],
        right_margin=None,
        left_margin=None,
        projection='2d',
        show_ticks=False):
    
    if '3d' in projection: from mpl_toolkits.mplot3d import Axes3D
    avail_projections = {'2d', '3d'}
    if projection not in avail_projections:
        raise ValueError('choose projection from', avail_projections)
    if left_margin is not None:
        raise ValueError('Currently not supporting to pass `left_margin`.')
    if np.any(colorbars) and right_margin is None:
        right_margin = 1 - rcParams['figure.subplot.right'] + 0.21  # 0.25
    elif right_margin is None:
        right_margin = 1 - rcParams['figure.subplot.right'] + 0.06  # 0.10
    # make a list of right margins for each panel
    if not isinstance(right_margin, list):
        right_margin_list = [right_margin for i in range(len(panels))]
    else:
        right_margin_list = right_margin

    # make a figure with len(panels) panels in a row side by side
    top_offset = 1 - rcParams['figure.subplot.top']
    bottom_offset = 0.15 if show_ticks else 0.08
    left_offset = 1 if show_ticks else 0.3  # in units of base_height
    base_height = rcParams['figure.figsize'][1]
    height = base_height
    base_width = rcParams['figure.figsize'][0]
    if show_ticks: base_width *= 1.1

    draw_region_width = base_width - left_offset - top_offset - 0.5  # this is kept constant throughout

    right_margin_factor = sum([1 + right_margin for right_margin in right_margin_list])
    width_without_offsets = right_margin_factor * draw_region_width  # this is the total width that keeps draw_region_width

    right_offset = (len(panels) - 1) * left_offset
    figure_width = width_without_offsets + left_offset + right_offset
    draw_region_width_frac = draw_region_width / figure_width
    left_offset_frac = left_offset / figure_width
    right_offset_frac = 1 - (len(panels) - 1) * left_offset_frac

    if ax is None:
        pl.figure(figsize=(figure_width, height),
                  subplotpars=sppars(left=0, right=1, bottom=bottom_offset))
    left_positions = [left_offset_frac, left_offset_frac + draw_region_width_frac]
    for i in range(1, len(panels)):
        right_margin = right_margin_list[i-1]
        left_positions.append(left_positions[-1] + right_margin * draw_region_width_frac)
        left_positions.append(left_positions[-1] + draw_region_width_frac)
    panel_pos = [[bottom_offset], [1-top_offset], left_positions]

    axs = []
    if ax is None:
        for icolor, color in enumerate(panels):
            left = panel_pos[2][2*icolor]
            bottom = panel_pos[0][0]
            width = draw_region_width / figure_width
            height = panel_pos[1][0] - bottom
            if projection == '2d': ax = pl.axes([left, bottom, width, height])
            elif projection == '3d': ax = pl.axes([left, bottom, width, height], projection='3d')
            axs.append(ax)
    else:
        axs = ax if isinstance(ax, list) else [ax]

    return axs, panel_pos, draw_region_width, figure_width