In [1]:
%matplotlib inline
import networkx as nx
import matplotlib.pyplot as plt
In [2]:
G = nx.Graph()
G.add_edge(1,2)
nx.draw_networkx(G)
plt.show()
In [3]:
G.add_nodes_from([3, 4])
nx.draw_networkx(G)
plt.show()
In [4]:
G.add_edge(3,4)
G.add_edges_from([(2, 3), (4, 1)])
nx.draw_networkx(G)
plt.show()
In [5]:
G.nodes()
Out[5]:
In [6]:
G.edges()
Out[6]:
In [7]:
G.adjacency_list()
Out[7]:
In [8]:
nx.to_dict_of_lists(G)
Out[8]:
In [9]:
nx.to_edgelist(G)
Out[9]:
In [10]:
nx.to_numpy_matrix(G)
Out[10]:
In [12]:
print (nx.to_scipy_sparse_matrix(G))
In [13]:
G.add_edge(1,3)
nx.draw_networkx(G)
plt.show()
In [14]:
G.degree()
Out[14]:
In [15]:
plt.hist(nx.fast_gnp_random_graph(10000, 0.01).degree().values())
In [16]:
G = nx.krackhardt_kite_graph()
nx.draw_networkx(G)
plt.show()
In [17]:
print nx.has_path(G, source=1, target=9)
print nx.shortest_path(G, source=1, target=9)
print nx.shortest_path_length(G, source=1, target=9)
In [18]:
nx.betweenness_centrality(G)
Out[18]:
In [19]:
nx.degree_centrality(G)
Out[19]:
In [20]:
nx.closeness_centrality(G)
Out[20]:
In [21]:
nx.eigenvector_centrality(G)
Out[21]:
In [22]:
nx.clustering(G)
Out[22]:
In [32]:
import community # Community module for community detection and clustering
G = nx.powerlaw_cluster_graph(100, 1, .4)
partition = community.best_partition(G)
for i in set(partition.values()):
print ("Community", i)
members = list_nodes = [nodes for nodes in partition.keys() if partition[nodes] == i]
print (members)
values = [partition.get(node) for node in G.nodes()]
nx.draw_spring(G, cmap = plt.get_cmap('jet'), node_color = values, node_size=30, with_labels=False)
plt.show()
print ("Modularity score:", community.modularity(partition, G))
In [33]:
dump_file_base = "dumped_graph"
# Be sure the dump_file file doesn't exist
def remove_file(filename):
import os
if os.path.exists(filename):
os.remove(filename)
In [34]:
G = nx.krackhardt_kite_graph()
In [35]:
# GML format write and read
GML_file = dump_file_base + '.gml'
remove_file(GML_file)
nx.write_gml(G, GML_file)
G2 = nx.read_gml(GML_file)
assert(G.edges() == G2.edges())
In [36]:
# The same can be done with
# JSON, Adjacency List, Edge List, GEXF, GraphML and so on
In [37]:
import snowball_sampling
my_social_network = nx.Graph()
snowball_sampling.snowball_sampling(my_social_network, 2, 'alberto')
nx.draw(my_social_network)
plt.show()
In [38]:
my_sampled_social_network = nx.Graph()
snowball_sampling.snowball_sampling(my_sampled_social_network, 3, 'alberto', sampling_rate=0.2)
nx.draw(my_sampled_social_network)
plt.show()
In [ ]:
In [ ]:
In [ ]:
In [ ]: