Plot a histogram from a numpy array of probabilities

    Args:
        Y_p: An [n] or [n, 1] np.ndarray of probabilities (floats in [0,1])
17000
def plot_probabilities_histogram(Y_p, title=None):
    
    if Y_p.ndim > 1:
        msg = (
            f"Arg Y_p should be a 1-dimensional np.ndarray, not of shape "
            f"{Y_p.shape}."
        )
        raise ValueError(msg)
    plt.hist(Y_p, bins=20)
    plt.xlim((0, 1.025))
    plt.xlabel("Probability")
    plt.ylabel("# Predictions")
    if isinstance(title, str):
        plt.title(title)
    plt.show()
1099601
def plot(self, intervals=None, new_fig=True):
        """"""

        import pylab as p

        if new_fig:
            p.figure()

        #step 1: plot histogram
        p.plot(self.x, self.y, ls='-', c='b', lw='1.5')

        #step 2: plot peaks
        first_peak = None
        last_peak = None
        if self.peaks:
            first_peak = min(self.peaks["peaks"][0])
            last_peak = max(self.peaks["peaks"][0])
            p.plot(self.peaks["peaks"][0], self.peaks["peaks"][1], 'rD', ms=10)
            p.plot(self.peaks["valleys"][0], self.peaks["valleys"][1], 'yD', ms=5)

        #Intervals
        if intervals is not None:
            #spacing = 0.02*max(self.y)
            for interval in intervals:
                if first_peak is not None:
                    if interval <= first_peak or interval >= last_peak:
                        continue
                p.axvline(x=interval, ls='-.', c='g', lw='1.5')
                if interval-1200 >= min(self.x):
                    p.axvline(x=interval-1200, ls=':', c='b', lw='0.5')
                if interval+1200 <= max(self.x):
                    p.axvline(x=interval+1200, ls=':', c='b', lw='0.5')
                if interval+2400 <= max(self.x):
                    p.axvline(x=interval+2400, ls='-.', c='r', lw='0.5')
                #spacing *= -1

        #p.title("Tonic-aligned complete-range pitch histogram")
        #p.xlabel("Pitch value (Cents)")
        #p.ylabel("Normalized frequency of occurence")
        p.show()
614103
def projection(self, axis):
        """"""
        axis = self.get_axis_number(axis)
        projected_hist = np.sum(self.histogram, axis=self.other_axes(axis))
        return Hist1d.from_histogram(projected_hist, bin_edges=self.bin_edges[axis])
73278
def plot(self, **plot_kwargs: Any) -> None:
        
        fig = plt.figure()
        plt.plot(self._rabi_angles, self._excited_state_probs, 'ro-',
                 figure=fig, **plot_kwargs)
        plt.xlabel(r"Rabi Angle (Radian)", figure=fig)
        plt.ylabel('Excited State Probability', figure=fig)
        fig.show()
435966
def output_pdf_plot(core_result, spid, models, options, fit_results):
    
    # PDF/PMF
    hist_bins = 11
    emp_hist, edges = np.histogram(core_result['y'].values, hist_bins,
                                   normed=True)
    x = (np.array(edges[:-1]) + np.array(edges[1:])) / 2
    df = pd.DataFrame({'x': x, 'empirical': emp_hist})

    def calc_func(model, df, shapes):
        try:
            return eval("mod.%s.pmf(np.floor(df['x']), *shapes)" % model)
        except:
            return eval("mod.%s.pdf(df['x'], *shapes)" % model)

    plot_exec_str = "ax.bar(df['x']-width/2, emp, width=width, color='gray')"

    _save_table_and_plot(spid, models, options, fit_results, 'data_pred_pdf',
                         df, calc_func, plot_exec_str)
939616
def scatterplot(self, x, y, **kw):
        
        self.panel.scatterplot(x, y, **kw)
404241
def _setup_xy(self, p):
        
        self.debug("bounds=%s, xdensity=%s, ydensity=%s, x=%s, y=%s, orientation=%s",p.bounds, p.xdensity, p.ydensity, p.x, p.y, p.orientation)

        x_points,y_points = SheetCoordinateSystem(p.bounds, p.xdensity, p.ydensity).sheetcoordinates_of_matrixidx()

        self.pattern_x, self.pattern_y = self._create_and_rotate_coordinate_arrays(x_points-p.x, y_points-p.y, p)
1060229
def sample_histograms(fig, input_sample, problem, param_dict):
    '''

    '''
    num_vars = problem['num_vars']
    names = problem['names']

    framing = 101 + (num_vars * 10)

    # Find number of levels
    num_levels = len(set(input_sample[:, 1]))

    out = []

    for variable in range(num_vars):
        ax = fig.add_subplot(framing + variable)
        out.append(ax.hist(input_sample[:, variable],
                           bins=num_levels,
                           normed=False,
                           label=None,
                           **param_dict))

        ax.set_title('%s' % (names[variable]))
        ax.tick_params(axis='x',  # changes apply to the x-axis
                       which='both',  # both major and minor ticks are affected
                       bottom='off',  # ticks along the bottom edge are off
                       top='off',  # ticks along the top edge are off
                       labelbottom='off')  # labels along the bottom edge off)
        if variable > 0:
            ax.tick_params(axis='y',  # changes apply to the y-axis
                           which='both',  # both major and minor ticks affected
                           labelleft='off')  # labels along the left edge off)

    return out
50888
def plot_data(self, proj, ax):
        
        x, y = proj
        x_data = self.ig.independent_data[x]
        y_data = self.ig.dependent_data[y]
        projected_data = np.column_stack((x_data, y_data)).T
        kde = gaussian_kde(projected_data)

        xx, yy = np.meshgrid(self.ig._x_points[x], self.ig._y_points[y])
        x_grid = xx.flatten()
        y_grid = yy.flatten()

        contour_grid = kde.pdf(np.column_stack((x_grid, y_grid)).T)
        # This is an fugly kludge, but it seems nescessary to make low density
        # areas show up.
        if self.ig.log_contour:
            contour_grid = np.log(contour_grid)
            vmin = -7
        else:
            vmin = None
        ax.contourf(xx, yy, contour_grid.reshape(xx.shape),
                    50, vmin=vmin, cmap='Blues')
1179278
def hist(P, edges, **kwargs):
  
  '''

  from matplotlib.collections import PatchCollection
  from matplotlib.patches     import Polygon

  # extract local options
  axis      = kwargs.pop( 'axis'      , plt.gca() )
  cindex    = kwargs.pop( 'cindex'    , None      )
  autoscale = kwargs.pop( 'autoscale' , True      )

  # set defaults
  kwargs.setdefault('edgecolor','k')

  # no color-index -> set transparent
  if cindex is None:
    kwargs.setdefault('facecolor',(0.,0.,0.,0.))

  # convert -> list of Polygons
  poly = []
  for p, xl, xu in zip(P, edges[:-1], edges[1:]):
    coor = np.array([
      [xl, 0.],
      [xu, 0.],
      [xu, p ],
      [xl, p ],
    ])
    poly.append(Polygon(coor))
  args = (poly)

  # convert patches -> matplotlib-objects
  p = PatchCollection(args,**kwargs)
  # add colors to patches
  if cindex is not None:
    p.set_array(cindex)
  # add patches to axis
  axis.add_collection(p)

  # rescale the axes manually
  if autoscale:
    # - get limits
    xlim = [ edges[0], edges[-1] ]
    ylim = [ 0       , np.max(P) ]
    # - set limits +/- 10% extra margin
    axis.set_xlim([xlim[0]-.1*(xlim[1]-xlim[0]),xlim[1]+.1*(xlim[1]-xlim[0])])
    axis.set_ylim([ylim[0]-.1*(ylim[1]-ylim[0]),ylim[1]+.1*(ylim[1]-ylim[0])])

  return p
1245357
def plot(self, bins=250, **kwargs):
        """"""
        # Data #
        counts = [sum(map(len, b.contigs)) for b in self.parent.bins]
        # Linear bins in logarithmic space #
        if 'log' in kwargs.get('x_scale', ''):
            start, stop = numpy.log10(1), numpy.log10(max(counts))
            bins = list(numpy.logspace(start=start, stop=stop, num=bins))
            bins.insert(0, 0)
        # Plot #
        fig = pyplot.figure()
        pyplot.hist(counts, bins=bins, color='gray')
        axes = pyplot.gca()
        # Information #
        title = 'Distribution of the total nucleotide count in the bins'
        axes.set_title(title)
        axes.set_xlabel('Number of nucleotides in a bin')
        axes.set_ylabel('Number of bins with that many nucleotides in them')
        # Save it #
        self.save_plot(fig, axes, **kwargs)
        pyplot.close(fig)
        # For convenience #
        return self
534978
def print_probabilities(state: State, ndigits: int = 4,
                        file: TextIO = None) -> None:
    
    prob = bk.evaluate(state.probabilities())
    for index, prob in np.ndenumerate(prob):
        prob = round(prob, ndigits)
        if prob == 0.0:
            continue
        ket = "".join([str(n) for n in index])
        print(ket, ":", prob, file=file)
578920
def predict_proba(self, L):
        
        n = L.shape[0]
        Y_p = np.random.rand(n, self.k)
        Y_p /= Y_p.sum(axis=1).reshape(-1, 1)
        return Y_p
1340800
def show_plot(t_array, th_array):
    
    th_mean = gv.mean(th_array)
    th_sdev = gv.sdev(th_array)
    thp = th_mean + th_sdev
    thm = th_mean - th_sdev
    plt.fill_between(t_array, thp, thm, color='0.8')
    plt.plot(t_array, th_mean, linewidth=0.5)
    plt.xlabel('$t$')
    plt.ylabel(r'$\theta(t)$')
    plt.savefig('pendulum.pdf', bbox_inches='tight')
    plt.show()
784822
def likelihood2(args):
    
    from matplotlib import gridspec

    p = OptionParser(likelihood2.__doc__)
    opts, args, iopts = p.set_image_options(args, figsize="10x5",
                                style="white", cmap="coolwarm")

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

    jsonfile, = args
    fig = plt.figure(figsize=(iopts.w, iopts.h))
    gs = gridspec.GridSpec(2, 2)
    ax1 = fig.add_subplot(gs[:, 0])
    ax2 = fig.add_subplot(gs[0, 1])
    ax3 = fig.add_subplot(gs[1, 1])
    plt.tight_layout(pad=3)
    pf = plot_panel(jsonfile, ax1, ax2, ax3, opts.cmap)

    root = fig.add_axes([0, 0, 1, 1])
    normalize_axes(root)

    image_name = "likelihood2.{}.".format(pf) + iopts.format
    savefig(image_name, dpi=iopts.dpi, iopts=iopts)
835200
def matplotlib_to_ginga_cmap(cm, name=None):
    """"""
    if name is None:
        name = cm.name
    arr = cm(np.arange(0, min_cmap_len) / np.float(min_cmap_len - 1))
    clst = arr[:, 0:3]
    return ColorMap(name, clst)
800662
def points(ys, width=None):
    '''
    '''
    if width is None:
        width = terminal.width()

    ys = np.array(ys)
    n = len(ys)
    y_min, y_max = np.min(ys), np.max(ys)
    n_bins = min(width, n)
    bins_per_n = float(n_bins) / float(n)
    # print n, n_bins, n_per_bin, bins_per_n
    sums = np.zeros(n_bins)
    counts = np.zeros(n_bins)
    for i, y in enumerate(ys):
        bin = int(i * bins_per_n)
        sums[bin] += y
        counts[bin] += 1
    bin_means = sums / counts
    # we want the lowest bin_height to be 0.0, and highest bin_height to be 1.0
    bin_heights = normalize(bin_means)
    bin_chars = (bin_heights * (len(terminal.bars) - 1)).astype(int)
    # print sums, counts, bin_means
    cells = [terminal.bars[bin_char] for bin_char in bin_chars]
    print '[%+f]' % y_max
    print u''.join(cells)
    print '[%+f]' % y_min