1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
|
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# igraph\n\nigraph (https://igraph.org/) is a popular network analysis package that\nprovides (among many other things) functions to convert to/from NetworkX.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\nimport networkx as nx\nimport igraph as ig"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## NetworkX to igraph\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"G = nx.dense_gnm_random_graph(30, 40, seed=42)\n\n# largest connected component\ncomponents = nx.connected_components(G)\nlargest_component = max(components, key=len)\nH = G.subgraph(largest_component)\n\n# convert to igraph\nh = ig.Graph.from_networkx(H)\n\n\n# Plot the same network with NetworkX and igraph\nfig, (ax0, ax1) = plt.subplots(nrows=1, ncols=2, figsize=(12, 6))\n\n# NetworkX draw\nax0.set_title(\"Plot with NetworkX draw\")\nnx.draw_kamada_kawai(H, node_size=50, ax=ax0)\n\n# igraph draw\nax1.set_title(\"Plot with igraph plot\")\nlayout = h.layout_kamada_kawai()\nig.plot(h, layout=layout, target=ax1)\nplt.axis(\"off\")\nplt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## igraph to NetworkX\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"g = ig.Graph.GRG(30, 0.2)\nG = g.to_networkx()\nnx.draw(G, node_size=50)\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.15"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
|