Plots the 2d histogram of the center
       coordinates of segments in the selected plane.
168858
def plot_density(population,  # pylint: disable=too-many-arguments, too-many-locals
                 bins=100, new_fig=True, subplot=111, levels=None, plane='xy',
                 colorlabel='Nodes per unit area', labelfontsize=16,
                 color_map='Reds', no_colorbar=False, threshold=0.01,
                 neurite_type=NeuriteType.basal_dendrite, **kwargs):
    '''
    '''
    fig, ax = common.get_figure(new_fig=new_fig, subplot=subplot)

    H1, xedges1, yedges1 = extract_density(population, plane=plane, bins=bins,
                                           neurite_type=neurite_type)

    mask = H1 < threshold  # mask = H1==0
    H2 = np.ma.masked_array(H1, mask)

    getattr(plt.cm, color_map).set_bad(color='white', alpha=None)

    plots = ax.contourf((xedges1[:-1] + xedges1[1:]) / 2,
                        (yedges1[:-1] + yedges1[1:]) / 2,
                        np.transpose(H2), # / np.max(H2),
                        cmap=getattr(plt.cm, color_map), levels=levels)

    if not no_colorbar:
        cbar = plt.colorbar(plots)
        cbar.ax.set_ylabel(colorlabel, fontsize=labelfontsize)

    kwargs['title'] = kwargs.get('title', '')
    kwargs['xlabel'] = kwargs.get('xlabel', plane[0])
    kwargs['ylabel'] = kwargs.get('ylabel', plane[1])

    return common.plot_style(fig=fig, ax=ax, **kwargs)
326299
def plot_sections(self, fout_dir=".", **kws_pltargs):
        """"""
        hdrgos = self.grprobj.hdrobj.get_section_hdrgos()
        pltargs = PltGroupedGosArgs(self.grprobj, fout_dir=fout_dir, **kws_pltargs)
        return self._plot_groups_hdrgos(hdrgos, pltargs)
841271
def plot_predictions_histogram(Y_ph, Y, title=None):
    
    labels = list(set(Y).union(set(Y_ph)))
    edges = [x - 0.5 for x in range(min(labels), max(labels) + 2)]

    plt.hist([Y_ph, Y], bins=edges, label=["Predicted", "Gold"])
    ax = plt.gca()
    ax.set_xticks(labels)
    plt.xlabel("Label")
    plt.ylabel("# Predictions")
    plt.legend(loc="upper right")
    if isinstance(title, str):
        plt.title(title)
    plt.show()
884412
def comp_centroid(data, bounding_box, debug_plot=False, plot_reference=None, logger=None):
    """"""

    from matplotlib.patches import Ellipse

    if logger is None:
        logger = logging.getLogger(__name__)

    region = bounding_box.slice
    ref_x = region[1].start
    ref_y = region[0].start
    logger.debug('region ofset is %s, %s', ref_x, ref_y)
    subimage = data[region].copy()
    bkg = sep.Background(subimage)
    data_sub = subimage - bkg
    objects = sep.extract(data_sub, 1.5, err=bkg.globalrms)
    # Select brightest object
    logger.debug('%d object found', len(objects))

    if len(objects) == 0:
        # print('No objects')
        return None

    iadx = objects['flux'].argmax()
    # plot background-subtracted image
    maxflux = objects[iadx]

    if debug_plot:
        fig, ax = plt.subplots()
        m, s = np.mean(data_sub), np.std(data_sub)
        ax.imshow(data_sub, interpolation='nearest', cmap='gray',
                  vmin=m - s, vmax=m + s, origin='lower',
                  extent=bounding_box.extent)
        if plot_reference:
            e = Ellipse(xy=(plot_reference[0], plot_reference[1]),
                        width=6,
                        height=6,
                        angle=0)
            e.set_facecolor('none')
            e.set_edgecolor('green')
            ax.add_artist(e)

        # plot an ellipse for each object
        for idx, obj in enumerate(objects):
            e = Ellipse(xy=(obj['x'] + ref_x, obj['y'] + ref_y),
                        width=6 * obj['a'],
                        height=6 * obj['b'],
                        angle=obj['theta'] * 180. / np.pi)
            e.set_facecolor('none')
            if idx == iadx:
                e.set_edgecolor('blue')
            else:
                e.set_edgecolor('red')
            ax.add_artist(e)
        return maxflux['x'], maxflux['y'], ax
    else:
        return maxflux['x'], maxflux['y']
977313
def plot_coordinates(self, X, ax=None, figsize=(6, 6), x_component=0, y_component=1,
                                   show_row_labels=True, show_col_labels=True, **kwargs):
        """"""

        utils.validation.check_is_fitted(self, 's_')

        if ax is None:
            fig, ax = plt.subplots(figsize=figsize)

        # Add style
        ax = plot.stylize_axis(ax)

        # Get labels and names
        row_label, row_names, col_label, col_names = util.make_labels_and_names(X)

        # Plot row principal coordinates
        row_coords = self.row_coordinates(X)
        ax.scatter(
            row_coords[x_component],
            row_coords[y_component],
            **kwargs,
            label=row_label
        )

        # Plot column principal coordinates
        col_coords = self.column_coordinates(X)
        ax.scatter(
            col_coords[x_component],
            col_coords[y_component],
            **kwargs,
            label=col_label
        )

        # Add row labels
        if show_row_labels:
            x = row_coords[x_component]
            y = row_coords[y_component]
            for i, label in enumerate(row_names):
                ax.annotate(label, (x[i], y[i]))

        # Add column labels
        if show_col_labels:
            x = col_coords[x_component]
            y = col_coords[y_component]
            for i, label in enumerate(col_names):
                ax.annotate(label, (x[i], y[i]))

        # Legend
        ax.legend()

        # Text
        ax.set_title('Principal coordinates')
        ei = self.explained_inertia_
        ax.set_xlabel('Component {} ({:.2f}% inertia)'.format(x_component, 100 * ei[x_component]))
        ax.set_ylabel('Component {} ({:.2f}% inertia)'.format(y_component, 100 * ei[y_component]))

        return ax
953257
def center(self, coords):
        
        x, y = [round(i, 0) for i in coords]
        self.view_rect.center = x, y

        tw, th = self.data.tile_size

        left, ox = divmod(x, tw)
        top, oy = divmod(y, th)

        vec = int(ox / 2), int(oy)

        iso = vector2_to_iso(vec)
        self._x_offset = iso[0]
        self._y_offset = iso[1]

        print(self._tile_view.size)
        print(self._buffer.get_size())

        # center the buffer on the screen
        self._x_offset += (self._buffer.get_width() - self.view_rect.width) // 2
        self._y_offset += (self._buffer.get_height() - self.view_rect.height) // 4

        # adjust the view if the view has changed without a redraw
        dx = int(left - self._tile_view.left)
        dy = int(top - self._tile_view.top)
        view_change = max(abs(dx), abs(dy))

        # force redraw every time: edge queuing not supported yet
        self._redraw_cutoff = 0

        if view_change and (view_change <= self._redraw_cutoff):
            self._buffer.scroll(-dx * tw, -dy * th)
            self._tile_view.move_ip(dx, dy)
            self._queue_edge_tiles(dx, dy)
            self._flush_tile_queue()

        elif view_change > self._redraw_cutoff:
            # logger.info('scrolling too quickly.  redraw forced')
            self._tile_view.move_ip(dx, dy)
            self.redraw_tiles()
1131019
def plot_gaussian_2D(mu, lmbda, color='b', centermarker=True,label='',alpha=1.,ax=None,artists=None):
    '''
    
    '''
    assert len(mu) == 2
    ax = ax if ax else plt.gca()

    # TODO use artists!

    t = np.hstack([np.arange(0,2*np.pi,0.01),0])
    circle = np.vstack([np.sin(t),np.cos(t)])
    ellipse = np.dot(np.linalg.cholesky(lmbda),circle)

    if artists is None:
        point = ax.scatter([mu[0]],[mu[1]],marker='D',color=color,s=4,alpha=alpha) \
                if centermarker else None
        line, = ax.plot(ellipse[0,:] + mu[0], ellipse[1,:] + mu[1],linestyle='-',
                linewidth=2,color=color,label=label,alpha=alpha)
    else:
        line, point = artists
        if centermarker:
            point.set_offsets(np.atleast_2d(mu))
        line.set_xdata(ellipse[0,:] + mu[0])
        line.set_ydata(ellipse[1,:] + mu[1])
        line.set_alpha(alpha)
        line.set_color(color)

    return line, point
368476
def plot_sphere(ax, center, radius, color='black', alpha=1., linspace_count=_LINSPACE_COUNT):
    

    u = np.linspace(0, 2 * np.pi, linspace_count)
    v = np.linspace(0, np.pi, linspace_count)
    sin_v = np.sin(v)
    x = center[0] + radius * np.outer(np.cos(u), sin_v)
    y = center[1] + radius * np.outer(np.sin(u), sin_v)
    z = center[2] + radius * np.outer(np.ones_like(u), np.cos(v))

    ax.plot_surface(x, y, z, linewidth=0.0, color=color, alpha=alpha)
461010
def centroid(self):
        

        ycen, xcen = self.cutout_centroid.value
        return (ycen + self._slice[0].start,
                xcen + self._slice[1].start) * u.pix
304012
def plot_target(target, ax):
    """"""
    ax.scatter(target[0], target[1], target[2], c="red", s=80)
164075
def report(args):
    '''
    
    '''
    from jcvi.utils.cbook import SummaryStats
    from jcvi.graphics.histogram import stem_leaf_plot

    p = OptionParser(report.__doc__)
    p.add_option("--pdf", default=False, action="store_true",
            help="Generate graphic output for the histogram [default: %default]")
    p.add_option("--components", default=1, type="int",
            help="Number of components to decompose peaks [default: %default]")
    add_plot_options(p)
    opts, args, iopts = p.set_image_options(args, figsize="5x5")

    if len(args) !=  1:
        sys.exit(not p.print_help())

    ks_file, = args
    data = KsFile(ks_file)
    ks_min = opts.vmin
    ks_max = opts.vmax
    bins = opts.bins

    for f in fields.split(",")[1:]:
        columndata = [getattr(x, f) for x in data]
        ks = ("ks" in f)
        if not ks:
            continue

        columndata = [x for x in columndata if ks_min <= x <= ks_max]

        st = SummaryStats(columndata)
        title = "{0} ({1}): ".format(descriptions[f], ks_file)
        title += "Median:{0:.3f} (1Q:{1:.3f}|3Q:{2:.3f}||".\
                format(st.median, st.firstq, st.thirdq)
        title += "Mean:{0:.3f}|Std:{1:.3f}||N:{2})".\
                format(st.mean, st.sd, st.size)

        tbins = (0, ks_max, bins) if ks else (0, .6, 10)
        digit = 2 if (ks_max * 1. / bins) < .1 else 1
        stem_leaf_plot(columndata, *tbins, digit=digit, title=title)

    if not opts.pdf:
        return

    components = opts.components
    data = [x.ng_ks for x in data]
    data = [x for x in data if ks_min <= x <= ks_max]

    fig = plt.figure(1, (iopts.w, iopts.h))
    ax = fig.add_axes([.12, .1, .8, .8])
    kp = KsPlot(ax, ks_max, opts.bins, legendp=opts.legendp)
    kp.add_data(data, components, fill=opts.fill, fitted=opts.fit)
    kp.draw(title=opts.title)
3259
def plot_sections(self, fout_dir=".", **kws_usr):
        """"""
        kws_plt, _ = self._get_kws_plt(None, **kws_usr)
        PltGroupedGos(self).plot_sections(fout_dir, **kws_plt)
1014533
def hist2d(x, y, label=None, opacity=None):
    
    x = np.atleast_1d(x)
    y = np.atleast_1d(y)
    data = [go.Histogram2d(x=x, y=y, opacity=opacity, name=label)]
    return Chart(data=data)
1178881
def draw_hist(self, metric, title=""):
        
        # TODO: assert isinstance(list(values.values())[0], np.ndarray)

        rows = 1
        cols = 1
        limit = 10  # max steps to show

        # We need a 3D projection Subplot, so ignore the one provided to
        # as an create a new one.
        ax = self.figure.add_subplot(self.gs, projection="3d")
        ax.view_init(30, -80)

        # Compute histograms
        verts = []
        area_colors = []
        edge_colors = []
        for i, s in enumerate(metric.steps[-limit:]):
            hist, edges = np.histogram(metric.data[-i-1:])
            # X is bin centers
            x = np.diff(edges)/2 + edges[:-1]
            # Y is hist values
            y = hist
            x = np.concatenate([x[0:1], x, x[-1:]])
            y = np.concatenate([[0], y, [0]])

            # Ranges
            if i == 0:
                x_min = x.min()
                x_max = x.max()
                y_min = y.min()
                y_max = y.max()
            x_min = np.minimum(x_min, x.min())
            x_max = np.maximum(x_max, x.max())
            y_min = np.minimum(y_min, y.min())
            y_max = np.maximum(y_max, y.max())

            alpha = 0.8 * (i+1) / min(limit, len(metric.steps))
            verts.append(list(zip(x, y)))
            area_colors.append(np.array(self.theme["hist_color"] + [alpha]))
            edge_colors.append(np.array(self.theme["hist_outline_color"] + [alpha]))

        poly = PolyCollection(verts, facecolors=area_colors, edgecolors=edge_colors)
        ax.add_collection3d(poly, zs=list(range(min(limit, len(metric.steps)))), zdir='y')

        ax.set_xlim(x_min, x_max)
        ax.set_ylim(0, limit)
        ax.set_yticklabels(metric.formatted_steps[-limit:])
        ax.set_zlim(y_min, y_max)
        ax.set_title(metric.name)
377343
def set_axis_centres(self, *args):
        
        for axis in self.axes_by_code.values():
            if isinstance(axis, CentredAxis):
                axis.centre = axis.value
733299
def plot_info(self, dvs):
        '''
        

        '''

        axl, axc, axr = dvs.title()
        axc.annotate("%s %d" % (self._mission.IDSTRING, self.ID),
                     xy=(0.5, 0.5), xycoords='axes fraction',
                     ha='center', va='center', fontsize=18)

        axc.annotate(r"%.2f ppm $\rightarrow$ %.2f ppm" %
                     (self.cdppr, self.cdpp),
                     xy=(0.5, 0.2), xycoords='axes fraction',
                     ha='center', va='center', fontsize=8, color='k',
                     fontstyle='italic')

        axl.annotate("%s %s%02d: %s" %
                     (self.mission.upper(),
                      self._mission.SEASONCHAR, self.season, self.name),
                     xy=(0.5, 0.5), xycoords='axes fraction',
                     ha='center', va='center', fontsize=12,
                     color='k')

        axl.annotate(self.aperture_name if len(self.neighbors) == 0
                     else "%s, %d neighbors" %
                     (self.aperture_name, len(self.neighbors)),
                     xy=(0.5, 0.2), xycoords='axes fraction',
                     ha='center', va='center', fontsize=8, color='k',
                     fontstyle='italic')

        axr.annotate("%s %.3f" % (self._mission.MAGSTRING, self.mag),
                     xy=(0.5, 0.5), xycoords='axes fraction',
                     ha='center', va='center', fontsize=12,
                     color='k')

        if not np.isnan(self.cdppg) and self.cdppg > 0:
            axr.annotate(r"GP %.3f ppm" % (self.cdppg),
                         xy=(0.5, 0.2), xycoords='axes fraction',
                         ha='center', va='center', fontsize=8, color='k',
                         fontstyle='italic')
576170
def plot(self):
        
        import pylab as p
        p.clf()
        fig = p.figure(1)
        nspw = len(self.gain[0])
        ext = n.ceil(n.sqrt(nspw))  # find best squre plot (simplest)
        for spw in range(len(self.gain[0])):
            ax = fig.add_subplot(ext, ext, spw+1)
            for pol in [0,1]:
                ax.scatter(range(len(self.gain)), n.abs(self.gain.data[:,spw,pol]), color=n.array(['k','y']).take(self.gain.mask[:,spw,pol]), marker=['x','.'][pol])

        fig.show()