pythonnetworkxpyvis

pyvis - How to make nodes IDs selectable (to copy into buffer) in browser


This code generates HTML files with sub-graphs. The problem is that it is not possible to copy some node ID from HTML page to be able to paste it into some other tool.

G = nx.from_pandas_edgelist(df, source='fromKey',
                            target='toKey', 
                            create_using=nx.DiGraph) 
i = 0

for h in nx.weakly_connected_components(G):

    i += 1
    #Create subgraph
    g=nx.subgraph(G, h) 

    #----Draw using pyvis
    net = Network(height='1000px',
                width='1000px',
                directed=True#,
                #heading='Subgraph '+str(i)
                ) 

    net.from_nx(g) 

   
    net.repulsion(central_gravity=0.1) 
    net.set_edge_smooth('dynamic')

    net.show('subgraph_'+str(i)+'.html', notebook=False)       

        

The graph looks good but not possible to select particular node id

Say, it is some node with id=100040003003405 - Is it any property which allows to copy ID using mouse cursor to be able to use it as a parameter for adhoc query rather than manually typing...


Solution

  • A simple hack is to inject <a> tags (as nodes' titles), hover then Copy link address :

    # add this before the loop
    nx.set_node_attributes(
        G,
        dict(zip(G.nodes, map(lambda n: f'<a href="{n}">{n}</a>', G.nodes))),
        name="title",
    )
    

    enter image description here Used (G):

    import random
    import networkx as nx
    
    random.seed(0)
    
    G = nx.Graph()
    
    nodes = [random.getrandbits(64) for _ in range(10)]
    
    while len(G.edges) < 15:
        G.add_edge(*random.sample(nodes, 2))