Here are the examples of the python api bokeh.plotting.from_networkx taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

7 Examples 7

3 View Source File :
License : GNU General Public License v3.0
Project Creator : aI-lab-glider

    def show_results(self):
        layout = self.hierarchy_pos(self.G, 0, x_range=(-50000, 100000), y_range=(-100000, 100000))
        graph_renderer = from_networkx(self.G, layout, scale=1, center=layout[0])
        graph_renderer.node_renderer.glyph = Circle(size=15, fill_color=Spectral4[0])
        graph_renderer.node_renderer.data_source.add(['  <  i>italics < /i>'] * self.N, 'fonts')
        graph_renderer.node_renderer.data_source.add(self.imgs, 'imgs')

    def update_graph(self, node):

0 View Source File :
License : BSD 3-Clause "New" or "Revised" License
Project Creator : BuildACell

def graphPlot(DG,DGspecies,DGreactions,plot,layout="force",positions=None,plot_species = True, plot_reactions = True, plot_edges = True, plot_arrows = True,\
              species_glyph_size = 12, reaction_glyph_size = 8, posscale = 1.0,layoutfunc=None,iterations=2000,rseed=30,show_species_images=False):
    """given a directed graph, plot it!
    DG: a directed graph of type DiGraph
    DGspecies: a directed graph which only contains the species nodes
    DGreactions: a directed graph which only contains the reaction nodes
    plot: a bokeh plot object
    layout: graph layout function. 
                'force' uses fa2 to push nodes apart
                'circle' plots the nodes and reactions in two overlapping circles, with the reactions on the inside of the circle
                'custom' allows user input "layoutfunc". Internally, layoutfunc is passed the three inputs (DG, DGspecies, DGreactions)
                                                        and should output a position dictionary with node {  <  node number>:(x,y)}

    positions: a dictionary of node names and x,y positions. this gets passed into the layout function
    posscale: multiply the scaling of the plot. This only affects the arrows because the arrows are a hack :("""
    if(not PLOT_NETWORK):
        warn("network plotting disabled because some libraries are not found")
    if(layout == "force"):
        # below are parameters for the force directed graph visualization
        forceatlas2 = ForceAtlas2(
            # Behavior alternatives
            outboundAttractionDistribution=True,  # Dissuade hubs
            linLogMode=False,  # NOT IMPLEMENTED
            # Prevent overlap (NOT IMPLEMENTED)

            # Performance
            jitterTolerance=1.0,  # Tolerance
            multiThreaded=False,  # NOT IMPLEMENTED

            # Tuning

            # Log

        positions = forceatlas2.forceatlas2_networkx_layout(
            DG, pos=positions, iterations=iterations)
    elif(layout == "circle"):
        positions = nx.circular_layout(DGspecies, scale=50*posscale)
        positions.update(nx.circular_layout(DGreactions, scale=35*posscale))
    elif(layout == "custom"):
        positions = layoutfunc(DG, DGspecies, DGreactions)
    reaction_renderer = from_networkx(DGreactions, positions, center=(0, 0))
    species_renderer = from_networkx(DGspecies, positions, center=(0, 0))
    edges_renderer = from_networkx(DG, positions, center=(0, 0))

    #Set xbounds and ybounds:
    xbounds = [0, 0]
    ybounds = [0, 0]
    for n in positions:
        xbounds[0] = min([xbounds[0], positions[n][0]])
        xbounds[1] = max([xbounds[1], positions[n][0]])
        ybounds[0] = min([ybounds[0], positions[n][1]])
        ybounds[1] = max([ybounds[1], positions[n][1]])

    max_glyph = max([reaction_glyph_size, species_glyph_size])
    xbounds[0] -= max_glyph
    xbounds[1] += max_glyph
    ybounds[0] -= max_glyph
    ybounds[1] += max_glyph

    # edges
    edges_renderer.node_renderer.glyph = Circle(
        size=species_glyph_size, line_alpha=0, fill_alpha=0, fill_color="color")
    edges_renderer.edge_renderer.glyph = MultiLine(
        line_alpha=0.2, line_width=4, line_join="round", line_color="color")
    edges_renderer.edge_renderer.selection_glyph = MultiLine(
        line_color=Spectral4[2], line_width=5, line_join="round")
    edges_renderer.edge_renderer.hover_glyph = MultiLine(
        line_color=Spectral4[1], line_width=5, line_join="round")
    if plot_arrows:
        xbounds_a, ybounds_a = makeArrows2(
            edges_renderer, DG, positions, headsize=5)  # make the arrows!
        xbounds[0] = min([xbounds[0], xbounds_a[0]])
        xbounds[1] = max([xbounds[1], xbounds_a[1]])
        ybounds[0] = min([ybounds[0], ybounds_a[0]])
        ybounds[1] = max([ybounds[1], ybounds_a[1]])

    # we want to find the middle of the graph and plot a square that is 1:1 aspect ratio

    # find the midpoint of the graph
    xmid = statistics.mean(xbounds)
    ymid = statistics.mean(ybounds)
    # now, subtract the middle from the edges
    xmiddlized = [a-xmid for a in xbounds]
    ymiddlized = [a-ymid for a in ybounds]
    # now, find the biggest dimension
    absdim = max([abs(a) for a in xmiddlized+ymiddlized])
    xlim = [xmid-absdim*1.05, xmid + absdim*1.05]
    ylim = [ymid-absdim*1.05, ymid + absdim*1.05]
    # now set it on the plot!
    plot.x_range = Range1d(xlim[0], xlim[1])
    plot.y_range = Range1d(ylim[0], ylim[1])

    # reactions
    reaction_renderer.node_renderer.glyph = Square(
        size=reaction_glyph_size, fill_color="color")
    reaction_renderer.node_renderer.selection_glyph = Square(
        size=reaction_glyph_size, fill_color=Spectral4[2])
    reaction_renderer.node_renderer.hover_glyph = Square(
        size=reaction_glyph_size, fill_color=Spectral4[1])

    # nodes
    species_renderer.node_renderer.glyph = Circle(size=12, fill_color="color")
    species_renderer.node_renderer.selection_glyph = Circle(size=15, fill_color=Spectral4[2])
    species_renderer.node_renderer.hover_glyph = Circle(size=15, fill_color=Spectral4[1])
    #this part adds the interactive elements that make it so that the lines are highlighted 
    #when you mouse over and click
    edge_hover_tool = HoverTool(tooltips= None,renderers=[edges_renderer])
    if( not show_species_images):
        species_hover_tool = HoverTool(tooltips=[("name", "@species"), ("type", "@type")],\
        species_hover_tool = HoverTool(tooltips=' < div> < div>  < img src="data:image/png;base64,@image" style="float: left; margin: 0px 0px 0px 0px;"> < /img> < /div> < /div>',\
    rxn_hover_tool = HoverTool(tooltips=[("reaction", "@species"), ("type", "@type"),("k_f","@k"),("k_r","@k_r")],\
    plot.add_tools(edge_hover_tool,species_hover_tool,rxn_hover_tool, TapTool(), BoxSelectTool(),PanTool(),WheelZoomTool())

    edges_renderer.selection_policy = NodesAndLinkedEdges()
    edges_renderer.inspection_policy = EdgesAndLinkedNodes()

    if plot_edges:
    if plot_reactions:
    if plot_species:

def generate_networkx_graph(CRN,useweights=False,use_pretty_print=False,pp_show_material=True,

0 View Source File :
License : MIT License
Project Creator : ivirshup

def gen_clustree_plot(
    g: nx.Graph,
    pos: dict = None,
    plot_kwargs: dict = None,
    node_kwargs: dict = None,
    edge_kwargs: dict = None,
    Takes a graph, basically just instantiates a plot

        g: clustree graph.
        pos: dict containing calculated layout positions
    if pos is None:
        pos = nx.nx_agraph.graphviz_layout(g, prog="dot")
    if plot_kwargs is None:
        plot_kwargs = dict(plot_width=1000, plot_height=600)
    if node_kwargs is None:
        node_kwargs = dict(size=15)
    if edge_kwargs is None:
        edge_kwargs = dict(line_alpha="edge_alpha", line_width=1)

    g_p = g.copy()
    # set_edge_alpha(g_p)

    plot = Plot(**get_ranges(pos), **plot_kwargs)

    graph_renderer = from_networkx(g_p, pos)
    graph_renderer.node_renderer.glyph = Circle(**node_kwargs)
    graph_renderer.edge_renderer.glyph = MultiLine(**edge_kwargs)


    # node_hover = HoverTool(
    #     tooltips=[("solution_name", "@solution_name"),
    #               ("partition_id", "@partition_id"), ("n_items", "@n_items")]
    # )

    # plot.add_tools(node_hover)

    return plot

def get_ranges(pos):

0 View Source File :
License : MIT License
Project Creator : ivirshup

def plot_hierarchy(
    complist: "ComponentList", coords: pd.DataFrame, *, scatter_kwargs={}
        List of components that will be plotted in this graph.
    coords = coords.copy()
    scatter_kwargs = scatter_kwargs.copy()
    g = complist.to_graph()
    assert len(list(nx.components.weakly_connected_components(g))) == 1
    for k, v in make_umap_plots(
        complist, coords, scatter_kwargs=scatter_kwargs
        g.nodes[k]["img"] = v

    pos = json_friendly(
        nx.nx_agraph.graphviz_layout(nx.DiGraph(g.edges(data=False)), prog="dot")

    graph_renderer = from_networkx(g, pos)
    graph_renderer.node_renderer.glyph = Circle(size=15)
    graph_renderer.edge_renderer.glyph = MultiLine(line_width=1)

    node_hover = HoverTool(
            ("img", "@img{safe}"),
            ("component_id", "@index"),
            ("# solutions:", "@n_solutions"),
            ("# samples in intersect", "@n_intersect"),
            ("# samples in union", "@n_union"),

    # Adding labels
    label_src = pd.DataFrame.from_dict(
        graph_renderer.layout_provider.graph_layout, orient="index", columns=["x", "y"]
    ) = "nodeid"
    label_src = ColumnDataSource(label_src)

    node_label = LabelSet(

    # layout = graph_renderer.layout_provider.graph_layout
    # label, x, y = zip(*((str(label), x, y) for label, (x, y) in layout.items()))
    # node_label = LabelSet(
    #     x=x, y=y, text=label, level="glyph"
    # )

    p = Plot(plot_width=1000, plot_height=500, **get_ranges(pos))
    p.add_tools(node_hover, SaveTool())
    return p

def plot_dag(
    """Plot the dag of the tax and transfer system.

    functions : str, pathlib.Path, callable, module, imports statements, dict
        Functions can be anything of the specified types and a list of the same objects.
        If the object is a dictionary, the keys of the dictionary are used as a name
        instead of the function name. For all other objects, the name is inferred from
        the function name.
    targets : str, list of str
        String or list of strings with names of functions whose output is actually
        needed by the user.
    columns_overriding_functions : str list of str
        Names of columns in the data which are preferred over function defined in the
        tax and transfer system.
    check_minimal_specification : {"ignore", "warn", "raise"}, default "ignore"
        Indicator for whether checks which ensure the most minimal configuration should
        be silenced, emitted as warnings or errors.
    selectors : str or list of str or dict or list of dict or list of str and dict
        Selectors allow to you to select and de-select nodes in the graph for
        visualization. For the full list of options, see the tutorial about
        `visualization   <  ../docs/tutorials/visualize.ipynb>`_. By default, all nodes are
    labels : bool, default True
        Annotate nodes with labels.
    tooltips : bool, default False
        Experimental feature which makes the source code of the functions accessible as
        a tooltip. Sometimes, the tooltip is not properly displayed.
    plot_kwargs : dict
        Additional keyword arguments passed to :class:`bokeh.models.Plot`.
    arrow_kwargs : dict
        Additional keyword arguments passed to :class:`bokeh.models.Arrow`. For example,
        change the size of the head with ``{"size": 10}``.
    edge_kwargs : dict
        Additional keyword arguments passed to :class:`bokeh.models.MultiLine`. For
        example, change the color with ``{"fill_color": "green"}``.
    label_kwargs : dict
        Additional keyword arguments passed to :class:`bokeh.models.LabelSet`. For
        example, change the fontsize with ``{"text_font_size": "12px"}``.
    node_kwargs : dict
        Additional keyword arguments passed to :class:`bokeh.models.Circle`. For
        example, change the color with ``{"fill_color": "orange"}``.

    targets = DEFAULT_TARGETS if targets is None else targets
    targets = parse_to_list_of_strings(targets, "targets")
    columns_overriding_functions = parse_to_list_of_strings(
        columns_overriding_functions, "columns_overriding_functions"

    # Load functions and perform checks.
    functions, internal_functions = load_user_and_internal_functions(functions)

    # Create one dictionary of functions and perform check.
    functions = {**internal_functions, **functions}
    functions = {
        k: v for k, v in functions.items() if k not in columns_overriding_functions
    _fail_if_targets_not_in_functions(functions, targets)

    # Partial parameters to functions such that they disappear in the DAG.
    functions = _mock_parameters_arguments(functions)

    dag = create_dag(
        functions, targets, columns_overriding_functions, check_minimal_specification

    selectors = [] if selectors is None else _to_list(selectors)
    plot_kwargs = {} if plot_kwargs is None else plot_kwargs
    arrow_kwargs = {} if arrow_kwargs is None else arrow_kwargs
    edge_kwargs = {} if edge_kwargs is None else edge_kwargs
    label_kwargs = {} if label_kwargs is None else label_kwargs
    node_kwargs = {} if node_kwargs is None else node_kwargs

    dag = _select_nodes_in_dag(dag, selectors)

    dag = _add_url_to_dag(dag)
    # Even if we do not use the source codes as tooltips, we need to remove the
    # functions.
    dag = _replace_functions_with_source_code(dag)

    plot_kwargs["title"] = _to_bokeh_title(
        plot_kwargs.get("title", "Tax and Transfer System")
    plot = Plot(**{**PLOT_KWARGS_DEFAULTS, **plot_kwargs})

    layout = _create_pydot_layout(dag)
    graph_renderer = from_networkx(dag, layout, scale=1, center=(0, 0))

    graph_renderer.node_renderer.glyph = Circle(
        **{**NODE_KWARGS_DEFAULTS, **node_kwargs}

    graph_renderer.edge_renderer.visible = False
    for (
        (start_node, end_node),
    ) in graph_renderer.edge_renderer.data_source.to_df().iterrows():
        (x_start, y_start), (x_end, y_end) = _compute_arrow_coordinates(
            layout[start_node], layout[end_node]
                end=NormalHead(**{**ARROW_KWARGS_DEFAULTS, **arrow_kwargs}),
                **{**EDGE_KWARGS_DEFAULTS, **edge_kwargs},


    tools = [BoxZoomTool(), ResetTool()]
    if tooltips:


    if labels:
        source = ColumnDataSource(
            pd.DataFrame(layout).T.rename(columns={0: "x", 1: "y"})
        labels = LabelSet(
            **{**LABEL_KWARGS_DEFAULT, **label_kwargs},


    return plot

def _mock_parameters_arguments(functions):

0 View Source File :
License : Apache License 2.0
Project Creator : scaleoutsystems

    def make_single_node_plot(self):
        Plot single node graph with reducer

        :return: Bokeh plot with the graph
        :rtype: bokeh.plotting.figure.Figure
        HOVER_TOOLTIPS = [
            ("Name", "@name"),
            ("Role", "@role"),
            ("Status", "@status"),
            ("Id", "@index"),
        G = networkx.Graph()
        G.add_node("reducer", adjusted_node_size=20, role='reducer',
        network_graph = from_networkx(G, networkx.spring_layout)
        network_graph.node_renderer.glyph = Circle(size=20, fill_color = Spectral8[0])
        network_graph.node_renderer.hover_glyph = Circle(size=20, fill_color='white',
        network_graph.node_renderer.selection_glyph = Circle(size=20,
                                                             fill_color='white', line_width=2)
        plot = figure(tooltips=HOVER_TOOLTIPS, tools="pan,wheel_zoom,save,reset", active_scroll='wheel_zoom',
                    width=725, height=460, sizing_mode='stretch_width',
                    x_range=Range1d(-1.5, 1.5), y_range=Range1d(-1.5, 1.5))

        plot.axis.visible = False
        plot.grid.visible = False
        plot.outline_line_color = None

        label = Label(x=0, y=0, text='reducer',
                     background_fill_color='#4bbf73', text_font_size='15px',
                     background_fill_alpha=.7, x_offset=-20, y_offset=10)
        return plot


    def make_netgraph_plot(self, df, df_nodes):

0 View Source File :
License : Apache License 2.0
Project Creator : scaleoutsystems

    def make_netgraph_plot(self, df, df_nodes):
        Create FEDn network visualization.

        :param df: pandas dataframe with defined edges
        :type df: pandas.Dataframe
        :param df_nodes:pandas dataframe with defined nodes
        :type df_nodes: pandas.Dataframe
        :return: Bokeh plot with the graph
        :rtype: bokeh.plotting.figure.Figure

        if df.empty:
            #no combiners and thus no clients, plot only reducer
            plot = self.make_single_node_plot()
            return plot
        G = networkx.from_pandas_edgelist(df, 'source', 'target', create_using=networkx.Graph())
        degrees = dict(
        networkx.set_node_attributes(G, name='degree', values=degrees)

        number_to_adjust_by = 20
        adjusted_node_size = dict([(node, degree + number_to_adjust_by) for node, degree in])
        networkx.set_node_attributes(G, name='adjusted_node_size', values=adjusted_node_size)
        # community
        from networkx.algorithms import community
        communities = community.greedy_modularity_communities(G)
        # Create empty dictionaries
        modularity_class = {}
        modularity_color = {}
        # Loop through each community in the network
        for community_number, community in enumerate(communities):
            # For each member of the community, add their community number and a distinct color
            for name in community:
                modularity_class[name] = community_number
                modularity_color[name] = Spectral8[community_number]

        # Add modularity class and color as attributes from the network above
        networkx.set_node_attributes(G, modularity_class, 'modularity_class')
        networkx.set_node_attributes(G, modularity_color, 'modularity_color')

        node_role = {k:v for k,v in zip(, df_nodes.role)}
        networkx.set_node_attributes(G, node_role, 'role')
        node_status = {k:v for k,v in zip(, df_nodes.status)}
        networkx.set_node_attributes(G, node_status, 'status')

        node_name = {k:v for k,v in zip(,}
        networkx.set_node_attributes(G, node_name, 'name')

        # Choose colors for node and edge highlighting
        node_highlight_color = 'white'
        edge_highlight_color = 'black'

        # Choose attributes from G network to size and color by — setting manual
        # size (e.g. 10) or color (e.g. 'skyblue') also allowed
        size_by_this_attribute = 'adjusted_node_size'
        color_by_this_attribute = 'modularity_color'

        # Establish which categories will appear when hovering over each node
        HOVER_TOOLTIPS = [
            ("Name", "@name"),
            ("Role", "@role"),
            ("Status", "@status"),
            ("Id", "@index"),
        # Create a plot — set dimensions, toolbar, and title
        plot = figure(tooltips=HOVER_TOOLTIPS,
                      tools="pan,wheel_zoom,save,reset", active_scroll='wheel_zoom',
                      width=725, height=460, sizing_mode='stretch_width',
                      x_range=Range1d(-1.5, 1.5), y_range=Range1d(-1.5, 1.5))

        # Create a network graph object
        # if one like lock reducer add args: pos={'reducer':(0,1)}, fixed=['reducer']
        network_graph = from_networkx(G, networkx.spring_layout, scale=1, center=(0, 0), seed=45)

        # Set node sizes and colors according to node degree (color as category from attribute)
        network_graph.node_renderer.glyph = Circle(size=size_by_this_attribute, fill_color=color_by_this_attribute)
        # Set node highlight colors
        network_graph.node_renderer.hover_glyph = Circle(size=size_by_this_attribute, fill_color=node_highlight_color,
        network_graph.node_renderer.selection_glyph = Circle(size=size_by_this_attribute,
                                                             fill_color=node_highlight_color, line_width=2)
        # Set edge opacity and width
        network_graph.edge_renderer.glyph = MultiLine(line_alpha=0.5, line_width=1)
        # Set edge highlight colors
        network_graph.edge_renderer.selection_glyph = MultiLine(line_color=edge_highlight_color, line_width=2)
        network_graph.edge_renderer.hover_glyph = MultiLine(line_color=edge_highlight_color, line_width=2)

        # Highlight nodes and edges
        network_graph.selection_policy = NodesAndLinkedEdges()
        network_graph.inspection_policy = NodesAndLinkedEdges()

        #Node labels, red if status is offline, green is active
        x, y = zip(*network_graph.layout_provider.graph_layout.values())
        node_names = list(G.nodes(data='name'))
        node_status = list(G.nodes(data='status'))

        idx_offline = []
        idx_online = []
        node_labels = []
        for e, n in enumerate(node_names):
            if node_status[e][1] == 'active':

        source_on = ColumnDataSource({'x': numpy.asarray(x)[idx_online], 'y': numpy.asarray(y)[idx_online], 'name': numpy.asarray(node_labels)[idx_online]})
        labels = LabelSet(x='x', y='y', text='name', source=source_on, background_fill_color='#4bbf73', text_font_size='15px',
                          background_fill_alpha=.7, x_offset=-20, y_offset=10)


        source_off = ColumnDataSource({'x': numpy.asarray(x)[idx_offline], 'y': numpy.asarray(y)[idx_offline], 'name': numpy.asarray(node_labels)[idx_offline]})
        labels = LabelSet(x='x', y='y', text='name', source=source_off, background_fill_color='#d9534f', text_font_size='15px',
                          background_fill_alpha=.7, x_offset=-20, y_offset=10)


        plot.axis.visible = False
        plot.grid.visible = False
        plot.outline_line_color = None
        return plot