bokeh.plotting.from_networkx

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 Source : search_tree_visualization.py
with GNU General Public License v3.0
from 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')
        self.plot.renderers.append(graph_renderer)
        show(self.plot)

    def update_graph(self, node):

0 Source : plotting.py
with BSD 3-Clause "New" or "Revised" License
from 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!
    Inputs:
    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 :("""
    random.seed(rseed)
    if(not PLOT_NETWORK):
        warn("network plotting disabled because some libraries are not found")
        return
    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)
            adjustSizes=False,
            edgeWeightInfluence=1.0,

            # Performance
            jitterTolerance=1.0,  # Tolerance
            barnesHutOptimize=True,
            barnesHutTheta=1.2,
            multiThreaded=False,  # NOT IMPLEMENTED

            # Tuning
            scalingRatio=2.4*posscale,
            strongGravityMode=False,
            gravity=1.0,

            # Log
            verbose=False)

        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")],\
                                        renderers=[species_renderer],attachment="right")
    else:
        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>',\
                                        renderers=[species_renderer],attachment="right")
    rxn_hover_tool = HoverTool(tooltips=[("reaction", "@species"), ("type", "@type"),("k_f","@k"),("k_r","@k_r")],\
                                        renderers=[reaction_renderer],attachment="right")
    
    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:
        plot.renderers.append(edges_renderer)
    if plot_reactions:
        plot.renderers.append(reaction_renderer)
    if plot_species:
        plot.renderers.append(species_renderer)

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

0 Source : clustree.py
with MIT License
from 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

    Args:
        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)

    plot.renderers.append(graph_renderer)

    # 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 Source : clustree.py
with MIT License
from ivirshup

def plot_hierarchy(
    complist: "ComponentList", coords: pd.DataFrame, *, scatter_kwargs={}
):
    """
    Params
    ------
    complist
        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
    ).items():
        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(
        tooltips=[
            ("img", "@img{safe}"),
            ("component_id", "@index"),
            ("# solutions:", "@n_solutions"),
            ("# samples in intersect", "@n_intersect"),
            ("# samples in union", "@n_union"),
        ],
        attachment="vertical",
    )

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

    node_label = LabelSet(
        x="x",
        y="y",
        text="nodeid",
        level="annotation",
        source=label_src,
        text_align="center",
    )

    # 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.renderers.append(graph_renderer)
    p.add_layout(node_label)
    p.add_tools(node_hover, SaveTool())
    return p

0 Source : visualization.py
with GNU Affero General Public License v3.0
from iza-institute-of-labor-economics

def plot_dag(
    functions,
    targets=None,
    columns_overriding_functions=None,
    check_minimal_specification="ignore",
    selectors=None,
    labels=True,
    tooltips=False,
    plot_kwargs=None,
    arrow_kwargs=None,
    edge_kwargs=None,
    label_kwargs=None,
    node_kwargs=None,
):
    """Plot the dag of the tax and transfer system.

    Parameters
    ----------
    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
        shown.
    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]
        )
        plot.add_layout(
            Arrow(
                end=NormalHead(**{**ARROW_KWARGS_DEFAULTS, **arrow_kwargs}),
                x_start=x_start,
                y_start=y_start,
                x_end=x_end,
                y_end=y_end,
                **{**EDGE_KWARGS_DEFAULTS, **edge_kwargs},
            )
        )

    plot.renderers.append(graph_renderer)

    tools = [BoxZoomTool(), ResetTool()]
    tools.append(TapTool(callback=OpenURL(url="@url")))
    if tooltips:
        tools.append(HoverTool(tooltips=TOOLTIPS))

    plot.add_tools(*tools)

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

    output_notebook()
    show(plot)

    return plot


def _mock_parameters_arguments(functions):

0 Source : plots.py
with Apache License 2.0
from 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',
                    status='active', 
                    name='reducer',
                    color_by_this_attribute=Spectral8[0])
        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',
                                                         line_width=2)
        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.renderers.append(network_graph)

        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)
        
        plot.add_layout(label)
        return plot
        

        

    def make_netgraph_plot(self, df, df_nodes):

0 Source : plots.py
with Apache License 2.0
from 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.degree(G))
        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.degree(G)])
        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.id, df_nodes.role)}
        networkx.set_node_attributes(G, node_role, 'role')
        
        node_status = {k:v for k,v in zip(df_nodes.id, df_nodes.status)}
        networkx.set_node_attributes(G, node_status, 'status')

        node_name = {k:v for k,v in zip(df_nodes.id, df_nodes.name)}
        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
        # https://networkx.github.io/documentation/networkx-1.9/reference/generated/networkx.drawing.layout.spring_layout.html
        # 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,
                                                         line_width=2)
        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()

        plot.renderers.append(network_graph)
        
        #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':
                idx_online.append(e)
            else:
                idx_offline.append(e)
            node_labels.append(n[1])

        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)

        plot.renderers.append(labels)

        
        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.renderers.append(labels)

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