Search code examples
networkxpyvis

How to display node attributes on a networkx graph visualized with pyvis?


I would like to display node attributes when visualized with pyvis.

import networkx
import obonet

G = obonet.read_obo('https://ftp.ebi.ac.uk/pub/databases/chebi/ontology/chebi_core.obo')

# Create smaller subgraph
H = nx.ego_graph(G, 'CHEBI:36464', 15)

H.nodes['CHEBI:24669']
>>> {'name': 'p-block molecular entity', 'subset': ['3_STAR'], 'def': '"Amain group molecular entity that contains one or more atoms of a p-block element." []', 'is_a': ['CHEBI:33579'], 'relationship': ['has_part CHEBI:33560']}

This is the data that I would like to show. For example name.

Then I plot the graph using pyvis:

from pyvis.network import Network

nt = Network('1500px', '1500px', notebook=True)
nt.from_nx(H)
nt.show('H.html')

And this is how the graph looks:

enter image description here

As you can see only the node labels are shown.


Solution

  • In order to get your node attribute displayed with the node labels, you can create a new 'label' key in your node dictionary and pass it the value of the attribute. See code below with the lite version of the dataset you provided:

    import networkx as nx
    import obonet
    from pyvis.network import Network
    
    G = obonet.read_obo('https://ftp.ebi.ac.uk/pub/databases/chebi/ontology/chebi_lite.obo')
    
    # Create smaller subgraph
    H = nx.ego_graph(G, 'CHEBI:36464', 15)
    
    for n in H.nodes(data=True):
      n[1]['label']=n[0]+' '+n[1]['name'] #concatenate label of the node with its attribute
    
    nt = Network('1500px', '1500px', notebook=True)
    nt.from_nx(H)
    nt.show('network.html')
    

    And the output gives:

    enter image description here

    If instead, you'd like to visualize the node attribute by hoovering over the node, you can use:

    import networkx as nx
    import obonet
    from pyvis.network import Network
    
    G = obonet.read_obo('https://ftp.ebi.ac.uk/pub/databases/chebi/ontology/chebi_lite.obo')
    
    # Create smaller subgraph
    H = nx.ego_graph(G, 'CHEBI:36464', 15)
    
    for n in H.nodes(data=True):
      n[1]['title']=n[1]['name'] #add hoovering to graph
    
    
    nt = Network('1500px', '1500px', notebook=True)
    nt.from_nx(H)
    nt.show('network.html')
    

    enter image description here