当前位置: 首页>>代码示例>>Python>>正文


Python mpld3.save_html函数代码示例

本文整理汇总了Python中mpld3.save_html函数的典型用法代码示例。如果您正苦于以下问题:Python save_html函数的具体用法?Python save_html怎么用?Python save_html使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了save_html函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: plot

    def plot(self, notebook=False, colormap='polar', scale=1, maptype='points', show=True, savename=None):

        # make a spatial map based on the scores
        fig = pyplot.figure(figsize=(12, 5))
        ax1 = pyplot.subplot2grid((2, 3), (0, 1), colspan=2, rowspan=2)
        if maptype is 'points':
            ax1, h1 = pointmap(self.scores, colormap=colormap, scale=scale, ax=ax1)
        elif maptype is 'image':
            ax1, h1 = imagemap(self.scores, colormap=colormap, scale=scale, ax=ax1)
        fig.add_axes(ax1)

        # make a scatter plot of sampled scores
        ax2 = pyplot.subplot2grid((2, 3), (1, 0))
        ax2, h2, samples = scatter(self.scores, colormap=colormap, scale=scale, thresh=0.01, nsamples=1000, ax=ax2, store=True)
        fig.add_axes(ax2)

        # make the line plot of reconstructions from principal components for the same samples
        ax3 = pyplot.subplot2grid((2, 3), (0, 0))
        ax3, h3, linedata = tsrecon(self.comps, samples, ax=ax3)

        plugins.connect(fig, LinkedView(h2, h3[0], linedata))
        plugins.connect(fig, HiddenAxes())

        if show and notebook is False:
            mpld3.show()

        if savename is not None:
            mpld3.save_html(fig, savename)
        elif show is False:
            return mpld3.fig_to_html(fig)
开发者ID:mathisonian,项目名称:thunder,代码行数:30,代码来源:pca.py

示例2: generate_embedding

def generate_embedding(param_file, model_file, mnist_file, output_file=None,
                       param_key=None):
    predictor = optimus.load(model_file)
    params = biggie.Stash(param_file)
    param_key = sorted(params.keys())[-1] if param_key is None else param_key
    predictor.param_values = params.get(param_key)

    train, valid, test = datatools.load_mnist_npz(mnist_file)
    idx = np.random.permutation(len(valid[0]))[:2000]
    x_in = valid[0][idx]
    y_true = valid[1][idx]
    z_out = predictor(x_in=x_in)['z_out']

    imgfiles = [datatools.generate_imagename(i, y)
                for i, y in enumerate(idx, y_true)]

    labels = ['<img src="{}{}" width=100 height=100>'.format(URL_BASE, img)
              for img in imgfiles]

    palette = seaborn.color_palette("Set3", 10)
    colors = np.asarray([palette[y] for y in y_true])
    fig = plt.figure(figsize=(10, 10))
    ax = fig.gca()
    handle = ax.scatter(z_out.T[0], z_out.T[1],
                        c=colors, s=75, alpha=0.66)

    tooltip = plugins.PointHTMLTooltip(
        handle, labels,
        voffset=10, hoffset=10)

    plugins.connect(fig, tooltip)
    plt.show()
    if output_file:
        with open(output_file, 'w') as fp:
            mpld3.save_html(fig, fp)
开发者ID:ejhumphrey,项目名称:mnistifolds,代码行数:35,代码来源:visualize.py

示例3: plot

    def plot(self, data, notebook=False, show=True, savename=None):

        fig = pyplot.figure()
        ncenters = len(self.centers)

        colorizer = Colorize()
        colorizer.get = lambda x: self.colors[int(self.predict(x)[0])]

        # plot time series of each center
        # TODO move into a time series plotting function in viz.plots
        for i, center in enumerate(self.centers):
            ax = pyplot.subplot2grid((ncenters, 3), (i, 0))
            ax.plot(center, color=self.colors[i], linewidth=5)
            fig.add_axes(ax)

        # make a scatter plot of the data
        ax2 = pyplot.subplot2grid((ncenters, 3), (0, 1), rowspan=ncenters, colspan=2)
        ax2, h2 = scatter(data, colormap=colorizer, ax=ax2)
        fig.add_axes(ax2)

        plugins.connect(fig, HiddenAxes())

        if show and notebook is False:
            mpld3.show()

        if savename is not None:
            mpld3.save_html(fig, savename)

        elif show is False:
            return mpld3.fig_to_html(fig)
开发者ID:uklibaite,项目名称:thunder,代码行数:30,代码来源:kmeans.py

示例4: export_fmt

 def export_fmt(self, filename, size, sizeofsizes, format):
     if sizeofsizes == 1:
         size = 'none'
     if format is 'png':
         add = '.png'
     elif format is 'pgf':
         add = '.pgf'
     elif format is 'pdf':
         add = '.pdf'
     elif format is 'html':
         add = '.html'
     elif format is 'svg':
         # save as pdf, then pdf2svg
         self.fig.savefig(filename + self.sizestring[size] + '.pdf',
                     bbox_extra_artists=self.artists, bbox_inches='tight',
                     transparent=True)
         os.system('pdf2svg ' + filename + self.sizestring[size] + '.pdf ' +
                   filename + self.sizestring[size] + '.svg')
         os.remove(filename + self.sizestring[size] + '.pdf')
     elif format is 'websvg':
         add = 'web.svg'
     if (format is not 'svg') and (format is not 'html'):
         self.fig.savefig(filename + self.sizestring[size] + add,
                     bbox_extra_artists=self.artists, bbox_inches='tight',
                     transparent=True)
     if format is 'html':
         add = '.html'
         mpld3.save_html(self.fig, filename + add)
         self.add_math_jax(filename + add)
     if format is 'pgf':
         self.remove_font_sizes(filename + self.sizestring[size] + add)
开发者ID:alexhagen,项目名称:pyg,代码行数:31,代码来源:twod.py

示例5: main

def main(args):
    # Import data
    logger.info(u'Importing data with following parameters: \n\tWide: {0}\n\tDesign: {1}\n\tUnique ID: {2}\n\tGroup Column: {3}'.format(args.fname, args.dname, args.uniqID, args.group))
    dat = wideToDesign(args.fname, args.dname, args.uniqID, args.group)
    dat.wide.convert_objects(convert_numeric=True)

    fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(20, 20))
    plt.subplots_adjust(hspace=0.3)

    # If there is group information, color by group.
    if hasattr(dat, 'group'):
        logger.info('Plotting sample distributions by group')
        legend1 = pltByTrt(dat, ax1)
    else:
        logger.info('Plotting sample distributions')
        pltBySample(dat, ax1)

    # Create Legend
    handles, labels = ax1.get_legend_handles_labels()
    ax1.legend(handles, labels, ncol=5, loc='upper right', fontsize=10)

    # Create second legend if there is group information
    if hasattr(dat, 'group'):
        ax1.add_artist(legend1)

    # Plot boxplot of samples
    pltBoxplot(dat, ax2)

    plt.savefig(args.ofig, format='pdf')
    mpld3.save_html(fig, args.ofig2, template_type='simple')
开发者ID:secimTools,项目名称:GalaxyTools,代码行数:30,代码来源:distribution.py

示例6: graphme

    def graphme(self, pngfilename="my_sample_png.png"):

        import numpy as np
        import matplotlib.pyplot as plt
        import matplotlib.dates as mdates
        import mpld3
        import datetime

        """ creating background info"""
        # create a plot with as may subplots as you choose
        fig, ax = plt.subplots()
        # add a grid to the background
        ax.grid(True, alpha = 0.2)
        # the x axis contains date
        fig.autofmt_xdate()
        # the dates are year, month
        ax.fmt_xdata = mdates.DateFormatter('%Y-%m')

        if self.table not in ['MS04314', 'MS00114', 'MS04334','MS04315','MS00115']:
            final_glitch = self.decide()

            dates = sorted(final_glitch.keys())
            dates2 = [x for x in dates if final_glitch[x]['mean'] != None and final_glitch[x]['mean'] != "None"]
            vals = [final_glitch[x]['mean'] for x in dates2]
            glitched_values = ax.plot(dates2, vals, 'b-')
            ax.legend(loc=4)
            ax.set_xlabel("dates")
            ax.set_ylabel("values")
            mpld3.show()
            mpld3.save_html(fig, 'my_output_html.html')
            import pylab
            pylab.savefig(pngfilename)
开发者ID:tinybike,项目名称:glitch,代码行数:32,代码来源:logic_glitch.py

示例7: test_interactive_shallowPP

def test_interactive_shallowPP(save_to_html=False):
    # Define left and right state (h,hu)
    ql = np.array([3.0, 5.0])
    qr = np.array([3.0, -5.0])
    # Define optional parameters (otherwise chooses default values)
    plotopts = {'g':1.0, 'time':2.0, 'tmax':5, 'hmax':10, 'humin':-15, 'humax':15}
    # Call interactive function (can be called without any argument)
    pt = shallow_water(ql,qr,**plotopts)
    if save_to_html:
        mpld3.save_html(pt, "test_shallow.html")
    mpld3.show()
开发者ID:BrisaDavis,项目名称:riemann,代码行数:11,代码来源:riemann_interactive.py

示例8: plot_param

def plot_param(df, path, param, units):
    fig, ax = plt.subplots(figsize=(8,6))
    df[param].plot(marker='o', ax=ax, legend=None)
    try:
        plt.ylabel(units[df.columns.get_loc(param)], labelpad=10)
    except:
        pass
    plt.xlabel('')
    plt.title(param + ' (time in UTC)')
    mpld3.save_html(fig, '{o}{p}.html'.format(o=path, p=param))
    plt.close(fig)
开发者ID:jsignell,项目名称:campbellsci-tools,代码行数:11,代码来源:web_plots_run_weekly.py

示例9: pcoa_plot_interactive

def pcoa_plot_interactive(profile, output_dir, dist_type):
    """Generate interactive PCoA plot.
    
    Args:
        profile (metagenomic_profile): Profile instance containing data. 
        output_dir (str): path to directory to save output
        dist_type (str): distance metric to use in PCoA.
        
    Returns:
        Path to output file. 
    """
    try:
        import mpld3 # Provides interactive graphs 
        import plugins # Custom mpld3 plugins    
    except ImportError:
        print("Could not import mpld3. Please install mpld3 or set 'interactive_plots' option to 'false.'")
        return
        
    __check_input(output_dir)
    
    df = __partition_abundance_data(profile)
    eig_pairs = __get_eig_pairs(df, dist_type)
    
    eig_pairs.sort()
    eig_pairs.reverse()
        
    PCo1 = eig_pairs[0][1]
    PCo2 = eig_pairs[1][1]
    
    # Begin plotting

    # Clear any current figures from the plot
    plt.clf()
    
    lgd_labels = __plot_markers_interactive(profile, PCo1, PCo2, a=0.7) # Main plotting 

    # Padding for x and y labels    
    ax = plt.gca()
    ax.tick_params(axis='both', which='major', pad=15)    
    
    plt.xlabel("PCo1", fontsize=16)
    plt.ylabel("PCo2", fontsize=16)
    
    fname = output_dir + "/" + "pcoa_" + dist_type + ".html"
    
    fig = plt.gcf()
    
    mpld3.plugins.connect(fig, plugins.TweakToolbar())
    mpld3.save_html(fig, fname)
    
    # Create legend 
    lgd_fname = __create_legend(lgd_labels, output_dir)
    
    return fname, lgd_fname
开发者ID:sierraa,项目名称:Comparative-Analysis,代码行数:54,代码来源:pcoa.py

示例10: plot_observed_aimpoints

def plot_observed_aimpoints(obs_aimpoints):
    """
    Make png and html (mpld3) plot of data in the ``obs_aimpoints`` table.
    """
    plt.close(1)
    fig = plt.figure(1, figsize=(8, 4))

    dates = DateTime(obs_aimpoints['mean_date'])
    years = dates.frac_year
    times = dates.secs
    ok = years > np.max(years) - float(opt.lookback) / 365.25
    obs_aimpoints = obs_aimpoints[ok]
    times = times[ok]

    lolims = {}
    uplims = {}
    for axis in ('dx', 'dy'):
        lolims[axis] = obs_aimpoints[axis] > 10
        uplims[axis] = obs_aimpoints[axis] < -10
        obs_aimpoints[axis] = obs_aimpoints[axis].clip(-10, 10)

    ok = ((np.abs(obs_aimpoints['target_offset_y']) < 100) &
          (np.abs(obs_aimpoints['target_offset_z']) < 100))
    plot_cxctime(times[ok], obs_aimpoints['dx'][ok], 'ob', label='CHIPX')
    plot_cxctime(times[ok], obs_aimpoints['dy'][ok], 'or', label='CHIPY')
    plot_cxctime(times[~ok], obs_aimpoints['dx'][~ok], '*b', label='CHIPX (offset > 100")')
    plot_cxctime(times[~ok], obs_aimpoints['dy'][~ok], '*r', label='CHIPY (offset > 100")')

    for axis in ('dx', 'dy'):
        if np.any(lolims[axis]):
            plt.errorbar(DateTime(times[lolims[axis]]).plotdate,
                         obs_aimpoints[axis][lolims[axis]], marker='.', yerr=1.5, lolims=True)
        if np.any(uplims[axis]):
            plt.errorbar(DateTime(times[uplims[axis]]).plotdate,
                         obs_aimpoints[axis][uplims[axis]], marker='.', yerr=1.5, uplims=True)

    plt.grid()
    ymax = max(12, np.max(np.abs(obs_aimpoints['dx'])), np.max(np.abs(obs_aimpoints['dy'])))
    plt.ylim(-ymax, ymax)
    plt.ylabel('Offset (arcsec)')
    plt.title('Observed aimpoint offsets')

    plt.legend(loc='upper left', fontsize='small', title='', framealpha=0.5)

    outroot = os.path.join(opt.data_root, 'observed_aimpoints')
    logger.info('Writing plot files {}.png,html'.format(outroot))
    mpld3.plugins.connect(fig, mpld3.plugins.MousePosition(fmt='.1f'))
    mpld3.save_html(fig, outroot + '.html')
    fig.patch.set_visible(False)
    plt.savefig(outroot + '.png', frameon=False)
开发者ID:sot,项目名称:aimpoint_mon,代码行数:50,代码来源:update_observed_aimpoints.py

示例11: plot_housing_temperature

def plot_housing_temperature():
    dat = fetch.Msid('aach1t', '2000:001', stat='daily')
    plt.close(1)
    fig = plt.figure(figsize=(8, 4))
    year = Time(dat.times, format='cxcsec').decimalyear
    plt.plot(year, dat.vals)
    plt.grid()
    plt.xlabel('Year')
    plt.ylabel('Temperature (degF)')
    plt.title('Aspect Camera housing temperature trend')

    outroot = os.path.join(opt.data_root, 'aca_housing_temperature')
    logger.info('Writing plot files {}.png,html'.format(outroot))
    mpld3.plugins.connect(fig, mpld3.plugins.MousePosition(fmt='.1f'))
    mpld3.save_html(fig, outroot + '.html')
    fig.patch.set_visible(False)
    plt.savefig(outroot + '.png', frameon=False)
开发者ID:sot,项目名称:aimpoint_mon,代码行数:17,代码来源:plot_aimpoint.py

示例12: test_interactive_linearPP

def test_interactive_linearPP(save_to_html=False):
    ## Define left and right state 
    ql = np.array([-2.0, 2.0]) 
    qr = np.array([0.0, -3.0])
    # Define two eigenvectors and eigenvalues (acoustics)
    zz = 2.0
    rho0 = 1.0
    r1 = np.array([zz,1.0])
    r2 = np.array([-zz,1.0])
    lam1 = zz/rho0
    lam2 = -zz/rho0
    plotopts={'q1min':-5, 'q1max':5, 'q2min':-5, 'q2max':5, 'domain':5, 'time':1, 
            'title1':"Pressure", 'title2':"Velocity"}
    pt = linear_phase_plane(ql,qr,r1,r2,lam1,lam2,**plotopts)
    if save_to_html:
        mpld3.save_html(pt, "test_linearPP.html")
    mpld3.show()
开发者ID:BrisaDavis,项目名称:riemann,代码行数:17,代码来源:riemann_interactive.py

示例13: show_mpld3

    def show_mpld3(self,fig,ax,points,xl_list,xl_labels):
        import mpld3
        from mpld3 import plugins
        import pandas as pd

        # Define some CSS to control our custom labels
        css = """
        table
        {
          border-collapse: collapse;
        }
        th
        {
          color: #000000;
          background-color: #ffffff;
        }
        td
        {
          background-color: #cccccc;
        }
        table, th, td
        {
          font-family:Arial, Helvetica, sans-serif;
          border: 1px solid black;
          text-align: right;
          font-size: 10px;
        }
        """
        df = pd.DataFrame(index=xl_labels)

        sorted_keys=sorted(xl_list[0].keys())

        for k in sorted_keys:
            df[k] = np.array([xl[k] for xl in xl_list])

        labels = []
        for i in range(len(xl_labels)):
            label = df.ix[[i], :].T
            # .to_html() is unicode; so make leading 'u' go away with str()
            labels.append(str(label.to_html()))

        tooltip = plugins.PointHTMLTooltip(points, labels,
                                   voffset=10, hoffset=10, css=css)
        plugins.connect(fig, tooltip)
        mpld3.save_html(fig,"output.html")
开发者ID:j-ma-bu-l-l-ock,项目名称:imp,代码行数:45,代码来源:xltable.py

示例14: downloadVideoAndEntropy

def downloadVideoAndEntropy(f, frame):
    fhandle = open(f, 'ab')
    ftp.retrbinary('RETR ' + f, fhandle.write)
    cap = cv2.VideoCapture(f)
    if cap.isOpened():
        cap.set(1, frame)
        ret, newframe = cap.read()
        if ret:
            newname = f.split(".")[0]
            finalname = newname + '_frame_' + str(frame) + '.png'
            cv2.imwrite(finalname, newframe)
            colorIm = Image.open(finalname)
            greyIm = colorIm.convert('L')
            colorIm = np.array(colorIm)
            greyIm = np.array(greyIm)
            N = 5
            S = greyIm.shape
            E = np.array(greyIm)
            for row in range(S[0]):
                for col in range(S[1]):
                    Lx = np.max([0, col - N])
                    Ux = np.min([S[1], col + N])
                    Ly = np.max([0, row - N])
                    Uy = np.min([S[0], row + N])
                    region = greyIm[Ly:Uy, Lx:Ux].flatten()
                    E[row, col] = entropy(region)
            grayImage = cv2.applyColorMap(greyIm, cv2.COLOR_BGR2GRAY)
            entropyImage = cv2.applyColorMap(greyIm, cv2.COLORMAP_JET)
            cv2.imwrite('gray_' + finalname, greyIm)
            # cv2.imwrite('color_' + finalname, entropyImage)
            a = np.empty_like(E)
            a[:, :] = E
            a = np.flipud(a)
            fig = plt.figure()
            plt.imshow(a, cmap=plt.get_cmap("jet"), origin="lower")
            plt.xlabel('Entropy in 10x10 neighborhood')
            plt.colorbar()
            plt.savefig('color_' + finalname, bbox_inches='tight')
            plt.imshow(E, cmap=plt.get_cmap("jet"), origin="lower")
            plt.plot()
            htmlname = newname + '_frame_' + str(frame) + '.html'
            mpld3.save_html(fig, htmlname)
            # mpld3.fig_to_html(fig, template_type="simple")
            print 'finished!'
    cap.release()
开发者ID:severagee,项目名称:Bee-GUI-WebApp,代码行数:45,代码来源:app.py

示例15: construct_plot

    def construct_plot(self, save_template=False, template_name="model.html"):
        # build plot data
        fig, ax = plt.subplots(subplot_kw=dict(axisbg='#EEEEEE'))
        scatter = ax.scatter(self.model_data[self.target].values,
                             self.model_data['prediction'].values.astype(int),
                             c= 'r',
                             cmap=plt.cm.jet)
        ax.grid(color='white', linestyle='solid')
        ax.set_title("Actual (target) vs. prediction", size=20)
        plt.ylabel('prediction')
        plt.xlabel('actual')

        # create interactive tooltip, save as HTML
        tooltip = mpld3.plugins.PointLabelTooltip(scatter)
        mpld3.plugins.connect(fig, tooltip)
        if save_template:
            mpld3.save_html(fig, template_name)
        return fig
开发者ID:LucDemortier,项目名称:DjangoDemo,代码行数:18,代码来源:regression.py


注:本文中的mpld3.save_html函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。