I want to visualize the graph using pyviz. I'm working on the code to extract a subgraph from a graph.
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
def RWS(G, vs, r=0.5, S=4):
#initialize subgraph
Gk = nx.DiGraph()
#initialize nodes
Vk = []
#add vs to Gk
Gk.add_node(vs)
Vk.append(vs)
while len(Vk) < S:
#get neighbor nodes set of Vk (step 4) (Also appending j just for the purpose of adding edge)
NS = [(n, j) for j in Vk for n in G.neighbors(j) if n not in Vk]
print("{} {} {} {}".format('length of NS is', len(NS), 'and vs =', vs))
# randomly select r of nodes in NS, add them into the Vk
if not len(NS) == 0:
for node, j in NS:
if np.random.uniform() < r:
Vk.append(node)
Gk.add_edge(j, node)
if len(Vk) == S or len(NS) < S:
break
else:
break
return Gk
if __name__ == '__main__':
m = np.matrix([
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0, 0]])
# G = nx.from_numpy_matrix(m, create_using=nx.MultiDiGraph())
G = nx.from_numpy_matrix(m, create_using=nx.DiGraph)
#expansion ratio
r = 0.5
#subgraph size
S = 4
# randomly select the node from G
vs = np.random.randint(0, G.size())
print(vs)
Gk = RWS(G, vs, r, S)
# VISUALIZATION
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_nodes(G, pos, nodelist=list(Gk.nodes()), node_color='r')
nx.draw_networkx_labels(G, pos)
nx.draw_networkx_edges(G, pos, edge_color='b', width=0.5)
nx.draw_networkx_edges(G, pos, edgelist=list(Gk.edges()), edge_color='g', width=1, arrowstyle='->')
plt.axis('off')
plt.show()
Here I have the graph in networkx format, and extract the subgraph from it, then visualize with networkx. To make it easier to see, subgraph is colored green. However, this visualization does not work well for large scaled graph.
So I want to recreate the visualization of this using pyvis. Can someone help me tto complete this?
In order to visualize this graph in
pyvis
, you can write the following function:Make sure that the graph and the sub-graph are both of the same type:
and finally you will have: