Plot stacked serie lines and stacked secondary lines
194051
def _plot(self):
        """"""
        for serie in self.series[::-1 if self.stack_from_top else 1]:
            self.line(serie)
        for serie in self.secondary_series[::-1 if self.stack_from_top else 1]:
            self.line(serie, True)
1265664
def line(self, x0, y0, x1, y1, c='*'):
        
        """
        steep = abs(y1 - y0) > abs(x1 - x0)
        if steep:
            (x0, y0) = (y0, x0)
            (x1, y1) = (y1, x1)
        if x0 > x1:
            (x0, x1) = (x1, x0)
            (y0, y1) = (y1, y0)
        deltax = x1 - x0
        deltay = abs(y1 - y0)
        error = deltax / 2
        y = y0
        if y0 < y1:
            ystep = 1
        else:
            ystep = -1
        for x in range(x0, x1 - 1):
            if steep:
                self[y, x] = c
            else:
                self[x, y] = c
            error = error - deltay
            if error < 0:
                y = y + ystep
                error = error + deltax
1232892
def twoSurfplots(self):
    
    # Could more elegantly just call surfplot twice
    # And also could include xyzinterp as an option inside surfplot.
    # Noted here in case anyone wants to take that on in the future...

    plt.subplot(211)
    plt.title('Load thickness, mantle equivalent [m]',fontsize=16)
    if self.latlon:
      plt.imshow(self.qs/(self.rho_m*self.g), extent=(0, self.dx*self.qs.shape[0], self.dy*self.qs.shape[1], 0))
      plt.xlabel('longitude [deg E]', fontsize=12, fontweight='bold')
      plt.ylabel('latitude [deg N]', fontsize=12, fontweight='bold')
    else:
      plt.imshow(self.qs/(self.rho_m*self.g), extent=(0, self.dx/1000.*self.qs.shape[0], self.dy/1000.*self.qs.shape[1], 0))
      plt.xlabel('x [km]', fontsize=12, fontweight='bold')
      plt.ylabel('y [km]', fontsize=12, fontweight='bold')
    plt.colorbar()

    plt.subplot(212)
    plt.title('Deflection [m]')
    if self.latlon:
      plt.imshow(self.w, extent=(0, self.dx*self.w.shape[0], self.dy*self.w.shape[1], 0))
      plt.xlabel('longitude [deg E]', fontsize=12, fontweight='bold')
      plt.ylabel('latitude [deg N]', fontsize=12, fontweight='bold')
    else:
      plt.imshow(self.w, extent=(0, self.dx/1000.*self.w.shape[0], self.dy/1000.*self.w.shape[1], 0))
      plt.xlabel('x [km]', fontsize=12, fontweight='bold')
      plt.ylabel('y [km]', fontsize=12, fontweight='bold')
    plt.colorbar()
26842
def plotGrid(self, numLines=(5,5), lineWidth=1, colour="#777777"):
        
        x1, x2, y1, y2 = mp.axis()
        ra1, dec0 = self.pixToSky(x1, y1)
        ra0, dec1 = self.pixToSky(x2, y2)

        xNum, yNum = numLines
        self.raRange, self.decRange  = self.getRaDecRanges(numLines)

        #import pdb; pdb.set_trace()
        #Guard against Ra of zero within the plot
        a1 = np.abs(ra1-ra0)
        a2 = np.abs( min(ra0, ra1) - (max(ra0, ra1) - 360))
        if a2 < a1:     #Then we straddle 360 degrees in RA
            if ra0 < ra1:
                ra1 -= 360
            else:
                ra0 -= 360


        #Draw lines of constant dec
        lwr = min(ra0, ra1)
        upr = max(ra0, ra1)
        stepX = round((upr-lwr) / float(xNum))
        ra_deg = np.arange(lwr - 3*stepX, upr + 3.5*stepX, 1, dtype=np.float)
        for dec in self.decRange:
            self.plotLine(ra_deg, dec, '-', color = colour, linewidth = lineWidth)


        #Draw lines of const ra
        lwr = min(dec0, dec1)
        upr = max(dec0, dec1)
        stepY = round((upr-lwr) / float(yNum))
        dec_deg = np.arange(dec0 - 3*stepY, dec1 + 3.5*stepY, 1, dtype=np.float)
        for ra in self.raRange:
            self.plotLine(ra, dec_deg, '-', color = colour, linewidth = lineWidth)

        mp.axis([x1, x2, y1, y2])
801359
def plot_cast(df, secondary_y=False, label=None, *args, **kwargs):
    

    ax = kwargs.pop("ax", None)
    fignums = plt.get_fignums()
    if ax is None and not fignums:
        ax = plt.axes()
        fig = ax.get_figure()
        fig.set_size_inches((5.25, 6.75))
    else:
        ax = plt.gca()
        fig = plt.gcf()

    figsize = kwargs.pop("figsize", fig.get_size_inches())
    fig.set_size_inches(figsize)

    y_inverted = False
    if not getattr(ax, "y_inverted", False):
        setattr(ax, "y_inverted", True)
        y_inverted = True

    if secondary_y:
        ax = ax.twiny()

    xlabel = getattr(df, "name", None)
    ylabel = getattr(df.index, "name", None)

    if isinstance(df, pd.DataFrame):
        labels = label if label else df.columns
        for k, (col, series) in enumerate(df.iteritems()):
            ax.plot(series, series.index, label=labels[k])
    elif isinstance(df, pd.Series):
        label = label if label else str(df.name)
        ax.plot(df.values, df.index, label=label, *args, **kwargs)

    ax.set_ylabel(ylabel)
    ax.set_xlabel(xlabel)
    if y_inverted and not secondary_y:
        ax.invert_yaxis()
    return ax
23235
def combine_concat_plans(plans, concat_axis):
    
    if len(plans) == 1:
        for p in plans[0]:
            yield p[0], [p[1]]

    elif concat_axis == 0:
        offset = 0
        for plan in plans:
            last_plc = None

            for plc, unit in plan:
                yield plc.add(offset), [unit]
                last_plc = plc

            if last_plc is not None:
                offset += last_plc.as_slice.stop

    else:
        num_ended = [0]

        def _next_or_none(seq):
            retval = next(seq, None)
            if retval is None:
                num_ended[0] += 1
            return retval

        plans = list(map(iter, plans))
        next_items = list(map(_next_or_none, plans))

        while num_ended[0] != len(next_items):
            if num_ended[0] > 0:
                raise ValueError("Plan shapes are not aligned")

            placements, units = zip(*next_items)

            lengths = list(map(len, placements))
            min_len, max_len = min(lengths), max(lengths)

            if min_len == max_len:
                yield placements[0], units
                next_items[:] = map(_next_or_none, plans)
            else:
                yielded_placement = None
                yielded_units = [None] * len(next_items)
                for i, (plc, unit) in enumerate(next_items):
                    yielded_units[i] = unit
                    if len(plc) > min_len:
                        # trim_join_unit updates unit in place, so only
                        # placement needs to be sliced to skip min_len.
                        next_items[i] = (plc[min_len:],
                                         trim_join_unit(unit, min_len))
                    else:
                        yielded_placement = plc
                        next_items[i] = _next_or_none(plans[i])

                yield yielded_placement, yielded_units
48693
def subplots(rows:int, cols:int, imgsize:int=4, figsize:Optional[Tuple[int,int]]=None, title=None, **kwargs):
    ""
    figsize = ifnone(figsize, (imgsize*cols, imgsize*rows))
    fig, axs = plt.subplots(rows,cols,figsize=figsize)
    if rows==cols==1: axs = [[axs]] # subplots(1,1) returns Axes, not [Axes]
    elif (rows==1 and cols!=1) or (cols==1 and rows!=1): axs = [axs]
    if title is not None: fig.suptitle(title, **kwargs)
    return array(axs)
952800
def plot_fit(self):
        
        self.plt.plot(*self.fit.fit, **self.options['fit'])
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
445309
def timeseries_subplot(X,
                       time=None,
                       color=None,
                       var_names=(),
                       highlightsX=(),
                       xlabel='',
                       ylabel='gene expression',
                       yticks=None,
                       xlim=None,
                       legend=True,
                       palette=None,
                       color_map='viridis'):
    

    if color is not None:
        use_color_map = isinstance(color[0], float) or isinstance(color[0], np.float32)
    palette = default_palette(palette)
    x_range = np.arange(X.shape[0]) if time is None else time
    if X.ndim == 1: X = X[:, None]
    if X.shape[1] > 1:
        colors = palette[:X.shape[1]].by_key()['color']
        subsets = [(x_range, X[:, i]) for i in range(X.shape[1])]
    elif use_color_map:
        colors = [color]
        subsets = [(x_range, X[:, 0])]
    else:
        levels, _ = np.unique(color, return_inverse=True)
        colors = np.array(palette[:len(levels)].by_key()['color'])
        subsets = [(x_range[color == l], X[color == l, :]) for l in levels]

    for i, (x, y) in enumerate(subsets):
        pl.scatter(
            x, y,
            marker='.',
            edgecolor='face',
            s=rcParams['lines.markersize'],
            c=colors[i],
            label=var_names[i] if len(var_names) > 0 else '',
            cmap=color_map,
            rasterized=settings._vector_friendly)
    ylim = pl.ylim()
    for ih, h in enumerate(highlightsX):
        pl.plot([h, h], [ylim[0], ylim[1]], '--', color='black')
    pl.ylim(ylim)
    if xlim is not None:
        pl.xlim(xlim)
    pl.xlabel(xlabel)
    pl.ylabel(ylabel)
    if yticks is not None:
        pl.yticks(yticks)
    if len(var_names) > 0 and legend:
        pl.legend(frameon=False)
141946
def _plot(self):
        """"""
        squares = self._squares()
        sq_dimensions = self.add_squares(squares)

        for index, serie in enumerate(self.series):
            current_square = self._current_square(squares, index)
            self.gaugify(serie, squares, sq_dimensions, current_square)
1011952
def plot_ts(fignum, dates, ts):
    
    vertical_plot_init(fignum, 10, 3)
    TS, Chrons = pmag.get_ts(ts)
    p = 1
    X, Y = [], []
    for d in TS:
        if d <= dates[1]:
            if d >= dates[0]:
                if len(X) == 0:
                    ind = TS.index(d)
                    X.append(TS[ind - 1])
                    Y.append(p % 2)
                X.append(d)
                Y.append(p % 2)
                p += 1
                X.append(d)
                Y.append(p % 2)
        else:
            X.append(dates[1])
            Y.append(p % 2)
            plt.plot(X, Y, 'k')
            plot_vs(fignum, dates, 'w', '-')
            plot_hs(fignum, [1.1, -.1], 'w', '-')
            plt.xlabel("Age (Ma): " + ts)
            isign = -1
            for c in Chrons:
                off = -.1
                isign = -1 * isign
                if isign > 0:
                    off = 1.05
                if c[1] >= X[0] and c[1] < X[-1]:
                    plt.text(c[1] - .2, off, c[0])
            return
1227340
def _bar(self, serie, parent, x, y, i, zero, secondary=False):
        """"""
        if secondary:
            cumulation = (
                self.secondary_negative_cumulation
                if y < self.zero else self.secondary_positive_cumulation
            )
        else:
            cumulation = (
                self.negative_cumulation
                if y < self.zero else self.positive_cumulation
            )
        zero = cumulation[i]
        cumulation[i] = zero + y
        if zero == 0:
            zero = self.zero
            y -= self.zero
        y += zero

        width = (self.view.x(1) - self.view.x(0)) / self._len
        x, y = self.view((x, y))
        y = y or 0
        series_margin = width * self._series_margin
        x += series_margin
        width -= 2 * series_margin
        if self.secondary_series:
            width /= 2
            x += int(secondary) * width
            serie_margin = width * self._serie_margin
            x += serie_margin
            width -= 2 * serie_margin
        height = self.view.y(zero) - y
        r = serie.rounded_bars * 1 if serie.rounded_bars else 0
        self.svg.transposable_node(
            parent,
            'rect',
            x=x,
            y=y,
            rx=r,
            ry=r,
            width=width,
            height=height,
            class_='rect reactive tooltip-trigger'
        )
        return x, y, width, height
335643
def series2df(Series, layer=2, split_sign = '_'):
    """"""
    try:
        Series.columns
        Series = Series.iloc[:,0]
    except:
        pass
    
    def _helper(x, layer=2):
        try:
            return flatten_dict(ast.literal_eval(x), layers=layer, split_sign=split_sign)
        except:
            try:
                return flatten_dict(x, layers=layer, split_sign=split_sign)
            except:
                return x
    
    df=pd.DataFrame(Series.apply(_helper).tolist())
    
    return df
502184
def merge_vertical_lines(lines, tol=TOLERANCE):
    
    if len(lines) == 0:
        return []
    merged_lines = [lines[0]]
    for line in lines[1:]:
        last_line = merged_lines[-1]
        if line[1] == last_line[1]:  # lines are vertically aligned
            if line[0] <= last_line[2] + tol:  # lines intersect
                y0, x0, y1, x1 = merged_lines[-1]
                merged_lines[-1] = (y0, x0, line[2], x1)
            else:
                merged_lines.append(
                    line
                )  # lines are vertically aligned but do not intersect
        else:
            merged_lines.append(line)
    return merged_lines
1159717
def plot(self, ncols=2):
        
        grid = gridplot(self.plots, ncols=ncols)
        return grid
1178753
def prevPlot(self):
        """"""
        if self.stacker.currentIndex() > 0:
            self.stacker.setCurrentIndex(self.stacker.currentIndex()-1)