I have a cora citation network data which has 2708 nodes and 5429 edges. and I tried to plot it using networkx
import scipy.sparse as sp
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
def encode_onehot(labels):
classes = set(labels)
classes_dict = {c: np.identity(len(classes))[i, :] for i, c in enumerate(classes)}
labels_onehot = np.array(list(map(classes_dict.get, labels)), dtype=np.int32)
return labels_onehot
def load_data(path="data/cora/", dataset="cora"):
print('Loading {} dataset...'.format(dataset))
idx_features_labels = np.genfromtxt("{}{}.content".format(path, dataset), dtype=np.dtype(str))
features = sp.csr_matrix(idx_features_labels[:, 1:-1], dtype=np.float32)
labels = encode_onehot(idx_features_labels[:, -1])
# build graph
idx = np.array(idx_features_labels[:, 0], dtype=np.int32)
idx_map = {j: i for i, j in enumerate(idx)}
edges_unordered = np.genfromtxt("{}{}.cites".format(path, dataset), dtype=np.int32)
edges = np.array(list(map(idx_map.get, edges_unordered.flatten())),
dtype=np.int32).reshape(edges_unordered.shape)
adj = sp.coo_matrix((np.ones(edges.shape[0]), (edges[:, 0], edges[:, 1])),
shape=(labels.shape[0], labels.shape[0]), dtype=np.float32)
# build symmetric adjacency matrix
adj = adj + adj.T.multiply(adj.T > adj) - adj.multiply(adj.T > adj)
print('Dataset has {} nodes, {} edges, {} features.'.format(adj.shape[0], edges.shape[0], features.shape[1]))
return features.todense(), adj, labels
X, A, y = load_data(dataset='cora')
G = nx.from_scipy_sparse_matrix(A)
nx.draw_networkx(G)
plt.show()
as you can see, this is hard to see. Is there any ways to make it easier to see? any suggestions would be appriciated.
you can use pyvis.network for the interactive visualization. you can also export graph to external files or plot network inline in notebook.
I usually use this function to plot the graph for myself.
def draw_graph3(networkx_graph,notebook=True,output_filename='graph.html',show_buttons=False,only_physics_buttons=False):
"""
This function accepts a networkx graph object,
converts it to a pyvis network object preserving its node and edge attributes,
and both returns and saves a dynamic network visualization.
Valid node attributes include:
"size", "value", "title", "x", "y", "label", "color".
(For more info: https://pyvis.readthedocs.io/en/latest/documentation.html#pyvis.network.Network.add_node)
Valid edge attributes include:
"arrowStrikethrough", "hidden", "physics", "title", "value", "width"
(For more info: https://pyvis.readthedocs.io/en/latest/documentation.html#pyvis.network.Network.add_edge)
Args:
networkx_graph: The graph to convert and display
notebook: Display in Jupyter?
output_filename: Where to save the converted network
show_buttons: Show buttons in saved version of network?
only_physics_buttons: Show only buttons controlling physics of network?
"""
# import
from pyvis import network as net
# make a pyvis network
pyvis_graph = net.Network(notebook=notebook)
pyvis_graph.width = '1000px'
# for each node and its attributes in the networkx graph
for node,node_attrs in networkx_graph.nodes(data=True):
pyvis_graph.add_node(node,**node_attrs)
# print(node,node_attrs)
# for each edge and its attributes in the networkx graph
for source,target,edge_attrs in networkx_graph.edges(data=True):
# if value/width not specified directly, and weight is specified, set 'value' to 'weight'
if not 'value' in edge_attrs and not 'width' in edge_attrs and 'weight' in edge_attrs:
# place at key 'value' the weight of the edge
edge_attrs['value']=edge_attrs['weight']
# add the edge
pyvis_graph.add_edge(source,target,**edge_attrs)
# turn buttons on
if show_buttons:
if only_physics_buttons:
pyvis_graph.show_buttons(filter_=['physics'])
else:
pyvis_graph.show_buttons()
# return and also save
return pyvis_graph.show(output_filename)
You can visualize graph by calling this function
draw_graph3(your_graph,output_filename='graph_output.html', notebook=False)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With