Plot 2d histogram.

    Pars will be a dictionary containing:
        data, figure_id, vmax, title_str, xp,yp, searchrad
961955
def plot_zeropoint(pars):
    
    from matplotlib import pyplot as plt

    xp = pars['xp']
    yp = pars['yp']
    searchrad = int(pars['searchrad'] + 0.5)

    plt.figure(num=pars['figure_id'])
    plt.clf()

    if pars['interactive']:
        plt.ion()
    else:
        plt.ioff()

    plt.imshow(pars['data'], vmin=0, vmax=pars['vmax'],
               interpolation='nearest')
    plt.viridis()
    plt.colorbar()
    plt.title(pars['title_str'])
    plt.plot(xp + searchrad, yp + searchrad, color='red', marker='+',
             markersize=24)
    plt.plot(searchrad, searchrad, color='yellow', marker='+', markersize=120)
    plt.text(searchrad, searchrad, "Offset=0,0", verticalalignment='bottom',
             color='yellow')
    plt.xlabel("Offset in X (pixels)")
    plt.ylabel("Offset in Y (pixels)")
    if pars['interactive']:
        plt.show()

    if pars['plotname']:
        suffix = pars['plotname'][-4:]
        output = pars['plotname']
        if '.' not in suffix:
            output += '.png'
            format = 'png'
        else:
            if suffix[1:] in ['png', 'pdf', 'ps', 'eps', 'svg']:
                format = suffix[1:]
        plt.savefig(output, format=format)
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
1116638
def compute_histogram(values, edges, use_orig_distr=False):
    """"""

    if use_orig_distr:
        return values

    # ignoring invalid values: Inf and Nan
    values = check_array(values).compressed()

    hist, bin_edges = np.histogram(values, bins=edges, density=True)
    hist = preprocess_histogram(hist, values, edges)

    return hist
768221
def _parse_track_dim(self,d1,interp=True,phys=False):
        """"""
        if interp: interpStr= 'interpolated'
        else: interpStr= ''
        if d1.lower() == 'x':
            tx= self.__dict__['_%sObsTrackXY' % interpStr][:,0]
        elif d1.lower() == 'y':
            tx= self.__dict__['_%sObsTrackXY' % interpStr][:,1]
        elif d1.lower() == 'z':
            tx= self.__dict__['_%sObsTrackXY' % interpStr][:,2]
        elif d1.lower() == 'r':
            tx= self.__dict__['_%sObsTrack' % interpStr][:,0]
        elif d1.lower() == 'phi':
            tx= self.__dict__['_%sObsTrack' % interpStr][:,5]
        elif d1.lower() == 'vx': 
            tx= self.__dict__['_%sObsTrackXY' % interpStr][:,3]
        elif d1.lower() == 'vy':
            tx= self.__dict__['_%sObsTrackXY' % interpStr][:,4]
        elif d1.lower() == 'vz':
            tx= self.__dict__['_%sObsTrackXY' % interpStr][:,5]
        elif d1.lower() == 'vr':
            tx= self.__dict__['_%sObsTrack' % interpStr][:,1]
        elif d1.lower() == 'vt':
            tx= self.__dict__['_%sObsTrack' % interpStr][:,2]
        elif d1.lower() == 'll':
            tx= self.__dict__['_%sObsTrackLB' % interpStr][:,0]
        elif d1.lower() == 'bb':
            tx= self.__dict__['_%sObsTrackLB' % interpStr][:,1]
        elif d1.lower() == 'dist':
            tx= self.__dict__['_%sObsTrackLB' % interpStr][:,2]
        elif d1.lower() == 'pmll':
            tx= self.__dict__['_%sObsTrackLB' % interpStr][:,4]
        elif d1.lower() == 'pmbb':
            tx= self.__dict__['_%sObsTrackLB' % interpStr][:,5]
        elif d1.lower() == 'vlos':
            tx= self.__dict__['_%sObsTrackLB' % interpStr][:,3]
        if phys and (d1.lower() == 'x' or d1.lower() == 'y' \
                         or d1.lower() == 'z' or d1.lower() == 'r'):
            tx= copy.copy(tx)
            tx*= self._ro
        if phys and (d1.lower() == 'vx' or d1.lower() == 'vy' \
                         or d1.lower() == 'vz' or d1.lower() == 'vr' \
                         or d1.lower() == 'vt'):
            tx= copy.copy(tx)
            tx*= self._vo
        return tx
1351816
def overlay_histogram(df, path, palette=None):
    
    if palette is None:
        palette = plotly.colors.DEFAULT_PLOTLY_COLORS * 5

    hist = Plot(path=path + "NanoComp_OverlayHistogram.html",
                title="Histogram of read lengths")
    hist.html, hist.fig = plot_overlay_histogram(df, palette, title=hist.title)
    hist.save()

    hist_norm = Plot(path=path + "NanoComp_OverlayHistogram_Normalized.html",
                     title="Normalized histogram of read lengths")
    hist_norm.html, hist_norm.fig = plot_overlay_histogram(
        df, palette, title=hist_norm.title, histnorm="probability")
    hist_norm.save()

    log_hist = Plot(path=path + "NanoComp_OverlayLogHistogram.html",
                    title="Histogram of log transformed read lengths")
    log_hist.html, log_hist.fig = plot_log_histogram(df, palette, title=log_hist.title)
    log_hist.save()

    log_hist_norm = Plot(path=path + "NanoComp_OverlayLogHistogram_Normalized.html",
                         title="Normalized histogram of log transformed read lengths")
    log_hist_norm.html, log_hist_norm.fig = plot_log_histogram(
        df, palette, title=log_hist_norm.title, histnorm="probability")
    log_hist_norm.save()

    return [hist, hist_norm, log_hist, log_hist_norm]
932339
def get_figure(neuron, plane, title):
    ''''''
    data = list(_make_trace(neuron, plane))
    axis = dict(
        gridcolor='rgb(255, 255, 255)',
        zerolinecolor='rgb(255, 255, 255)',
        showbackground=True,
        backgroundcolor='rgb(230, 230,230)'
    )

    if plane != '3d':
        soma_2d = [
            # filled circle
            {
                'type': 'circle',
                'xref': 'x',
                'yref': 'y',
                'fillcolor': 'rgba(50, 171, 96, 0.7)',
                'x0': neuron.soma.center[0] - neuron.soma.radius,
                'y0': neuron.soma.center[1] - neuron.soma.radius,
                'x1': neuron.soma.center[0] + neuron.soma.radius,
                'y1': neuron.soma.center[1] + neuron.soma.radius,

                'line': {
                    'color': 'rgba(50, 171, 96, 1)',
                },
            },
        ]

    else:
        soma_2d = []
        theta = np.linspace(0, 2 * np.pi, 100)
        phi = np.linspace(0, np.pi, 100)
        z = np.outer(np.ones(100), np.cos(phi)) + neuron.soma.center[2]
        r = neuron.soma.radius
        data.append(
            go.Surface(
                x=(np.outer(np.cos(theta), np.sin(phi)) + neuron.soma.center[0]) * r,
                y=(np.outer(np.sin(theta), np.sin(phi)) + neuron.soma.center[1]) * r,
                z=z * r,
                cauto=False,
                surfacecolor=['black'] * len(z),
                showscale=False,
            )
        )

    layout = dict(
        autosize=True,
        title=title,
        scene=dict(  # This is used for 3D plots
            xaxis=axis, yaxis=axis, zaxis=axis,
            camera=dict(up=dict(x=0, y=0, z=1), eye=dict(x=-1.7428, y=1.0707, z=0.7100,)),
            aspectmode='data'
        ),
        yaxis=dict(scaleanchor="x"),  # This is used for 2D plots
        shapes=soma_2d,
    )

    res = dict(data=data, layout=layout)
    return res
1225394
def _process_hist(self, hist):
        
        edges, hvals, widths, lims, isdatetime = super(SideHistogramPlot, self)._process_hist(hist)
        offset = self.offset * lims[3]
        hvals *= 1-self.offset
        hvals += offset
        lims = lims[0:3] + (lims[3] + offset,)
        return edges, hvals, widths, lims, isdatetime
862015
def plot_hist(image, threshold=0., fit_line=False, normfreq=True,
    ## plot label arguments
    title=None, grid=True, xlabel=None, ylabel=None,
    ## other plot arguments
    facecolor='green', alpha=0.75):
    
    img_arr = image.numpy().flatten()
    img_arr = img_arr[np.abs(img_arr) > threshold]

    if normfreq != False:
        normfreq = 1. if normfreq == True else normfreq
    n, bins, patches = plt.hist(img_arr, 50, normed=normfreq, facecolor=facecolor, alpha=alpha)

    if fit_line:
        # add a 'best fit' line
        y = mlab.normpdf( bins, img_arr.mean(), img_arr.std())
        l = plt.plot(bins, y, 'r--', linewidth=1)

    if xlabel is not None:
        plt.xlabel(xlabel)
    if ylabel is not None:
        plt.ylabel(ylabel)
    if title is not None:
        plt.title(title)

    plt.grid(grid)
    plt.show()
1068482
def draw_slices(hist, func=np.sum, **kwargs):
    
    from mpl_toolkits.axes_grid1 import make_axes_locatable
    kwargs.setdefault('ls','-')
    ax = plt.gca()

    data = hist

    # Slices
    vslice = func(data,axis=0)
    hslice = func(data,axis=1)

    npix = np.array(data.shape)
    #xlim,ylim = plt.array(zip([0,0],npix-1))
    xlim = ax.get_xlim()
    ylim = ax.get_ylim()
    #extent = ax.get_extent()
    #xlim =extent[:2]
    #ylim = extent[2:]

    # Bin centers
    xbin = np.linspace(xlim[0],xlim[1],len(vslice))#+0.5 
    ybin = np.linspace(ylim[0],ylim[1],len(hslice))#+0.5
    divider = make_axes_locatable(ax)
    
    #gh2 = pywcsgrid2.GridHelperSimple(wcs=self.header, axis_nums=[2, 1])
    hax = divider.append_axes("right", size=1.2, pad=0.05,sharey=ax,
                              axes_class=axes_divider.LocatableAxes)
    hax.axis["left"].toggle(label=False, ticklabels=False)
    #hax.plot(hslice, plt.arange(*ylim)+0.5,'-') # Bin center
    hax.plot(hslice, ybin, **kwargs) # Bin center
    hax.xaxis.set_major_locator(MaxNLocator(4,prune='both'))
    hax.set_ylim(*ylim)

    #gh1 = pywcsgrid2.GridHelperSimple(wcs=self.header, axis_nums=[0, 2])
    vax = divider.append_axes("top", size=1.2, pad=0.05, sharex=ax,
                              axes_class=axes_divider.LocatableAxes)
    vax.axis["bottom"].toggle(label=False, ticklabels=False)
    vax.plot(xbin, vslice, **kwargs) 
    vax.yaxis.set_major_locator(MaxNLocator(4,prune='lower'))
    vax.set_xlim(*xlim)

    return vax,hax
212
def plot_images(images, ax, ims_per_row=5, padding=5, digit_dimensions=(28, 28),
                cmap=matplotlib.cm.binary, vmin=None, vmax=None):
    """"""
    N_images = images.shape[0]
    N_rows = (N_images - 1) // ims_per_row + 1
    pad_value = np.min(images.ravel())
    concat_images = np.full(((digit_dimensions[0] + padding) * N_rows + padding,
                             (digit_dimensions[1] + padding) * ims_per_row + padding), pad_value)
    for i in range(N_images):
        cur_image = np.reshape(images[i, :], digit_dimensions)
        row_ix = i // ims_per_row
        col_ix = i % ims_per_row
        row_start = padding + (padding + digit_dimensions[0]) * row_ix
        col_start = padding + (padding + digit_dimensions[1]) * col_ix
        concat_images[row_start: row_start + digit_dimensions[0],
                      col_start: col_start + digit_dimensions[1]] = cur_image
    cax = ax.matshow(concat_images, cmap=cmap, vmin=vmin, vmax=vmax)
    plt.xticks(np.array([]))
    plt.yticks(np.array([]))
    return cax
708005
def plot_eps_data_hist(self, dfs):
        
        # check if this is a DC inversion
        if 'datum' in dfs[0]:
            dc_inv = True
        else:
            dc_inv = False

        nr_y = len(dfs)
        size_y = 5 / 2.54 * nr_y
        if dc_inv:
            nr_x = 1
        else:
            nr_x = 3
        size_x = 15 / 2.54

        fig, axes = plt.subplots(nr_y, nr_x, figsize=(size_x, size_y))
        axes = np.atleast_2d(axes)

        # plot initial data errors
        df = dfs[0]
        if dc_inv:
            ax = axes[0, 0]
            ax.hist(
                df['datum'] / df['eps_r'],
                100,
            )
            ax.set_xlabel(r'$-log(|R|) / \epsilon_r$')
            ax.set_ylabel(r'count')
        else:
            # complex inversion
            ax = axes[0, 0]
            ax.hist(
                df['-log(|R|)'] / df['eps'],
                100,
            )
            ax.set_xlabel(r'$-log(|R|)$')
            ax.set_ylabel(r'count')

            ax = axes[0, 1]
            ax.hist(
                df['-log(|R|)'] / df['eps_r'],
                100,
            )
            ax.set_xlabel(r'$-log(|R|) / \epsilon_r$')
            ax.set_ylabel(r'count')

            ax = axes[0, 2]
            phase_data = df['-Phase(rad)'] / df['eps_p']
            if not np.all(np.isinf(phase_data) | np.isnan(phase_data)):
                ax.hist(
                    phase_data,
                    100,
                )
            ax.set_xlabel(r'$-\phi[rad] / \epsilon_p$')
            ax.set_ylabel(r'count')

        # iterations
        for it, df in enumerate(dfs[1:]):
            ax = axes[1 + it, 0]
            ax.hist(
                df['psi'],
                100
            )
            rms = np.sqrt(
                1 / df['psi'].shape[0] *
                np.sum(
                    df['psi'] ** 2
                )
            )
            ax.axvline(rms, color='k', linestyle='dashed')
            ax.set_title('iteration: {0}'.format(it))
            ax.set_xlabel('psi')
            ax.set_ylabel(r'count')

            ax = axes[1 + it, 1]
            Rdat = df['Re(d)']
            Rmod = df['Re(f(m))']

            ax.scatter(
                Rdat,
                Rmod,
            )
            ax.set_xlabel(r'$log(R_{data}~[\Omega])$')
            ax.set_ylabel(r'$log(R_{mod}~[\Omega])$')

            ax = axes[1 + it, 2]
            phidat = df['Im(d)']
            phimod = df['Im(f(m))']

            ax.scatter(
                phidat,
                phimod,
            )
            ax.set_xlabel(r'$\phi_{data}~[mrad]$')
            ax.set_ylabel(r'$\phi_{mod}~[mrad]$')

        fig.tight_layout()
        fig.savefig('eps_plot_hist.png', dpi=300)
799393
def plot_hpars(HDD, hpars, sym):
    
    plt.figure(num=HDD['hyst'])
    X, Y = [], []
    X.append(0)
    Y.append(old_div(float(hpars['hysteresis_mr_moment']), float(
        hpars['hysteresis_ms_moment'])))
    X.append(float(hpars['hysteresis_bc']))
    Y.append(0)
    plt.plot(X, Y, sym)
    bounds = plt.axis()
    n4 = 'Ms: ' + '%8.2e' % (float(hpars['hysteresis_ms_moment'])) + ' Am^2'
    plt.text(bounds[1] - .9 * bounds[1], -.9, n4)
    n1 = 'Mr: ' + '%8.2e' % (float(hpars['hysteresis_mr_moment'])) + ' Am^2'
    plt.text(bounds[1] - .9 * bounds[1], -.7, n1)
    n2 = 'Bc: ' + '%8.2e' % (float(hpars['hysteresis_bc'])) + ' T'
    plt.text(bounds[1] - .9 * bounds[1], -.5, n2)
    if 'hysteresis_xhf' in list(hpars.keys()):
        n3 = r'Xhf: ' + '%8.2e' % (float(hpars['hysteresis_xhf'])) + ' m^3'
        plt.text(bounds[1] - .9 * bounds[1], -.3, n3)
    plt.figure(num=HDD['deltaM'])
    X, Y, Bcr = [], [], ""
    if 'hysteresis_bcr' in list(hpars.keys()):
        X.append(float(hpars['hysteresis_bcr']))
        Y.append(0)
        Bcr = float(hpars['hysteresis_bcr'])
    plt.plot(X, Y, sym)
    bounds = plt.axis()
    if Bcr != "":
        n1 = 'Bcr: ' + '%8.2e' % (Bcr) + ' T'
        plt.text(bounds[1] - .5 * bounds[1], .9 * bounds[3], n1)
1357845
def get_histogram(data):
    

    count = len(data)

    if count < 2:
        raise StatisticsError('Too few data points ({}) for get_histogram'.format(count))

    min_ = data[0]
    max_ = data[-1]
    std = stdev(data)

    bins = get_histogram_bins(min_, max_, std, count)

    res = {x: 0 for x in bins}

    for value in data:
        for bin_ in bins:
            if value <= bin_:
                res[bin_] += 1
                break

    return sorted(iteritems(res))
1006143
def mini_histogram(series, **kwargs):
    
    imgdata = BytesIO()
    plot = _plot_histogram(series, figsize=(2, 0.75), **kwargs)
    plot.axes.get_yaxis().set_visible(False)

    if LooseVersion(matplotlib.__version__) <= '1.5.9':
        plot.set_axis_bgcolor("w")
    else:
        plot.set_facecolor("w")

    xticks = plot.xaxis.get_major_ticks()
    for tick in xticks[1:-1]:
        tick.set_visible(False)
        tick.label.set_visible(False)
    for tick in (xticks[0], xticks[-1]):
        tick.label.set_fontsize(8)
    plot.figure.subplots_adjust(left=0.15, right=0.85, top=1, bottom=0.35, wspace=0, hspace=0)
    plot.figure.savefig(imgdata)
    imgdata.seek(0)
    result_string = 'data:image/png;base64,' + quote(base64.b64encode(imgdata.getvalue()))
    plt.close(plot.figure)
    return result_string
90690
def plot(self, data):
    

    import IPython

    if not isinstance(data, dict) or not all(isinstance(v, pd.DataFrame) for v in data.values()):
      raise ValueError('Expect a dictionary where the values are all dataframes.')

    gfsg = GenericFeatureStatisticsGenerator()
    data = [{'name': k, 'table': self._remove_nonascii(v)} for k, v in six.iteritems(data)]
    data_proto = gfsg.ProtoFromDataFrames(data)
    protostr = base64.b64encode(data_proto.SerializeToString()).decode("utf-8")
    html_id = 'f' + datalab.utils.commands.Html.next_id()

    HTML_TEMPLATE = """<link rel="import" href="/nbextensions/gcpdatalab/extern/facets-jupyter.html" >
        <facets-overview id="{html_id}"></facets-overview>
        <script>
          document.querySelector("#{html_id}").protoInput = "{protostr}";
        </script>"""
    html = HTML_TEMPLATE.format(html_id=html_id, protostr=protostr)
    return IPython.core.display.HTML(html)
76643
def heatmap(x, y, step=None, min_pt=None, max_pt=None,
                 colormap='Blues', alpha=1, grid=False,
                 colorbar=True, scale='lin',
                 vmax='auto', vmin='auto', crop=True):
    
    (x_vec, y_vec, hist_matrix) = calc_2d_hist(x, y, step, min_pt, max_pt)

    # simple in this case because it is positive counts
    if scale == 'log':
        for row in hist_matrix:
            for i, el in enumerate(row):
                row[i] = 0 if row[i] == 0 else log10(row[i])

    # plot
    fig = plt.figure()
    init_heatmap(x_vec, y_vec, hist_matrix, fig, colormap=colormap,
                 alpha=alpha, grid=grid, colorbar=colorbar,
                 vmax=vmax, vmin=vmin, crop=crop)

    return fig
1251000
def _condense(self, data):
    '''
    
    '''
    rval = {}
    for resolution,histogram in data.items():
      for value,count in histogram.items():
        rval[ value ] = count + rval.get(value,0)
    return rval