def plot_curve(
    func: Callable[[np.ndarray], np.ndarray] = lambda x: 1 + (x - 2) ** 2,
    x_min: int = 0,
    x_max: int = 5,
    renderer: hv.renderer = hv.renderer("bokeh"),
):

    xs = np.linspace(x_min, x_max, 100)
    ys = [func(x) for x in xs]

    curve = hv.Curve((xs, ys), "x", hv.Dimension("f(x)"), label="Graph of f")

    curve.opts(opts.Curve(height=600, width=900, line_width=2.50, tools=["hover"]))

    # Create plot and save it as html file. We create the plot depending on the input
    # parameter renderer either via bokeh or via plotly.
    if renderer == "bokeh":
        renderer = hv.renderer("bokeh")
        # Using renderer save
        renderer.save(curve, "bokeh")
    elif renderer == "plotly":
        renderer = hv.renderer("plotly").get_plot(curve).state
        plotly.offline.plot(renderer, filename="plotly.html")
    elif renderer == "online":
        hv.save(curve, 'browse_me.html', )
Exemple #2
0
def hv_bokeh():
    import holoviews as hv
    hv.renderer('bokeh')
    prev_backend = hv.Store.current_backend
    hv.Store.current_backend = 'bokeh'
    yield
    hv.Store.current_backend = prev_backend
Exemple #3
0
def hv_mpl():
    import holoviews as hv
    hv.renderer('matplotlib')
    prev_backend = hv.Store.current_backend
    hv.Store.current_backend = 'matplotlib'
    yield
    hv.Store.current_backend = prev_backend
Exemple #4
0
def explicitPathHoloviewsGraph():
    hv.extension('bokeh')
    #%opts Graph [width=400 height=400]
    N = 8
    node_indices = np.arange(N)
    #using index as indicator of the node number
    #source reveals the point of departure a1
    source = np.zeros(
        N
    )  #every edge starts from node 0 - numpy array of zeros : [0. 0. 0. 0. 0. 0. 0. 0.]
    #target reveals the point of arrival a2
    target = node_indices  #numpy array of range : [0 1 2 3 4 5 6 7]

    padding = dict(x=(-1.2, 1.2),
                   y=(-1.2, 1.2))  #X and Y showed scale on the cartesian table

    simple_graph = hv.Graph(((source, target), )).redim.range(**padding)

    def bezier(start, end, control, steps=np.linspace(0, 1, 100)):
        return (1 - steps)**2 * start + 2 * (
            1 - steps) * steps * control + steps**2 * end

    x, y = simple_graph.nodes.array([0, 1]).T

    paths = []
    for node_index in node_indices:
        ex, ey = x[node_index], y[node_index]
        paths.append(
            np.column_stack([bezier(x[0], ex, 0),
                             bezier(y[0], ey, 0)]))

    bezier_graph = hv.Graph(
        ((source, target), (x, y, node_indices), paths)).redim.range(**padding)
    hv.renderer('bokeh').save(bezier_graph, 'out')
Exemple #5
0
    def update_hist(self):
        hv.extension("matplotlib")
        dcrop = (self.da_masked *
                 self.da_zone.sel(id=self.id_i)).isel(step=self.step)
        dcrop.name = self.da.name
        var_name = self.da.name
        if self.levels:
            hv_img = hv.Image(hv.Dataset(dcrop),
                              kdims=["longitude", "latitude"
                                     ]).opts(colorbar=True,
                                             color_levels=self.levels,
                                             cmap=self.colors)
            html_map = hv.renderer("matplotlib").html(hv_img)
        else:
            hv_img = hv.Image(hv.Dataset(dcrop),
                              kdims=["longitude",
                                     "latitude"]).opts(colorbar=True,
                                                       color_levels=30)
            html_map = hv.renderer("matplotlib").html(hv_img)

    # Si besoin de specifier le range : hv_img.redim.__getattribute__("range")(**{var_name:(self.vmin,self.vmax)}))

        dstack = dcrop.stack(z=("latitude", "longitude")).reset_index("z")
        dstack["z"] = range(len(dstack.z))
        dstack.name = self.da.name
        hv_dst = hv.Dataset(dstack)
        k = histogram(hv_dst, dynamic=True, name="Test")

        html = ''' <h4> Histogramme sur {} </h4> de {}'''.format(
            self.hist_name, self.variable)
        self.html2.value = html + hv.renderer("matplotlib").html(k) + html_map
Exemple #6
0
 def get_url(obj, path_):
     """Saves obj in path and returns an object with the url."""
     uuid_plot = path_ + str(uuid.uuid4())
     try:
         hv.renderer('bokeh').save(obj, uuid_plot)
         plot_path = '/geppetto/{}.html'.format(
             uuid_plot.split('webapp/')[1])
         return {'url': plot_path}
     except Exception as e:
         e.args = ["Error saving plot"] + list(e.args)
         raise e
Exemple #7
0
def render_graphs(input_df, layer):
    padding = dict(x=(-1.2, 1.2), y=(-1.2, 1.2))
    purchase_row = my_data.loc[my_data['Etype'] == 5].iloc[0]
    title_graph = '{}  Layer {}'.format(purchase_row['Source_Names'], layer)

    simple_graph = hv.Graph(
        ((input_df['Source_Names'], input_df['Destination_Names']), ),
        label=title_graph).redim.range(**padding)
    simple_graph()
    simple_graph.options(inspection_policy='edges', show_title=True)
    #hv.Layout([simple_graph.relabel(label=title)])
    hv.renderer('bokeh').server_doc(simple_graph)
Exemple #8
0
 def save(self, savedData):
     """Saves a savedData object as pickle file. Also saves a picture of the
     plot to be used as a thumbnail. Typically the input is the output from
     the savegen function.
     
     Args:
         savedData: savedData object containing data and metadata information
     """
     save_name = savedData.name
     with open('%s.p' % (save_name,), 'wb') as file:
         pickle.dump(savedData, file)
     hv.renderer('bokeh').save(savedData.plot.options(toolbar=None), './DataThumbnails/%s' % (save_name,), fmt='png')
Exemple #9
0
def myGraphTest():
    graphData = pd.read_csv('./myGraph.tsv', sep='\t')

    source = graphData['jobTitleNodeIndex'].values
    sourceLabels = graphData['jobTitleName'].values
    target = graphData['skillNodeIndex'].values
    targetLabels = graphData['skillName'].values

    padding = dict(x=(-1.2, 1.2),
                   y=(-1.2, 1.2))  #X and Y showed scale on the cartesian table

    myGraph = hv.Graph(((source, target), )).redim.range(**padding)
    hv.renderer('bokeh').save(myGraph, 'out')
Exemple #10
0
    def write_histogram_for_annotation_worktime_by_user(self, df: pandas.DataFrame) -> None:
        """
        教師付者ごとに教師付時間のヒストグラムを出力する。

        Args:
            df: タスク一覧のDataFrame

        """

        if len(df) == 0:
            logger.info("タスク一覧が0件のため出力しません。")
            return

        output_file_worktime = f"{self.histogram_outdir}/ヒストグラム-1回目の教師付者ごと-教師付時間"
        logger.debug(f"{output_file_worktime}.html を出力します。")
        output_file_first_worktime = f"{self.histogram_outdir}/ヒストグラム-1回目の教師付者ごと-1回目の教師付時間"
        logger.debug(f"{output_file_first_worktime}.html を出力します。")

        first_annotation_user_id_list = df["first_annotation_user_id"].dropna().unique().tolist()
        if len(first_annotation_user_id_list) == 0:
            logger.info("教師付したタスクが1つもないので、出力しません。")
            return

        histograms_worktime = []
        histograms_first_worktime = []
        for user_id in first_annotation_user_id_list:

            filtered_df = df[df["first_annotation_user_id"] == user_id]
            username = filtered_df.iloc[0]["first_annotation_username"]
            histograms_worktime.append(
                self._create_histogram_by_user(
                    filtered_df, "annotation_worktime_hour", "教師付時間[hour]", user_id=user_id, username=username
                )
            )
            histograms_first_worktime.append(
                self._create_histogram_by_user(
                    filtered_df, "first_annotation_worktime_hour", "1回目の教師付時間[hour]", user_id=user_id, username=username
                )
            )

        layout_worktime = (
            hv.Layout(histograms_worktime).cols(3).opts(hv.opts.Histogram(width=500), hv.opts.Layout(shared_axes=True))
        )
        hv.renderer("bokeh").save(layout_worktime, output_file_worktime)

        layout_first_worktime = (
            hv.Layout(histograms_first_worktime)
            .cols(3)
            .opts(hv.opts.Histogram(width=500), hv.opts.Layout(shared_axes=True))
        )
        hv.renderer("bokeh").save(layout_first_worktime, output_file_first_worktime)
Exemple #11
0
 def _render(self, doc, comm, root):
     from holoviews import Store, renderer
     if not Store.renderers:
         loaded_backend = (self.backend or 'bokeh')
         renderer(loaded_backend)
         Store.current_backend = loaded_backend
     backend = self.backend or Store.current_backend
     renderer = Store.renderers[backend]
     if backend == 'bokeh':
         renderer = renderer.instance(mode='server' if comm is None else 'default')
     kwargs = {'doc': doc, 'root': root} if backend == 'bokeh' else {}
     if comm:
         kwargs['comm'] = comm
     return renderer.get_plot(self.object, **kwargs)
def quicksave(plot_object: Any,
              outfile_basename: str,
              renderer: str = 'matplotlib',
              fmt: Optional[str] = None) -> None:
    """Quicksave function for a holoviews plot to a standalone html file.

    Parameters
    ----------
    plot_object - a holoviews layout object    
    outfile_basename - The base name of the output file.
    renderer - name of a holoviews renderer, e.g 'bokeh', 'matplotlib', or 'plotly'
    """
    hv.renderer(renderer).save(plot_object, outfile_basename, fmt=fmt)

    return
Exemple #13
0
def testHoloviews():
    ''''''
    hv.extension('bokeh')
    hv.renderer('matplotlib')
    station_info = pd.read_csv('./assets/station_info.csv')
    #station_info.head()
    scatter = hv.Scatter(station_info, 'services', 'ridership')
    #htmlOutput
    #render(scatter, './output.html', {'html':htmlOutput})
    #BOKEH RENDERER	#http://holoviews.org/user_guide/Deploying_Bokeh_Apps.html
    hv.renderer('bokeh').save(scatter, 'out')
    #IPYTHON RENDERER (works with dynamic maps by making a widget)   #http://holoviews.org/user_guide/Plots_and_Renderers.html
    #html = renderer.html(scatter)
    display_html(html, raw=True)
    return
Exemple #14
0
def cpu_boxplot():
    renderer = hv.renderer('bokeh')

    def datafunc_down(data):
        algo1_data = data['algo-1']
        algo2_data = data['algo-2']

        return hv.BoxWhisker(algo1_data, vdims='algo-1') + hv.BoxWhisker(
            algo2_data, vdims='algo-2')

    # def datafunc_up(data):
    #    return hv.BoxWhisker(data, vdims='cpu usage algo2')
    def cb():
        down_stream.send(get_cpu_boxplot_data())

    down_stream = hv.streams.Buffer(get_cpu_boxplot_data(),
                                    length=100,
                                    index=False)
    mem_dmap = hv.DynamicMap(datafunc_down, streams=[down_stream])

    # Render plot and attach periodic callback

    cb_attacher = PeriodicCallback(cb, 100)
    cb_attacher.start()
    return mem_dmap, cb_attacher
Exemple #15
0
def plot_holoviews_i(G, filename="graph.html"):
    import holoviews as hv

    extension = hv.extension('bokeh')
    renderer = hv.renderer('bokeh')
    graph_plot = hv.Graph.from_networkx(G, nx.layout.spring_layout)
    renderer.save(graph_plot, 'graph.html')
def fermi_surface_slices(arr: xr.DataArray,
                         n_slices=9,
                         ev_per_slice=0.02,
                         bin=0.01,
                         out=None,
                         **kwargs):
    import holoviews as hv  # pylint: disable=import-error
    slices = []
    for i in range(n_slices):
        high = -ev_per_slice * i
        low = high - bin
        image = hv.Image(arr.sum([
            d for d in arr.dims
            if d not in ['theta', 'beta', 'phi', 'eV', 'kp', 'kx', 'ky']
        ]).sel(eV=slice(low, high)).sum('eV'),
                         label='%g eV' % high)

        slices.append(image)

    layout = hv.Layout(slices).cols(3)
    if out is not None:
        renderer = hv.renderer('matplotlib').instance(fig='svg', holomap='gif')
        filename = path_for_plot(out)
        renderer.save(layout, path_for_holoviews(filename))
        return filename
    else:
        return layout
Exemple #17
0
    def plot_direction(self, avg_df, selected_bin_1, selected_bin_2,
                       selected_bin_3):
        """
        Create a HTML plot of the Magnitude Velocity data from the
        CSV file.
        :param avg_df:  Dataframe of the csv file
        :param selected_bin_1: Selected Bin 1.
        :param selected_bin_2: Selected Bin 2.
        :param selected_bin_3: Selected Bin 3.
        :return:
        """
        # Title
        title = "Water Direction"

        bin_1 = self.get_plot_earth_vel(avg_df, "Direction", 0, selected_bin_1,
                                        'Bin ' + str(selected_bin_1),
                                        "Direction", "Degrees")
        bin_2 = self.get_plot_earth_vel(avg_df, "Direction", 0, selected_bin_2,
                                        'Bin ' + str(selected_bin_2),
                                        "Direction", "Degrees")
        bin_3 = self.get_plot_earth_vel(avg_df, "Direction", 0, selected_bin_3,
                                        'Bin ' + str(selected_bin_3),
                                        "Direction", "Degrees")

        plots = (bin_1 * bin_2 * bin_3).relabel("Water Direction")
        plots.opts(legend_position='top_left')

        # Save the plot to a file
        renderer = hv.renderer('bokeh')
        bk_plot = renderer.get_plot(plots).state
        output_file(self.html_file, title=title)
        save(bk_plot)

        # Refresh the web view
        self.refresh_web_view_sig.emit()
def MakeHVGraph(G):
    # Set plot options
    print "Setting plot options"
    options = {
        'Graph':
        dict(node_size=5,
             edge_line_width=.2,
             height=1000,
             width=1000,
             xaxis=None,
             yaxis=None,
             inspection_policy='nodes')
    }
    padding = dict(x=(-1.2, 1.2), y=(-1.2, 1.2))
    # Make a holoviews graph
    print "Making the Interactive graph"
    Graph = hv.Graph.from_networkx(G, nx.spring_layout).redim.range(**padding)
    del G

    # This makes the html graph
    renderer = hv.renderer('bokeh')
    renderer.save(Graph, 'hvplot.html')
    plot = renderer.get_plot(Graph.options(options)).state
    from bokeh.io import output_file, save, show
    save(plot, 'hvplot.html')

    # Open the plot
    show(plot)
Exemple #19
0
def figsave(hvobj, filename, **args):
    """Saves a plot to an image file.

    Args:
        hvobj (holoviews object): Plot to be saved.
        filename (string): Filename (without extension).

    Kwargs:
        fmt (string): Image format (default: 'png'). Use 'gif' when saving
            animations.
        size (int): Figure size in percent (default: 100).
        dpi (int): Figure resolution in dots per inch.
        fps (int): Frames per second for animations.
    """
    fmt = args.pop('fmt', 'png')
    hv.renderer('matplotlib').instance(**args).save(hvobj, filename, fmt=fmt)
Exemple #20
0
def set_plotting_defaults():
    try:
        import holoviews as hv
        from bokeh.themes.theme import Theme
    except ImportError:
        return

    theme = Theme(json={"attrs": {"Axis": {
        "minor_tick_line_color": None,
        "major_tick_in": 0
    }}})

    hv.renderer("bokeh").theme = theme

    # once this issue https://github.com/pyviz/holoviews/issues/3319 is resolved,
    # then we can do this in a less hacky way for toolbar=None. For tools=["hover"],
    # though, we might still need this loop; try once the issue is resolved.

    elements = []
    for element in dir(hv.opts):
        # this filters out most things we don't want
        if not element[0].isupper():
            continue

        # still have issues with a few layout-like elements that don't use tools directly
        try:
            elements.append(getattr(hv.opts, element)(tools=["hover"], toolbar=None))
        except ValueError:
            elements.append(getattr(hv.opts, element)(toolbar=None))

    hv.opts.defaults(*elements)
    def generateHoloview(self, df, SSC, FSC, type, counter_max=50):
        renderer = hv.renderer('bokeh')
        body_points = hv.Scatter(df, SSC, FSC).opts(color='r', title='SSC vs FSC Default Gating')
        body_hist = body_points.hist(num_bins=50, dimension=[SSC, FSC])
        body = body_hist

        counter = 0

        for index in range(len(df.columns)):
            for index2 in range(index+1, len(df.columns)):
                col = df.columns[index]
                col2 = df.columns[index2]
                if col2 != col and col not in (SSC, FSC) and col2 not in (SSC, FSC) and counter < counter_max:
                    points = hv.Scatter(df, col, col2)
                    hist = points.hist(num_bins=50, dimension=[col, col2])
                    body += hist
                    counter += 1
        print(counter)
        try:
            body = body.opts(
                opts.Scatter(tools=['box_select', 'lasso_select']),
                opts.Layout(shared_axes=True, shared_datasource=True)).cols(2)
        except:
            body = body.opts(
                opts.Scatter(tools=['box_select', 'lasso_select']),
                opts.Layout(shared_axes=True, shared_datasource=True))
        renderer.save(body, os.path.join(self.directory, str(type)+"gating"))
Exemple #22
0
def plot_overlay_mpl():
    renderer = hv.renderer('matplotlib')
    a = ts.affpop_hand(region='D2d')
    obj = plot(region='D2d') * plot(a)['PC']
    obj = (plot(region='D2d') * plot(a)['SA1']) +\
        (plot(region='D2d') * plot(a)['RA']) +\
        (plot(region='D2d') * plot(a)['PC'])
Exemple #23
0
    def write_histogram_for_annotation_count_by_label(self, df: pandas.DataFrame) -> None:
        """
        アノテーションラベルごとのアノテーション数をヒストグラムで出力する。
        """
        if len(df) == 0:
            logger.info("タスク一覧が0件のため出力しない")
            return

        renderer = hv.renderer("bokeh")

        output_file = f"{self.histogram_outdir}/ヒストグラム-ラベルごとのアノテーション数"
        logger.debug(f"{output_file}.html を出力します。")

        histograms = []
        label_columns = [e for e in df.columns if e.startswith("label_")]

        for column in label_columns:
            label_name = column[len("label_") :]
            histogram_name = HistogramName(
                column=column, x_axis_label=f"'{label_name}'のアノテーション数", title=f"{label_name}"
            )
            hist = self._create_histogram(df, histogram_name=histogram_name)

            histograms.append(hist)

        # 軸範囲が同期しないようにする
        layout = hv.Layout(histograms).options(shared_axes=False).cols(3)
        renderer.save(layout, output_file)
Exemple #24
0
def network_util_graph():

    renderer = hv.renderer('bokeh')

    # Define DynamicMap callbacks returning Elements

    def network_map(data):
        plot = hv.Curve(data).options(title="Network utilization (algo1)",
                                      width=800,
                                      padding=0.1)
        return plot

    network_stream = hv.streams.Buffer(get_network_data(),
                                       length=500,
                                       index=False)

    def cb():
        network_stream.send(get_network_data())

    # Define DynamicMaps and display plot

    network_dmap = hv.DynamicMap(network_map, streams=[network_stream])

    # Render plot and attach periodic callback
    cb_attacher = PeriodicCallback(cb, 100)
    cb_attacher.start()
    return network_dmap, cb_attacher
Exemple #25
0
def serve_embedding(data):
    from .huddinge_browser import HuddingBrowser
    import holoviews as hv
    import traceback

    renderer = hv.renderer('bokeh')

    hb = HuddingBrowser(data)
    p = hb.holoview_plot()

    app = renderer.app(p)

    from tornado.ioloop import IOLoop
    from bokeh.server.server import Server

    loop = IOLoop.current()
    server = Server({'/': app}, port=0, io_loop=loop)

    def show_callback():
        server.show('/')

    loop.add_callback(show_callback)
    server.start()
    try:
        log.info("Starting loop")
        loop.start()
    except Exception as e:
        traceback.print_exc()

        server.stop()
def node_bundle_tab(filename):
    G = scripts.MakeNetworkxGraph.__makegraph__(sep_type='semicolon',
                                                nodes_df_link=filename)
    """ Make HV network """
    hv_graph = hv.Graph.from_networkx(G, nx.spring_layout,
                                      k=1).relabel('Force-Directed Spring')

    hv_graph.opts(width=650,
                  height=650,
                  xaxis=None,
                  yaxis=None,
                  padding=0.1,
                  node_size=hv.dim('size'),
                  node_color=hv.dim('node_type'),
                  cmap='YlOrBr',
                  edge_color=hv.dim('weight'),
                  edge_cmap='YlGnBu',
                  edge_line_width=hv.dim('weight'))

    bundle_graph_plot = bundle_graph(hv_graph)
    """ END HERE """

    # Output files to Flask
    renderer = hv.renderer('bokeh')
    # plot = renderer.get_plot(hv_graph, show=True).state
    bundle_plot = renderer.get_plot(bundle_graph_plot, show=True).state
    return bundle_plot
Exemple #27
0
def display_server(dmap_in):
    ### This is to render the chart in a web server to display as a dashboard!!
    renderer = hv.renderer('bokeh')
    #### You must have a Dynamic Map dmap to render these Bokeh objects on Servers
    app = renderer.app(dmap_in)
    server = renderer.app(dmap_in, show=True, new_window=True)
    display(server)
Exemple #28
0
def plot_phase_diagrams(filenames,fileout):
    for i in range(len(filenames)):
        print 'i: ',i
        ds = yt.load(filenames[i])
        center_guess = initial_center_guess(ds,track_name)
        halo_center = get_halo_center(ds,center_guess)
        rb = sym_refine_box(ds,halo_center)

        args = filenames[i].split('/')
        sim_label = args[-3]

        dens = np.log10(rb['H_nuclei_density'])
        temp = np.log10(rb['Temperature'])

        df = pd.DataFrame({'temp':temp, 'dens':dens})
        phase_scatter = hv.Scatter(df,kdims=['dens'],vdims=['temp'],label=sim_label)

        #phase_data = np.zeros((len(rb['H_nuclei_density']),2))
        #phase_data[:,0] = np.log10(rb['H_nuclei_density'])
        #phase_data[:,1] = np.log10(rb['Temperature'])

        #points = hv.Points(phase_data,kdims=['nH','temp'],label=sim_label)
        hv.opts({'Histogram': {'style': {'alpha':0.3, 'fill_color':'k'}}})
        xhist = (histogram(phase_scatter, bin_range=(-7.5, 1), dimension='dens',normed=True)) #,alpha=0.3, fill_color='k'))
        yhist = (histogram(phase_scatter, bin_range=(3, 8.5), dimension='temp',normed=True)) #,alpha=0.3, fill_color='k'))

        if i == 0:
            phase_plot = (datashade(phase_scatter,cmap=cm.plasma, dynamic=False,x_range=(-7.5,1),y_range=(3,8.5))) << yhist(plot=dict(width=125)) << xhist(plot=dict(height=125))
        else:
            plot2 = (datashade(phase_scatter,cmap=cm.plasma, dynamic=False,x_range=(-7.5,1),y_range=(3,8.5))) << yhist(plot=dict(width=125)) << xhist(plot=dict(height=125))
            phase_plot = phase_plot + plot2

        renderer = hv.renderer('bokeh').instance(fig='html')
        renderer.save(phase_plot, fileout)
    return
Exemple #29
0
def holoviews_extra_resources() -> Dict[str, List[str]]:
    import holoviews as hv

    renderer = hv.renderer("bokeh")
    js_html, css_html = renderer.html_assets()

    def _split_html_assets(js_html: str,
                           css_html: str) -> Dict[str, List[str]]:
        resources = _split_js_html_assets(js_html)
        resources.update(_split_css_html_assets(css_html))
        return resources

    def _split_js_html_assets(js_html: str) -> Dict[str, List[str]]:
        pattern = r'<script src="(.*?)" type="text/javascript"></script>'
        extra_javascript = re.findall(pattern, js_html)

        pattern = r'(<script type="text/javascript">.*?</script>)'
        extra_raw_javascript = re.findall(pattern, js_html, re.DOTALL)

        return {
            "extra_javascript": extra_javascript,
            "extra_raw_javascript": extra_raw_javascript,
        }

    def _split_css_html_assets(css_html: str) -> Dict[str, List[str]]:
        pattern = r'<link rel="stylesheet" href="(.*?)">'
        extra_css = re.findall(pattern, css_html)

        pattern = r"(<style>.*?</style>)"
        extra_raw_css = re.findall(pattern, css_html, re.DOTALL)

        return {"extra_css": extra_css, "extra_raw_css": extra_raw_css}

    return _split_html_assets(js_html, css_html)
Exemple #30
0
def myGraphTestSpringLayout():
    #EXAMPLE GRAPH EDGE LIST
    path = "/u/alfonsda/Documents/DOCTORAT_TAL/004projetOntologie/holoviews-examples/myGraphEdgeList.tsv"
    #100 000 PROFILES GRAPH EDGE LIST
    #path = "/u/alfonsda/Documents/DOCTORAT_TAL/004projetOntologie/002data/candidats/2016-09-15/fr/anglophone/sample100milFunctions/edgeListNoWeight.tsv"

    g = nx.read_edgelist(
        path,
        delimiter='\t',
        nodetype=str,
        data=(('weight', float),
              ('color', str)))  #the bigger the edgelist weight appears shorter
    padding = dict(x=(-1.2, 1.2),
                   y=(-1.2, 1.2))  #X and Y showed scale on the cartesian table

    renderer = hv.renderer('bokeh')

    myGraph = hv.Graph.from_networkx(
        g,
        nx.spring_layout,
        nodes=None,
        weight='weight',
        iterations=100,
        scale=2,
        center=(0, 0)
    )  #the spring layout uses Fruchterman-Reingold force-directed algorithm to lay out the graph
    #myGraph.redim.range(**padding).opts(plot=dict(color_index='Type', edge_color_index='Weight'),
    #                                    style=dict(cmap=['blue', 'red']))
    myGraph = myGraph.redim.range(**padding).opts(
        plot=dict(height=800,
                  width=1000,
                  node_fill_color='color',
                  edge_color_index='Weight'),
        style=dict(node_fill_color='red', cmap=['green', 'red']))
    renderer.save(myGraph, 'out')
Exemple #31
0
def plot_and_save_process_graph(holoviews_table, filename):
    '''plot and save process graph from output file made by loop.py
    '''

    process = hv.Scatter(holoviews_table, 'ms', 'process')
    renderer = hv.renderer('matplotlib')
    renderer.save(process, 'process_' + filename)
 def setUp(self):
     try:
         import scipy # noqa
     except:
         raise SkipTest('SciPy not available')
     try:
         import matplotlib # noqa
     except:
         raise SkipTest('SciPy not available')
     self.renderer = hv.renderer('matplotlib')
     np.random.seed(42)
     super(StatisticalCompositorTest, self).setUp()
Exemple #33
0
    def collect(self, blocks, figure_key="", subfig=0):
        '''collect holoview output.

        '''
        map_figure2text = {}
        extension = "svg"
        rst_text = '''.. figure:: /{absfn}
'''

        for block in blocks:
            if not hasattr(block, "hv"):
                continue

            if self.engine == "mpl":
                renderer = hv.Store.renderers['matplotlib'].instance(fig='svg')
                plot = renderer.get_plot(block.hv)
                rendered = renderer(plot, fmt="auto")
        
                (data, info) = rendered
            
                # remove special characters from filename. I think the docutils
                # system removes these from links which later causes problems
                # as the link does not point to the correct location of the
                # file.
                outname = Utils.quote_filename(
                    "%s_%s" % (self.template_name, block.title))
                outputpath = os.path.join(
                    self.outdir, '%s.%s' % (outname, extension))

                # save to file
                with open(outputpath, "w") as outf:
                    outf.write(data)

                # use absolute path
                absfn = os.path.abspath(outputpath)
                map_figure2text["#$hv %s$#" % block.title] = rst_text.format(
                    absfn=absfn)
            elif self.engine == "bokeh":
                renderer = hv.renderer("bokeh")
                html = renderer.static_html(block.hv)

                lines = [".. only:: html\n"] +\
                        ["   .. raw:: html\n"] +\
                        ["      " + x for x in html.splitlines()]

                lines = "\n".join(lines)
                
                map_figure2text["#$hv %s$#" % block.title] = lines

        return map_figure2text
Exemple #34
0
how to connnect a simple HoloViews plot with custom widgets and
combine them into a bokeh layout.

The app can be served using:

    bokeh serve --show player.py

"""
import numpy as np
import holoviews as hv

from bokeh.io import curdoc
from bokeh.layouts import layout
from bokeh.models import Slider, Button

renderer = hv.renderer('bokeh')

# Declare the HoloViews object
start = 0
end = 10
hmap = hv.HoloMap({i: hv.Image(np.random.rand(10,10)) for i in range(start, end+1)})

# Convert the HoloViews object into a plot
plot = renderer.get_plot(hmap)

def animate_update():
    year = slider.value + 1
    if year > end:
        year = start
    slider.value = year
 def setUp(self):
     self.renderer = holoviews.renderer('matplotlib')
     np.random.seed(42)
Exemple #36
0
from unittest import SkipTest

import numpy as np

from holoviews import renderer
from holoviews.core import Dimension, NdMapping, DynamicMap, HoloMap
from holoviews.element import Curve
from holoviews.element.comparison import ComparisonTestCase

try:
    from holoviews.plotting.bokeh.widgets import BokehServerWidgets
    from bokeh.models.widgets import Select, Slider, AutocompleteInput, TextInput, Div
    bokeh_renderer = renderer('bokeh')
except:
    BokehServerWidgets = None


class TestBokehServerWidgets(ComparisonTestCase):

    def setUp(self):
        if not BokehServerWidgets:
            raise SkipTest("Bokeh required to test BokehServerWidgets")

    def test_bokeh_widgets_server_mode(self):
        dmap = DynamicMap(lambda X: Curve([]), kdims=['X']).redim.range(X=(0, 5))
        widgets = bokeh_renderer.instance(mode='server').get_widget(dmap, None)
        div, widget = widgets.widgets['X']
        self.assertIsInstance(widget, Slider)
        self.assertEqual(widget.value, 0)
        self.assertEqual(widget.start, 0)
        self.assertEqual(widget.end, 5)
import dask.dataframe as dd
import holoviews as hv
import geoviews as gv

from bokeh.models import Slider, Button
from bokeh.layouts import layout
from bokeh.io import curdoc
from bokeh.models import WMTSTileSource

from holoviews.operation.datashader import datashade, aggregate, shade
from holoviews.plotting.util import fire
shade.cmap = fire

hv.extension('bokeh')
renderer = hv.renderer('bokeh').instance(mode='server')

# Load data
usecols = ['tpep_pickup_datetime', 'dropoff_x', 'dropoff_y']
ddf = dd.read_csv('../data/nyc_taxi.csv', parse_dates=['tpep_pickup_datetime'], usecols=usecols)
ddf['hour'] = ddf.tpep_pickup_datetime.dt.hour
ddf = ddf.persist()

from bokeh.models import WMTSTileSource
url = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{Z}/{Y}/{X}.jpg'
wmts = gv.WMTS(WMTSTileSource(url=url))

stream = hv.streams.Stream.define('HourSelect', hour=0)()
points = hv.Points(ddf, kdims=['dropoff_x', 'dropoff_y'])
dmap = hv.util.Dynamic(points, operation=lambda obj, hour: obj.select(hour=hour),
                       streams=[stream])