\documentclass[10pt,a4paper]{article} % Packages \usepackage{fancyhdr} % For header and footer \usepackage{multicol} % Allows multicols in tables \usepackage{tabularx} % Intelligent column widths \usepackage{tabulary} % Used in header and footer \usepackage{hhline} % Border under tables \usepackage{graphicx} % For images \usepackage{xcolor} % For hex colours %\usepackage[utf8x]{inputenc} % For unicode character support \usepackage[T1]{fontenc} % Without this we get weird character replacements \usepackage{colortbl} % For coloured tables \usepackage{setspace} % For line height \usepackage{lastpage} % Needed for total page number \usepackage{seqsplit} % Splits long words. %\usepackage{opensans} % Can't make this work so far. Shame. Would be lovely. \usepackage[normalem]{ulem} % For underlining links % Most of the following are not required for the majority % of cheat sheets but are needed for some symbol support. \usepackage{amsmath} % Symbols \usepackage{MnSymbol} % Symbols \usepackage{wasysym} % Symbols %\usepackage[english,german,french,spanish,italian]{babel} % Languages % Document Info \author{gonz95alo} \pdfinfo{ /Title (networkx.pdf) /Creator (Cheatography) /Author (gonz95alo) /Subject (NetworkX Cheat Sheet) } % Lengths and widths \addtolength{\textwidth}{6cm} \addtolength{\textheight}{-1cm} \addtolength{\hoffset}{-3cm} \addtolength{\voffset}{-2cm} \setlength{\tabcolsep}{0.2cm} % Space between columns \setlength{\headsep}{-12pt} % Reduce space between header and content \setlength{\headheight}{85pt} % If less, LaTeX automatically increases it \renewcommand{\footrulewidth}{0pt} % Remove footer line \renewcommand{\headrulewidth}{0pt} % Remove header line \renewcommand{\seqinsert}{\ifmmode\allowbreak\else\-\fi} % Hyphens in seqsplit % This two commands together give roughly % the right line height in the tables \renewcommand{\arraystretch}{1.3} \onehalfspacing % Commands \newcommand{\SetRowColor}[1]{\noalign{\gdef\RowColorName{#1}}\rowcolor{\RowColorName}} % Shortcut for row colour \newcommand{\mymulticolumn}[3]{\multicolumn{#1}{>{\columncolor{\RowColorName}}#2}{#3}} % For coloured multi-cols \newcolumntype{x}[1]{>{\raggedright}p{#1}} % New column types for ragged-right paragraph columns \newcommand{\tn}{\tabularnewline} % Required as custom column type in use % Font and Colours \definecolor{HeadBackground}{HTML}{333333} \definecolor{FootBackground}{HTML}{666666} \definecolor{TextColor}{HTML}{333333} \definecolor{DarkBackground}{HTML}{157818} \definecolor{LightBackground}{HTML}{F7FAF7} \renewcommand{\familydefault}{\sfdefault} \color{TextColor} % Header and Footer \pagestyle{fancy} \fancyhead{} % Set header to blank \fancyfoot{} % Set footer to blank \fancyhead[L]{ \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{C} \SetRowColor{DarkBackground} \vspace{-7pt} {\parbox{\dimexpr\textwidth-2\fboxsep\relax}{\noindent \hspace*{-6pt}\includegraphics[width=5.8cm]{/web/www.cheatography.com/public/images/cheatography_logo.pdf}} } \end{tabulary} \columnbreak \begin{tabulary}{11cm}{L} \vspace{-2pt}\large{\bf{\textcolor{DarkBackground}{\textrm{NetworkX Cheat Sheet}}}} \\ \normalsize{by \textcolor{DarkBackground}{gonz95alo} via \textcolor{DarkBackground}{\uline{cheatography.com/152363/cs/32835/}}} \end{tabulary} \end{multicols}} \fancyfoot[L]{ \footnotesize \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{LL} \SetRowColor{FootBackground} \mymulticolumn{2}{p{5.377cm}}{\bf\textcolor{white}{Cheatographer}} \\ \vspace{-2pt}gonz95alo \\ \uline{cheatography.com/gonz95alo} \\ \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Cheat Sheet}} \\ \vspace{-2pt}Published 7th September, 2022.\\ Updated 23rd October, 2022.\\ Page {\thepage} of \pageref{LastPage}. \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Sponsor}} \\ \SetRowColor{white} \vspace{-5pt} %\includegraphics[width=48px,height=48px]{dave.jpeg} Measure your website readability!\\ www.readability-score.com \end{tabulary} \end{multicols}} \begin{document} \raggedright \raggedcolumns % Set font size to small. Switch to any value % from this page to resize cheat sheet text: % www.emerson.emory.edu/services/latex/latex_169.html \footnotesize % Small font. \begin{multicols*}{2} \begin{tabularx}{8.4cm}{x{4.08 cm} x{3.92 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{The basics}} \tn % Row 0 \SetRowColor{LightBackground} Import library & `import networx as nx` \tn % Row Count 2 (+ 2) % Row 1 \SetRowColor{white} Import matplotlib for graph drawing & `import matplotlib.pyplot as plt` \tn % Row Count 4 (+ 2) % Row 2 \SetRowColor{LightBackground} Initialize (Di)graphs & `G = nx.Graph(), G = nx.DiGraph()` \tn % Row Count 6 (+ 2) % Row 3 \SetRowColor{white} Create a (Di)graph from another graph & `G = nx.Graph(H), G = nx.DiGraph(H)` \tn % Row Count 8 (+ 2) % Row 4 \SetRowColor{LightBackground} Copy existing graphs & `G2 = G1.copy()` \tn % Row Count 9 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{x{2.64 cm} x{5.36 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Unweighted node and edge creation/deletion}} \tn % Row 0 \SetRowColor{LightBackground} Add nodes & `G.add\_node(1) \{\{nl\}\} G.add\_nodes\_from({[}'a', 'b'{]})` \tn % Row Count 2 (+ 2) % Row 1 \SetRowColor{white} Add (directed) edges & `G.add\_edge(1, 2) \{\{nl\}\} G.add\_edges\_from({[}(1, 'a'), (1, 'c'){]})` \tn % Row Count 5 (+ 3) % Row 2 \SetRowColor{LightBackground} Delete nodes & `G.remove\_node(1) \{\{nl\}\} G.remove\_nodes\_from({[}'a', 'b'{]})` \tn % Row Count 8 (+ 3) % Row 3 \SetRowColor{white} Delete edges & `G.remove\_edge(1, 2) \{\{nl\}\} G.remove\_edges\_from({[}(1, 'a'), (1, 'c'){]})` \tn % Row Count 11 (+ 3) \hhline{>{\arrayrulecolor{DarkBackground}}--} \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{If G is directed, then these take into account edge direction.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{x{3.44 cm} x{4.56 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Weights and attributes}} \tn % Row 0 \SetRowColor{LightBackground} Add nodes with attribute & `G.add\_nodes\_from({[}1, 2{]}, color = 'blue')` \tn % Row Count 2 (+ 2) % Row 1 \SetRowColor{white} Change node attributes & `G.nodes{[}1{]}{[}'color'{]} = 'red'` \tn % Row Count 4 (+ 2) % Row 2 \SetRowColor{LightBackground} Add edges with attribute & `G.add\_edges\_from({[}(1,2), (2,4){]}, weight=3)` \tn % Row Count 7 (+ 3) % Row 3 \SetRowColor{white} Change edge attributes & `G.edges{[}1,2{]}{[}'weight'{]} = 2` \tn % Row Count 9 (+ 2) % Row 4 \SetRowColor{LightBackground} Set attributes from dictionary & \seqsplit{`nx.set\_node\_attributes(G}, \{1: \{'city': 'Madrid'\}\})` \tn % Row Count 12 (+ 3) \hhline{>{\arrayrulecolor{DarkBackground}}--} \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Attributes can have any name (color, timestamp, weight, etc). However for edge weights they should have 'weight', as many functions for weighted graphs assume it.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{x{3.28 cm} x{4.72 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Basic graph properties}} \tn % Row 0 \SetRowColor{LightBackground} Number of nodes & `N = len(G.nodes())` \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} Number of edges & `E = len(G.edges())` \tn % Row Count 2 (+ 1) % Row 2 \SetRowColor{LightBackground} Node-degree dictionary & `degreedict = G.degrees` \tn % Row Count 4 (+ 2) % Row 3 \SetRowColor{white} Directedness & `G.is\_directed(), G.is\_undirected()` \tn % Row Count 6 (+ 2) % Row 4 \SetRowColor{LightBackground} Planarity & `G.is\_planar()` \tn % Row Count 7 (+ 1) % Row 5 \SetRowColor{white} Diameter, radius & `d = nx.diameter(G), r = nx.radius(G)` \tn % Row Count 9 (+ 2) % Row 6 \SetRowColor{LightBackground} Average shortest path length & `aspl = \seqsplit{nx.average\_shortest\_path\_length(G)`} \tn % Row Count 11 (+ 2) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{x{3.76 cm} x{4.24 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Iterate over a graph}} \tn % Row 0 \SetRowColor{LightBackground} Iterate over nodes/edges & `nodelist = {[}n for n in G.nodes(){]} \{\{nl\}\} edgelist = {[}n for n in G.edges(){]}` \tn % Row Count 4 (+ 4) % Row 1 \SetRowColor{white} Iterate over node/edge attributes & `node\_attrs = {[}n for n in G.nodes(data=True){]} \{\{nl\}\} edge\_attrs = {[}n for n in G.edges(data=True){]}` \tn % Row Count 9 (+ 5) % Row 2 \SetRowColor{LightBackground} Iterate over in/out edges & `in\_list = {[}e for e in G.in\_edges(){]} \{\{nl\}\} out\_list = {[}e for e in G.out\_edges(){]}` \tn % Row Count 13 (+ 4) % Row 3 \SetRowColor{white} Iterate over node's neighbors & `neighs = {[}n for n in G.neighbors(node){]}` \tn % Row Count 15 (+ 2) % Row 4 \SetRowColor{LightBackground} Iterate over \seqsplit{successors/predecessors} & `succ = {[}n for n in G.successors(node){]} \{\{nl\}\} pred = {[}n for n in G.predecessors(node){]}` \tn % Row Count 20 (+ 5) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{x{3.76 cm} x{4.24 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Connectivity properties}} \tn % Row 0 \SetRowColor{LightBackground} Connectedness & `G.is\_connected() \{\{nl\}\} \seqsplit{G.is\_weakly\_connected()}, \{\{nl\}\} \seqsplit{G.is\_strongly\_connected()`} \tn % Row Count 4 (+ 4) % Row 1 \SetRowColor{white} Contains node or edge? & `G.has\_node(node), G.has\_edge(*edge)` \tn % Row Count 6 (+ 2) % Row 2 \SetRowColor{LightBackground} List of connected components & `cc = \seqsplit{nx.connected\_components(G)} \{\{nl\}\} wcc = \seqsplit{nx.weakly\_connected\_components(G)} \{\{nl\}\} scc = \seqsplit{nx.strongly\_connected\_components(G)`} \tn % Row Count 13 (+ 7) % Row 3 \SetRowColor{white} Largest (simply) connected component & `largest\_cc = \seqsplit{max(nx.connected\_components(G)}, key=len) \{\{nl\}\} LCC = \seqsplit{G.subgraph(largest\_cc).copy()`} \tn % Row Count 18 (+ 5) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{x{3.28 cm} x{4.72 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Some matricial representations}} \tn % Row 0 \SetRowColor{LightBackground} Adjacency matrix (standard) & `A = nx.to\_numpy\_array(G, dtype=int)` \tn % Row Count 2 (+ 2) % Row 1 \SetRowColor{white} Adjacency matrix (sparse) & `A = \seqsplit{nx.to\_scipy\_sparse\_array(G)} ` \tn % Row Count 4 (+ 2) % Row 2 \SetRowColor{LightBackground} Adjacency matrix eigenvalues & `eigs = \seqsplit{nx.adjacency\_spectrum(G)`} \tn % Row Count 6 (+ 2) % Row 3 \SetRowColor{white} Graph from adjacency matrix & `G = \seqsplit{nx.from\_numpy\_array(A)} \{\{nl\}\} G = \seqsplit{nx.from\_scipy\_sparse\_array(A)`} \tn % Row Count 9 (+ 3) % Row 4 \SetRowColor{LightBackground} Incidence matrix (sparse) & `I = \seqsplit{nx.incidence\_matrix(G)`} \tn % Row Count 11 (+ 2) % Row 5 \SetRowColor{white} Laplacian matrix (sparse) & `L = \seqsplit{nx.laplacian\_matrix(G)`} \tn % Row Count 13 (+ 2) % Row 6 \SetRowColor{LightBackground} Laplacian matrix eigenvalues & `eigs = \seqsplit{nx.laplacian\_spectrum(G)`} \tn % Row Count 15 (+ 2) % Row 7 \SetRowColor{white} Google matrix (standard) & `Goog = nx.google\_matrix(G)` \tn % Row Count 17 (+ 2) \hhline{>{\arrayrulecolor{DarkBackground}}--} \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{Sparse matrices/arrays are memory efficient. See the Scipy page on them for their methods, or convert them to numpy arrays with \seqsplit{`sparse\_array.todense()`}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{x{3.76 cm} x{4.24 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Graph plotting}} \tn % Row 0 \SetRowColor{LightBackground} Plotting command, standard options & `nx.draw(G, pos=pos, with\_labels=True, ax=axis )` \tn % Row Count 3 (+ 3) % Row 1 \SetRowColor{white} Node positioning options (I) & `pos = {[}nx.circular\_layout(G), nx.planar\_layout(G), nx.random\_layout(G){]}` \tn % Row Count 7 (+ 4) % Row 2 \SetRowColor{LightBackground} Node positioning options (II) & `pos = {[}nx.shell\_layout(G), nx.spring\_layout(G), nx.spiral\_layout(G){]}` \tn % Row Count 11 (+ 4) % Row 3 \SetRowColor{white} Node colors and sizes in nx.draw() & `node\_color = colorlist \{\{nl\}\} node\_size = sizelist` \tn % Row Count 14 (+ 3) % Row 4 \SetRowColor{LightBackground} Edge colors and widths in nx.draw() & `edge\_color = colorlist \{\{nl\}\} width = widthlist` \tn % Row Count 17 (+ 3) % Row 5 \SetRowColor{white} Node fine-tuning & \seqsplit{`nx.draw\_networkx\_nodes(G}, other options)` \tn % Row Count 19 (+ 2) % Row 6 \SetRowColor{LightBackground} Edge fine-tuning & \seqsplit{`nx.draw\_networkx\_edges(G}, other options)` \tn % Row Count 21 (+ 2) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{x{1.76 cm} x{6.24 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Centrality measures}} \tn % Row 0 \SetRowColor{LightBackground} Degree & `C = \seqsplit{nx.degree\_centrality(G)`} \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} \seqsplit{Betweenness} & `C = \seqsplit{nx.betweeness\_centrality(G)`} \tn % Row Count 3 (+ 2) % Row 2 \SetRowColor{LightBackground} \seqsplit{Closeness} & `C = \seqsplit{nx.closeness\_centrality(G)`} \tn % Row Count 5 (+ 2) % Row 3 \SetRowColor{white} \seqsplit{Eigenvector} & `C = \seqsplit{nx.eigenvector\_centrality\_numpy(G)`} \tn % Row Count 7 (+ 2) % Row 4 \SetRowColor{LightBackground} Katz & `C = \seqsplit{nx.katz\_centrality\_numpy(G}, alpha=0.1, beta=1.0)` \tn % Row Count 9 (+ 2) % Row 5 \SetRowColor{white} \seqsplit{PageRank} & `C = nx.pagerank(G, alpha=0.1, personalization=None)` \tn % Row Count 11 (+ 2) % Row 6 \SetRowColor{LightBackground} HITS & `C = nx.hits(G)` \tn % Row Count 12 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}--} \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{All measures return a dictionary `\{node:value\}`. They do not take into account weights, one needs to provide an extra argument `weight='weight'` in order to consider them.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{x{3.52 cm} x{4.48 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Undirected graph generators}} \tn % Row 0 \SetRowColor{LightBackground} Path graph & `G = nx.path\_graph(N)` \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} Cycle graph & `G = nx.cycle\_graph(N)` \tn % Row Count 3 (+ 2) % Row 2 \SetRowColor{LightBackground} Star graph & `G = nx.star\_graph(N)` \tn % Row Count 4 (+ 1) % Row 3 \SetRowColor{white} Complete graph & `G = \seqsplit{nx.complete\_graph(N)`} \tn % Row Count 6 (+ 2) % Row 4 \SetRowColor{LightBackground} Erd{\"o}s-Renyi (random) & `G = \seqsplit{nx.erdos\_renyi\_graph(N}, p)` \tn % Row Count 8 (+ 2) % Row 5 \SetRowColor{white} Barabasi-Albert (scale-free) & `G = \seqsplit{nx.barabasi\_albert\_graph(N}, m)` \tn % Row Count 10 (+ 2) % Row 6 \SetRowColor{LightBackground} Watts-Strogatz (small world) & `G = \seqsplit{nx.watts\_strogatz\_graph(N}, p)` \tn % Row Count 12 (+ 2) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} % That's all folks \end{multicols*} \end{document}