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(')

# 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:

As you can see only the node labels are shown.

5

1 Answer

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(')

# 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:

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(')

# 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')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest