Arturo Sbr
Arturo Sbr

Reputation: 6333

Display node and edge attributes in interactive Networkx graph using Pyvis

Edit

I updated pyvis to version 0.3.2 and the plot is working as expected now.

Read on if you're interested in displaying node and edge attributes on a Pyvis visualization of a Networkx graph.


Original question

I have two Pandas dataframes: edges_df and nodes_df. I used them to create networkx graph G which I'm then passing to a Pyvis network.

edges_df looks as follows:

src dst color title
140 1 3 #379951 T/B
146 5 15 #379951 T/B
7 1 2 #0b03fc 78
0 0 1 #0b03fc 62
139 4 10 #379951 T/B

nodes_df looks as follows:

id color title
1 1 #47abfc I am node 1
15 15 #47abfc I am node 15
14 14 #f24e77 I am node 14
2 2 #f24e77 I am node 2
8 8 #f24e77 I am node 8

I created G as follows:

# Declare nx graph from pandas edges
G = nx.from_pandas_edgelist(
    df=edges_df,
    source='src',
    target='dst',
    edge_attr=['color', 'title']
)

# Set node attributes from pandas
nx.set_node_attributes(
    G=G,
    values=nodes_df_renamed.set_index('id').to_dict('index')
)

The docs state that:

Note that the Networkx node properties with the same names as those consumed by pyvis (e.g., title) are translated directly to the correspondingly-named pyvis node attributes.

Hence, I assumed that if my networkx graph had node attributes that follow pyvis' naming conventions, the resulting graph would automatically display each node's attributes.

However, when I build a pyvis Network from G, the resulting drawing does not display the colors or titles as expected. For example, I was expecting node 1 to be blue (#47abfc) and display the string 'I am node 1' when the user hovers over it.

# Imports
from pyvis import network as net
import networkx as nx
from IPython.display import HTML

# Declare pyvis graph from G
gpv = net.Network(notebook=True, cdn_resources='in_line')
gpv.from_nx(G)
gpv.save_graph('example.html')
HTML(filename='example.html')

Sadly, none of the title or color attributes from neither my edges or nodes is rendering as I expected.

enter image description here

How can I get Pyvis to render nodes and edges according to the corresponding attributes from my networkx graph?

The data I'm working with is HUGE (25B edges) and I'd like to avoid using for loops to add nodes or edges one by one.


Summary

By creating a Networkx graph with node and edge attributes that follow Pyvis' naming conventions, the resulting visualization will inherit the attributes of the Networkx graph.

For example, adding node attribute title will result in hover elements that display the corresponding node's title.

success

Upvotes: 0

Views: 921

Answers (0)

Related Questions