python-igraph API reference

List of all classes, functions and methods in python-igraph

class documentation

Generic graph.

This class is built on top of GraphBase, so the order of the methods in the generated API documentation is a little bit obscure: inherited methods come after the ones implemented directly in the subclass. Graph provides many functions that GraphBase does not, mostly because these functions are not speed critical and they were easier to implement in Python than in pure C. An example is the attribute handling in the constructor: the constructor of Graph accepts three dictionaries corresponding to the graph, vertex and edge attributes while the constructor of GraphBase does not. This extension was needed to make Graph serializable through the pickle module. Graph also overrides some functions from GraphBase to provide a more convenient interface; e.g., layout functions return a Layout instance from Graph instead of a list of coordinate pairs.

Graphs can also be indexed by strings or pairs of vertex indices or vertex names. When a graph is indexed by a string, the operation translates to the retrieval, creation, modification or deletion of a graph attribute:

>>> g = Graph.Full(3)
>>> g["name"] = "Triangle graph"
>>> g["name"]
'Triangle graph'
>>> del g["name"]

When a graph is indexed by a pair of vertex indices or names, the graph itself is treated as an adjacency matrix and the corresponding cell of the matrix is returned:

>>> g = Graph.Full(3)
>>> g.vs["name"] = ["A", "B", "C"]
>>> g[1, 2]
1
>>> g["A", "B"]
1
>>> g["A", "B"] = 0
>>> g.ecount()
2

Assigning values different from zero or one to the adjacency matrix will be translated to one, unless the graph is weighted, in which case the numbers will be treated as weights:

>>> g.is_weighted()
False
>>> g["A", "B"] = 2
>>> g["A", "B"]
1
>>> g.es["weight"] = 1.0
>>> g.is_weighted()
True
>>> g["A", "B"] = 2
>>> g["A", "B"]
2
>>> g.es["weight"]
[1.0, 1.0, 2]
Class Method ​Adjacency Generates a graph from its adjacency matrix.
Class Method ​Bipartite No summary
Class Method ​Data​Frame Generates a graph from one or two dataframes.
Class Method ​Dict​Dict Constructs a graph from a dict-of-dicts representation.
Class Method ​Dict​List Constructs a graph from a list-of-dictionaries representation.
Class Method from​_graph​_tool Converts the graph from graph-tool
Class Method from​_networkx Converts the graph from networkx
Class Method GRG Generates a random geometric graph.
Class Method ​Incidence Creates a bipartite graph from an incidence matrix.
Class Method ​List​Dict Constructs a graph from a dict-of-lists representation.
Class Method ​Read Unified reading function for graphs.
Class Method ​Read_​DIMACS Reads a graph from a file conforming to the DIMACS minimum-cost flow file format.
Class Method ​Read_​Graph​MLz Reads a graph from a zipped GraphML file.
Class Method ​Read_​Pickle Reads a graph from Python pickled format
Class Method ​Read_​Picklez Reads a graph from compressed Python pickled format, uncompressing it on-the-fly.
Class Method ​Tuple​List Constructs a graph from a list-of-tuples representation.
Method __add__ Copies the graph and extends the copy depending on the type of the other object given.
Method __and__ Graph intersection operator.
Method __bool__ Returns True if the graph has at least one vertex, False otherwise.
Method __coerce__ Coercion rules.
Method __iadd__ In-place addition (disjoint union).
Method __init__ __init__(n=0, edges=None, directed=False, graph_attrs=None, vertex_attrs=None, edge_attrs=None)
Method __isub__ In-place subtraction (difference).
Method __mul__ Copies exact replicas of the original graph an arbitrary number of times.
Method __or__ Graph union operator.
Method __plot__ Plots the graph to the given Cairo context or matplotlib Axes.
Method __reduce__ Support for pickling.
Method __str__ Returns a string representation of the graph.
Method __sub__ Removes the given object(s) from the graph
Method add​_edge Adds a single edge to the graph.
Method add​_edges Adds some edges to the graph.
Method add​_vertex No summary
Method add​_vertices Adds some vertices to the graph.
Method all​_st​_cuts Returns all the cuts between the source and target vertices in a directed graph.
Method all​_st​_mincuts Returns all the mincuts between the source and target vertices in a directed graph.
Method as​_directed Returns a directed copy of this graph. Arguments are passed on to GraphBase.to_directed() that is invoked on the copy.
Method as​_undirected Returns an undirected copy of this graph. Arguments are passed on to GraphBase.to_undirected() that is invoked on the copy.
Method biconnected​_components Calculates the biconnected components of the graph.
Method bipartite​_projection Projects a bipartite graph into two one-mode graphs. Edge directions are ignored while projecting.
Method bipartite​_projection​_size No summary
Method blocks Calculates the biconnected components of the graph.
Method clear Clears the graph, deleting all vertices, edges, and attributes.
Method community​_edge​_betweenness Community structure based on the betweenness of the edges in the network.
Method community​_fastgreedy Community structure based on the greedy optimization of modularity.
Method community​_infomap Finds the community structure of the network according to the Infomap method of Martin Rosvall and Carl T. Bergstrom.
Method community​_label​_propagation Finds the community structure of the graph according to the label propagation method of Raghavan et al.
Method community​_leading​_eigenvector Newman's leading eigenvector method for detecting community structure.
Method community​_leading​_eigenvector​_naive Naive implementation of Newman's eigenvector community structure detection.
Method community​_leiden Finds the community structure of the graph using the Leiden algorithm of Traag, van Eck & Waltman.
Method community​_multilevel Community structure based on the multilevel algorithm of Blondel et al.
Method community​_optimal​_modularity Calculates the optimal modularity score of the graph and the corresponding community structure.
Method community​_spinglass Finds the community structure of the graph according to the spinglass community detection method of Reichardt & Bornholdt.
Method community​_walktrap Community detection algorithm of Latapy & Pons, based on random walks.
Method components Calculates the (strong or weak) connected components for a given graph.
Method count​_automorphisms​_vf2 Returns the number of automorphisms of the graph.
Method degree​_distribution Calculates the degree distribution of the graph.
Method delete​_edges Deletes some edges from the graph.
Method dfs Conducts a depth first search (DFS) on the graph.
Method disjoint​_union Creates the disjoint union of two (or more) graphs.
Method dyad​_census Calculates the dyad census of the graph.
Method get​_adjacency Returns the adjacency matrix of a graph.
Method get​_adjacency​_sparse Returns the adjacency matrix of a graph as a SciPy CSR matrix.
Method get​_adjlist Returns the adjacency list representation of the graph.
Method get​_all​_simple​_paths Calculates all the simple paths from a given node to some other nodes (or all of them) in a graph.
Method get​_automorphisms​_vf2 Returns all the automorphisms of the graph
Method get​_edge​_dataframe Export edges with attributes to pandas.DataFrame
Method get​_incidence Returns the incidence matrix of a bipartite graph. The incidence matrix is an n times m matrix, where n and m are the number of vertices in the two vertex classes.
Method get​_inclist Returns the incidence list representation of the graph.
Method get​_vertex​_dataframe Export vertices with attributes to pandas.DataFrame
Method gomory​_hu​_tree Calculates the Gomory-Hu tree of an undirected graph with optional edge capacities.
Method indegree Returns the in-degrees in a list.
Method intersection Creates the intersection of two (or more) graphs.
Method is​_named Returns whether the graph is named.
Method is​_weighted Returns whether the graph is weighted.
Method k​_core Returns some k-cores of the graph.
Method layout Returns the layout of the graph according to a layout algorithm.
Method layout​_auto Chooses and runs a suitable layout function based on simple topological properties of the graph.
Method layout​_sugiyama Places the vertices using a layered Sugiyama layout.
Method maxflow Returns a maximum flow between the given source and target vertices in a graph.
Method maximum​_bipartite​_matching Finds a maximum matching in a bipartite graph.
Method mincut Calculates the minimum cut between the given source and target vertices or within the whole graph.
Method modularity Calculates the modularity score of the graph with respect to a given clustering.
Method outdegree Returns the out-degrees in a list.
Method pagerank Calculates the PageRank values of a graph.
Method path​_length​_hist Returns the path length histogram of the graph
Method spanning​_tree Calculates a minimum spanning tree for a graph.
Method summary Returns the summary of the graph.
Method to​_dict​_dict Export graph to dictionary of dicts of edge attributes
Method to​_dict​_list Export graph as two lists of dictionaries, for vertices and edges.
Method to​_graph​_tool Converts the graph to graph-tool
Method to​_list​_dict Export graph to a dictionary of lists (or other sequences).
Method to​_networkx Converts the graph to networkx format.
Method to​_tuple​_list Export graph to a list of edge tuples
Method transitivity​_avglocal​_undirected Calculates the average of the vertex transitivities of the graph.
Method triad​_census Calculates the triad census of the graph.
Method union Creates the union of two (or more) graphs.
Method write Unified writing function for graphs.
Method write​_adjacency Writes the adjacency matrix of the graph to the given file
Method write​_dimacs Writes the graph in DIMACS format to the given file.
Method write​_graphmlz Writes the graph to a zipped GraphML file.
Method write​_pickle Saves the graph in Python pickled format
Method write​_picklez Saves the graph in Python pickled format, compressed with gzip.
Method write​_svg Saves the graph as an SVG (Scalable Vector Graphics) file
Class Variable __hash__ Undocumented
Class Variable __iter__ Undocumented
Class Variable ​Formula Undocumented
Property es The edge sequence of the graph
Property vs The vertex sequence of the graph
Class Method _reconstruct Reconstructs a Graph object from Python's pickled format.
Property _as​_parameter_ Undocumented

Inherited from GraphBase:

Method __new__ Create and return a new object. See help(type) for accurate signature.
Method all​_minimal​_st​_separators Returns a list containing all the minimal s-t separators of a graph.
Method are​_connected Decides whether two given vertices are directly connected.
Method articulation​_points Returns the list of articulation points in the graph.
Method assortativity Returns the assortativity of the graph based on numeric properties of the vertices.
Method assortativity​_degree Returns the assortativity of a graph based on vertex degrees.
Method assortativity​_nominal Returns the assortativity of the graph based on vertex categories.
Method ​Asymmetric_​Preference Generates a graph based on asymmetric vertex types and connection probabilities.
Method ​Atlas Generates a graph from the Graph Atlas.
Method attributes
Method authority​_score Calculates Kleinberg's authority score for the vertices of the graph
Method average​_path​_length Calculates the average path length in a graph.
Method ​Barabasi Generates a graph based on the Barabasi-Albert model.
Method betweenness Calculates or estimates the betweenness of vertices in a graph.
Method bfs Conducts a breadth first search (BFS) on the graph.
Method bfsiter Constructs a breadth first search (BFS) iterator of the graph.
Method bibcoupling Calculates bibliographic coupling scores for given vertices in a graph.
Method bridges Returns the list of bridges in the graph.
Method canonical​_permutation Calculates the canonical permutation of a graph using the BLISS isomorphism algorithm.
Method chordal​_completion Returns the list of edges needed to be added to the graph to make it chordal.
Method clique​_number Returns the clique number of the graph.
Method cliques Returns some or all cliques of the graph as a list of tuples.
Method closeness Calculates the closeness centralities of given vertices in a graph.
Method cocitation Calculates cocitation scores for given vertices in a graph.
Method cohesive​_blocks Calculates the cohesive block structure of the graph.
Method complementer Returns the complementer of the graph
Method compose Returns the composition of two graphs.
Method connected​_components Calculates the (strong or weak) connected components for a given graph.
Method constraint Calculates Burt's constraint scores for given vertices in a graph.
Method contract​_vertices Contracts some vertices in the graph, i.e. replaces groups of vertices with single vertices. Edges are not affected.
Method convergence​_degree Undocumented (yet).
Method convergence​_field​_size Undocumented (yet).
Method copy Creates a copy of the graph.
Method coreness Finds the coreness (shell index) of the vertices of the network.
Method count​_isomorphisms​_vf2 Determines the number of isomorphisms between the graph and another one
Method count​_multiple Counts the multiplicities of the given edges.
Method count​_subisomorphisms​_vf2 Determines the number of subisomorphisms between the graph and another one
Method ​De_​Bruijn Generates a de Bruijn graph with parameters (m, n)
Method decompose Decomposes the graph into subgraphs.
Method degree Returns some vertex degrees from the graph.
Method ​Degree_​Sequence Generates a graph with a given degree sequence.
Method delete​_vertices Deletes vertices and all its edges from the graph.
Method density Calculates the density of the graph.
Method dfsiter Constructs a depth first search (DFS) iterator of the graph.
Method diameter Calculates the diameter of the graph.
Method difference Subtracts the given graph from the original
Method diversity Calculates the structural diversity index of the vertices.
Method dominator Returns the dominator tree from the given root node
Method eccentricity Calculates the eccentricities of given vertices in a graph.
Method ecount Counts the number of edges.
Method edge​_attributes
Method edge​_betweenness Calculates or estimates the edge betweennesses in a graph.
Method edge​_connectivity Calculates the edge connectivity of the graph or between some vertices.
Method eigen​_adjacency Undocumented
Method eigenvector​_centrality Calculates the eigenvector centralities of the vertices in a graph.
Method ​Erdos_​Renyi Generates a graph based on the Erdos-Renyi model.
Method ​Establishment Generates a graph based on a simple growing model with vertex types.
Method ​Famous Generates a famous graph based on its name.
Method farthest​_points Returns two vertex IDs whose distance equals the actual diameter of the graph.
Method feedback​_arc​_set Calculates an approximately or exactly minimal feedback arc set.
Method ​Forest_​Fire Generates a graph based on the forest fire model
Method ​Full Generates a full graph (directed or undirected, with or without loops).
Method ​Full_​Citation Generates a full citation graph
Method get​_all​_shortest​_paths Calculates all of the shortest paths from/to a given node in a graph.
Method get​_diameter Returns a path with the actual diameter of the graph.
Method get​_edgelist Returns the edge list of a graph.
Method get​_eid Returns the edge ID of an arbitrary edge between vertices v1 and v2
Method get​_eids Returns the edge IDs of some edges between some vertices.
Method get​_isomorphisms​_vf2 Returns all isomorphisms between the graph and another one
Method get​_shortest​_paths Calculates the shortest paths from/to a given node in a graph.
Method get​_subisomorphisms​_lad Returns all subisomorphisms between the graph and another one using the LAD algorithm.
Method get​_subisomorphisms​_vf2 Returns all subisomorphisms between the graph and another one
Method girth Returns the girth of the graph.
Method ​Growing_​Random Generates a growing random graph.
Method harmonic​_centrality Calculates the harmonic centralities of given vertices in a graph.
Method has​_multiple Checks whether the graph has multiple edges.
Method hub​_score Calculates Kleinberg's hub score for the vertices of the graph
Method incident Returns the edges a given vertex is incident on.
Method independence​_number Returns the independence number of the graph.
Method independent​_vertex​_sets Returns some or all independent vertex sets of the graph as a list of tuples.
Method induced​_subgraph Returns a subgraph spanned by the given vertices.
Method is​_bipartite Decides whether the graph is bipartite or not.
Method is​_chordal Returns whether the graph is chordal or not.
Method is​_connected Decides whether the graph is connected.
Method is​_dag Checks whether the graph is a DAG (directed acyclic graph).
Method is​_directed Checks whether the graph is directed.
Method is​_loop Checks whether a specific set of edges contain loop edges
Method is​_minimal​_separator Decides whether the given vertex set is a minimal separator.
Method is​_multiple Checks whether an edge is a multiple edge.
Method is​_mutual Checks whether an edge has an opposite pair.
Method is​_separator Decides whether the removal of the given vertices disconnects the graph.
Method is​_simple Checks whether the graph is simple (no loop or multiple edges).
Method is​_tree Checks whether the graph is a (directed or undirected) tree graph.
Method ​Isoclass Generates a graph with a given isomorphism class.
Method isoclass Returns the isomorphism class of the graph or its subgraph.
Method isomorphic Checks whether the graph is isomorphic to another graph.
Method isomorphic​_bliss Checks whether the graph is isomorphic to another graph, using the BLISS isomorphism algorithm.
Method isomorphic​_vf2 Checks whether the graph is isomorphic to another graph, using the VF2 isomorphism algorithm.
Method ​K_​Regular Generates a k-regular random graph
Method ​Kautz Generates a Kautz graph with parameters (m, n)
Method knn Calculates the average degree of the neighbors for each vertex, and the same quantity as the function of vertex degree.
Method laplacian Returns the Laplacian matrix of a graph.
Method largest​_cliques Returns the largest cliques of the graph as a list of tuples.
Method largest​_independent​_vertex​_sets Returns the largest independent vertex sets of the graph as a list of tuples.
Method ​Lattice Generates a regular lattice.
Method layout​_bipartite Place the vertices of a bipartite graph in two layers.
Method layout​_circle Places the vertices of the graph uniformly on a circle or a sphere.
Method layout​_davidson​_harel Places the vertices on a 2D plane according to the Davidson-Harel layout algorithm.
Method layout​_drl Places the vertices on a 2D plane or in the 3D space ccording to the DrL layout algorithm.
Method layout​_fruchterman​_reingold Places the vertices on a 2D plane according to the Fruchterman-Reingold algorithm.
Method layout​_graphopt This is a port of the graphopt layout algorithm by Michael Schmuhl. graphopt version 0.4.1 was rewritten in C and the support for layers was removed.
Method layout​_grid Places the vertices of a graph in a 2D or 3D grid.
Method layout​_kamada​_kawai Places the vertices on a plane according to the Kamada-Kawai algorithm.
Method layout​_lgl Places the vertices on a 2D plane according to the Large Graph Layout.
Method layout​_mds Places the vertices in an Euclidean space with the given number of dimensions using multidimensional scaling.
Method layout​_random Places the vertices of the graph randomly.
Method layout​_reingold​_tilford Places the vertices on a 2D plane according to the Reingold-Tilford layout algorithm.
Method layout​_reingold​_tilford​_circular Circular Reingold-Tilford layout for trees.
Method layout​_star Calculates a star-like layout for the graph.
Method LCF Generates a graph from LCF notation.
Method linegraph Returns the line graph of the graph.
Method maxdegree Returns the maximum degree of a vertex set in the graph.
Method maxflow​_value Returns the value of the maximum flow between the source and target vertices.
Method maximal​_cliques Returns the maximal cliques of the graph as a list of tuples.
Method maximal​_independent​_vertex​_sets Returns the maximal independent vertex sets of the graph as a list of tuples.
Method maximum​_cardinality​_search No summary
Method mincut​_value Returns the minimum cut between the source and target vertices or within the whole graph.
Method minimum​_size​_separators Returns a list containing all separator vertex sets of minimum size.
Method motifs​_randesu Counts the number of motifs in the graph
Method motifs​_randesu​_estimate Counts the total number of motifs in the graph
Method motifs​_randesu​_no Counts the total number of motifs in the graph
Method neighborhood No summary
Method neighborhood​_size No summary
Method neighbors Returns adjacent vertices to a given vertex.
Method permute​_vertices Permutes the vertices of the graph according to the given permutation and returns the new graph.
Method personalized​_pagerank Calculates the personalized PageRank values of a graph.
Method predecessors Returns the predecessors of a given vertex.
Method ​Preference Generates a graph based on vertex types and connection probabilities.
Method radius Calculates the radius of the graph.
Method random​_walk Performs a random walk of a given length from a given node.
Method ​Read_​DL Reads an UCINET DL file and creates a graph based on it.
Method ​Read_​Edgelist Reads an edge list from a file and creates a graph based on it.
Method ​Read_​GML Reads a GML file and creates a graph based on it.
Method ​Read_​Graph​DB Reads a GraphDB format file and creates a graph based on it.
Method ​Read_​Graph​ML Reads a GraphML format file and creates a graph based on it.
Method ​Read_​Lgl Reads an .lgl file used by LGL.
Method ​Read_​Ncol Reads an .ncol file used by LGL.
Method ​Read_​Pajek Reads a Pajek format file and creates a graph based on it.
Method ​Realize_​Degree_​Sequence Generates a graph from a degree sequence.
Method ​Recent_​Degree Generates a graph based on a stochastic model where the probability of an edge gaining a new node is proportional to the edges gained in a given time window.
Method reciprocity No summary
Method rewire Randomly rewires the graph while preserving the degree distribution.
Method rewire​_edges Rewires the edges of a graph with constant probability.
Method ​Ring Generates a ring graph.
Method SBM Generates a graph based on a stochastic blockmodel.
Method shortest​_paths Calculates shortest path lengths for given vertices in a graph.
Method similarity​_dice Dice similarity coefficient of vertices.
Method similarity​_inverse​_log​_weighted Inverse log-weighted similarity coefficient of vertices.
Method similarity​_jaccard Jaccard similarity coefficient of vertices.
Method simplify Simplifies a graph by removing self-loops and/or multiple edges.
Method st​_mincut Calculates the minimum cut between the source and target vertices in a graph.
Method ​Star Generates a star graph.
Method ​Static_​Fitness Generates a non-growing graph with edge probabilities proportional to node fitnesses.
Method ​Static_​Power_​Law Generates a non-growing graph with prescribed power-law degree distributions.
Method strength Returns the strength (weighted degree) of some vertices from the graph
Method subcomponent Determines the indices of vertices which are in the same component as a given vertex.
Method subgraph​_edges Returns a subgraph spanned by the given edges.
Method subisomorphic​_lad Checks whether a subgraph of the graph is isomorphic to another graph.
Method subisomorphic​_vf2 Checks whether a subgraph of the graph is isomorphic to another graph.
Method successors Returns the successors of a given vertex.
Method to​_directed Converts an undirected graph to directed.
Method to​_prufer Converts a tree graph into a Prufer sequence.
Method to​_undirected Converts a directed graph to undirected.
Method topological​_sorting Calculates a possible topological sorting of the graph.
Method transitivity​_local​_undirected Calculates the local transitivity (clustering coefficient) of the given vertices in the graph.
Method transitivity​_undirected Calculates the global transitivity (clustering coefficient) of the graph.
Method ​Tree Generates a tree in which almost all vertices have the same number of children.
Method ​Tree_​Game Generates a random tree by sampling uniformly from the set of labelled trees with a given number of nodes.
Method unfold​_tree Unfolds the graph using a BFS to a tree by duplicating vertices as necessary.
Method vcount Counts the number of vertices.
Method vertex​_attributes
Method vertex​_connectivity Calculates the vertex connectivity of the graph or between some vertices.
Method ​Watts_​Strogatz No summary
Method ​Weighted_​Adjacency Generates a graph from its adjacency matrix.
Method write​_dot Writes the graph in DOT format to the given file.
Method write​_edgelist Writes the edge list of a graph to a file.
Method write​_gml Writes the graph in GML format to the given file.
Method write​_graphml Writes the graph to a GraphML file.
Method write​_leda Writes the graph to a file in LEDA native format.
Method write​_lgl Writes the edge list of a graph to a file in .lgl format.
Method write​_ncol Writes the edge list of a graph to a file in .ncol format.
Method write​_pajek Writes the graph in Pajek format to the given file.
Method __graph​_as​_capsule Returns the igraph graph encapsulated by the Python object as a PyCapsule
Method __register​_destructor Registers a destructor to be called when the object is freed by Python. This function should not be used directly by igraph users.
Method _​Bipartite Internal function, undocumented.
Method _​Full_​Bipartite Internal function, undocumented.
Method _get​_all​_simple​_paths Internal function, undocumented.
Method _GRG Internal function, undocumented.
Method _​Incidence Internal function, undocumented.
Method _is​_matching Internal function, undocumented.
Method _is​_maximal​_matching Internal function, undocumented.
Method _layout​_sugiyama Internal function, undocumented.
Method _maximum​_bipartite​_matching Internal function, undocumented.
Method _​Random_​Bipartite Internal function, undocumented.
Method _raw​_pointer Returns the memory address of the igraph graph encapsulated by the Python object as an ordinary Python integer.
Method _spanning​_tree Internal function, undocumented.
@classmethod
def Adjacency(cls, matrix, mode='directed', *args, **kwargs):
Generates a graph from its adjacency matrix.
Parameters
matrix

the adjacency matrix. Possible types are:

  • a list of lists
  • a numpy 2D array or matrix (will be converted to list of lists)
  • a scipy.sparse matrix (will be converted to a COO matrix, but not to a dense matrix)
  • a pandas.DataFrame (column/row names must match, and will be used as vertex names).
mode

the mode to be used. Possible values are:

  • "directed" - the graph will be directed and a matrix element gives the number of edges between two vertex.
  • "undirected" - alias to "max" for convenience.
  • "max" - undirected graph will be created and the number of edges between vertex i and j is max(A(i, j), A(j, i))
  • "min" - like "max", but with min(A(i, j), A(j, i))
  • "plus" - like "max", but with A(i, j) + A(j, i)
  • "upper" - undirected graph with the upper right triangle of the matrix (including the diagonal)
  • "lower" - undirected graph with the lower left triangle of the matrix (including the diagonal)
*argsUndocumented
**kwargsUndocumented
@classmethod
def Bipartite(cls, types, edges, directed=False, *args, **kwds):

Creates a bipartite graph with the given vertex types and edges. This is similar to the default constructor of the graph, the only difference is that it checks whether all the edges go between the two vertex classes and it assigns the type vector to a type attribute afterwards.

Examples:

>>> g = Graph.Bipartite([0, 1, 0, 1], [(0, 1), (2, 3), (0, 3)])
>>> g.is_bipartite()
True
>>> g.vs["type"]
[False, True, False, True]
Parameters
typesthe vertex types as a boolean list. Anything that evaluates to False will denote a vertex of the first kind, anything that evaluates to True will denote a vertex of the second kind.
edgesthe edges as a list of tuples.
directedwhether to create a directed graph. Bipartite networks are usually undirected, so the default is False
*argsUndocumented
**kwdsUndocumented
Returns
the graph with a binary vertex attribute named "type" that stores the vertex classes.
@classmethod
def DataFrame(cls, edges, directed=True, vertices=None, use_vids=True):
Generates a graph from one or two dataframes.
Parameters
edgespandas DataFrame containing edges and metadata. The first two columns of this DataFrame contain the source and target vertices for each edge. These indicate the vertex IDs as nonnegative integers rather than vertex names unless use_vids is False. Further columns may contain edge attributes.
directed:boolwhether the graph is directed
verticesNone (default) or pandas DataFrame containing vertex metadata. The DataFrame's index must contain the vertex IDs as a sequence of intergers from 0 to len(vertices) - 1. If use_vids is False, the first column must contain the unique vertex names. Vertex names should be strings for full compatibility, but many functions will work if you set the name with any hashable object. All other columns will be added as vertex attributes by column name.
use​_vids:boolwhether to interpret the first two columns of the edges argument as vertex ids (0-based integers) instead of vertex names. If this argument is set to True and the first two columns of edges are not integers, an error is thrown.
Returns

the graph

Vertex names in either the edges or vertices arguments that are set to NaN (not a number) will be set to the string "NA". That might lead to unexpected behaviour: fill your NaNs with values before calling this function to mitigate.

@classmethod
def DictDict(cls, edges, directed=False, vertex_name_attr='name'):

Constructs a graph from a dict-of-dicts representation.

Each key can be an integer or a string and represent a vertex. Each value is a dict representing edges (outgoing if the graph is directed) from that vertex. Each dict key is an integer/string for a target vertex, such that an edge will be created between those two vertices. Integers are interpreted as vertex_ids from 0 (as used in igraph), strings are interpreted as vertex names, in which case vertices are given separate numeric ids. Each value is a dictionary of edge attributes for that edge.

Example:

>>> {'Alice': {'Bob': {'weight': 1.5}, 'David': {'weight': 2}}}

creates a graph with three vertices (Alice, Bob, and David) and two edges:

  • Alice - Bob (with weight 1.5)
  • Alice - David (with weight 2)
Parameters
edgesthe dict of dict of dicts specifying the edges and their attributes
directed:boolwhether to create a directed graph
vertex​_name​_attr:strUndocumented
Returns
a Graph object
Unknown Field: vertex_name_attr
vertex attribute that will store the names
@classmethod
def DictList(cls, vertices, edges, directed=False, vertex_name_attr='name', edge_foreign_keys=('source', 'target'), iterative=False):

Constructs a graph from a list-of-dictionaries representation.

This function is useful when you have two lists of dictionaries, one for vertices and one for edges, each containing their attributes (e.g. name, weight). Of course, the edge dictionary must also contain two special keys that indicate the source and target vertices connected by that edge. Non-list iterables should work as long as they yield dictionaries or dict-like objects (they should have the 'items' and '__getitem__' methods). For instance, a database query result is likely to be fit as long as it's iterable and yields dict-like objects with every iteration.

Parameters
verticesthe list of dictionaries for the vertices or None if there are no special attributes assigned to vertices and we should simply use the edge list of dicts to infer vertex names.
edgesthe list of dictionaries for the edges. Each dict must have at least the two keys specified by edge_foreign_keys to label the source and target vertices, while additional items will be treated as edge attributes.
directed:boolwhether the constructed graph will be directed
vertex​_name​_attr:strthe name of the distinguished key in the dicts in the vertex data source that contains the vertex names. Ignored if vertices is None.
edge​_foreign​_keystuple specifying the attributes in each edge dictionary that contain the source (1st) and target (2nd) vertex names. These items of each dictionary are also added as edge_attributes.
iterative:boolwhether to add the edges to the graph one by one, iteratively, or to build a large edge list first and use that to construct the graph. The latter approach is faster but it may not be suitable if your dataset is large. The default is to add the edges in a batch from an edge list.
Returns

the graph that was constructed

Example:

>>> vertices = [{'name': 'apple'}, {'name': 'pear'}, {'name': 'peach'}]
>>> edges = [{'source': 'apple', 'target': 'pear', 'weight': 1.2},
...          {'source': 'apple', 'target': 'peach', 'weight': 0.9}]
>>> g = Graph.DictList(vertices, edges)

The graph has three vertices with names and two edges with weights.

@classmethod
def from_graph_tool(cls, g):
Converts the graph from graph-tool
Parameters
ggraph-tool Graph
@classmethod
def from_networkx(cls, g, vertex_attr_hashable='_nx_name'):

Converts the graph from networkx

Vertex names will be stored as a vertex_attr_hashable attribute (usually "_nx_name", but see below). Because igraph stored vertices in an ordered manner, vertices will get new IDs from 0 up. In case of multigraphs, each edge will have an "_nx_multiedge_key" attribute, to distinguish edges that connect the same two vertices.

Parameters
gnetworkx Graph or DiGraph
vertex​_attr​_hashable:strattribute used to store the Python hashable used by networkx to identify each vertex. The default value '_nx_name' ensures lossless round trip conversions to/from networkx. An alternative choice is 'name': in that case, using strings for vertex names is recommended and, if the graph is re-exported to networkx, Graph.to_networkx(vertex_attr_hashable="name") must be used to recover the correct vertex nomenclature in the exported network.
@classmethod
def GRG(cls, n, radius, torus=False):

Generates a random geometric graph.

The algorithm drops the vertices randomly on the 2D unit square and connects them if they are closer to each other than the given radius. The coordinates of the vertices are stored in the vertex attributes x and y.

Parameters
nThe number of vertices in the graph
radiusThe given radius
torusThis should be True if we want to use a torus instead of a square.
@classmethod
def Incidence(cls, matrix, directed=False, mode='out', multiple=False, weighted=None, *args, **kwds):

Creates a bipartite graph from an incidence matrix.

Example:

>>> g = Graph.Incidence([[0, 1, 1], [1, 1, 0]])
Parameters
matrixthe incidence matrix.
directedwhether to create a directed graph.
modedefines the direction of edges in the graph. If "out", then edges go from vertices of the first kind (corresponding to rows of the matrix) to vertices of the second kind (the columns of the matrix). If "in", the opposite direction is used. "all" creates mutual edges. Ignored for undirected graphs.
multipledefines what to do with non-zero entries in the matrix. If False, non-zero entries will create an edge no matter what the value is. If True, non-zero entries are rounded up to the nearest integer and this will be the number of multiple edges created.
weighteddefines whether to create a weighted graph from the incidence matrix. If it is c{None} then an unweighted graph is created and the multiple argument is used to determine the edges of the graph. If it is a string then for every non-zero matrix entry, an edge is created and the value of the entry is added as an edge attribute named by the weighted argument. If it is True then a weighted graph is created and the name of the edge attribute will be ‘weight’.
*argsUndocumented
**kwdsUndocumented
Returns
the graph with a binary vertex attribute named "type" that stores the vertex classes.
Raises
ValueErrorif the weighted and multiple are passed together.
@classmethod
def ListDict(cls, edges, directed=False, vertex_name_attr='name'):

Constructs a graph from a dict-of-lists representation.

This function is used to construct a graph from a dictionary of lists. Other, non-list sequences (e.g. tuples) and lazy iterators are are accepted. For each key x, its corresponding value must be a sequence of multiple values y: the edge (x,y) will be created in the graph. x and y must be either one of:

  • two integers: the vertices with those ids will be connected
  • two strings: the vertices with those names will be connected

If names are used, the order of vertices is not guaranteed, and each vertex will be given the vertex_name_attr attribute.

Parameters
edgesthe dict of sequences describing the edges
directed:boolwhether to create a directed graph
vertex​_name​_attr:strUndocumented
Returns

a Graph object

Example:

>>> mydict = {'apple': ['pear', 'peach'], 'pear': ['peach']}
>>> g = Graph.ListDict(mydict)

# The graph has three vertices with names and three edges connecting # each pair.

Unknown Field: vertex_name_attr
vertex attribute that will store the names
@classmethod
def Read(cls, f, format=None, *args, **kwds):

Unified reading function for graphs.

This method tries to identify the format of the graph given in the first parameter and calls the corresponding reader method.

The remaining arguments are passed to the reader method without any changes.

Parameters
fthe file containing the graph to be loaded
formatthe format of the file (if known in advance). None means auto-detection. Possible values are: "ncol" (NCOL format), "lgl" (LGL format), "graphdb" (GraphDB format), "graphml", "graphmlz" (GraphML and gzipped GraphML format), "gml" (GML format), "net", "pajek" (Pajek format), "dimacs" (DIMACS format), "edgelist", "edges" or "edge" (edge list), "adjacency" (adjacency matrix), "dl" (DL format used by UCINET), "pickle" (Python pickled format), "picklez" (gzipped Python pickled format)
*argsUndocumented
**kwdsUndocumented
Raises
IOErrorif the file format can't be identified and none was given.
@classmethod
def Read_DIMACS(cls, f, directed=False):

Reads a graph from a file conforming to the DIMACS minimum-cost flow file format.

For the exact definition of the format, see http://lpsolve.sourceforge.net/5.5/DIMACS.htm.

Restrictions compared to the official description of the format are as follows:

  • igraph's DIMACS reader requires only three fields in an arc definition, describing the edge's source and target node and its capacity.
  • Source vertices are identified by 's' in the FLOW field, target vertices are identified by 't'.
  • Node indices start from 1. Only a single source and target node is allowed.
Parameters
fthe name of the file or a Python file handle
directedwhether the generated graph should be directed.
Returns
the generated graph. The indices of the source and target vertices are attached as graph attributes source and target, the edge capacities are stored in the capacity edge attribute.
@classmethod
def Read_GraphMLz(cls, f, index=0):
Reads a graph from a zipped GraphML file.
Parameters
fthe name of the file
indexif the GraphML file contains multiple graphs, specified the one that should be loaded. Graph indices start from zero, so if you want to load the first graph, specify 0 here.
Returns
the loaded graph object
@classmethod
def Read_Pickle(cls, fname=None):
Reads a graph from Python pickled format
Parameters
fnamethe name of the file, a stream to read from, or a string containing the pickled data.
Returns
the created graph object.
@classmethod
def Read_Picklez(cls, fname):
Reads a graph from compressed Python pickled format, uncompressing it on-the-fly.
Parameters
fnamethe name of the file or a stream to read from.
Returns
the created graph object.
@classmethod
def TupleList(cls, edges, directed=False, vertex_name_attr='name', edge_attrs=None, weights=False):

Constructs a graph from a list-of-tuples representation.

This representation assumes that the edges of the graph are encoded in a list of tuples (or lists). Each item in the list must have at least two elements, which specify the source and the target vertices of the edge. The remaining elements (if any) specify the edge attributes of that edge, where the names of the edge attributes originate from the edge_attrs list. The names of the vertices will be stored in the vertex attribute given by vertex_name_attr.

The default parameters of this function are suitable for creating unweighted graphs from lists where each item contains the source vertex and the target vertex. If you have a weighted graph, you can use items where the third item contains the weight of the edge by setting edge_attrs to "weight" or ["weight"]. If you have even more edge attributes, add them to the end of each item in the edges list and also specify the corresponding edge attribute names in edge_attrs as a list.

Parameters
edgesthe data source for the edges. This must be a list where each item is a tuple (or list) containing at least two items: the name of the source and the target vertex. Note that names will be assigned to the name vertex attribute (or another vertex attribute if vertex_name_attr is specified), even if all the vertex names in the list are in fact numbers.
directed:boolwhether the constructed graph will be directed
vertex​_name​_attr:strthe name of the vertex attribute that will contain the vertex names.
edge​_attrsthe names of the edge attributes that are filled with the extra items in the edge list (starting from index 2, since the first two items are the source and target vertices). If None or an empty sequence, only the source and target vertices will be extracted and additional tuple items will be ignored. If a string, it is interpreted as a single edge attribute.
weightsalternative way to specify that the graph is weighted. If you set weights to true and edge_attrs is not given, it will be assumed that edge_attrs is ["weight"] and igraph will parse the third element from each item into an edge weight. If you set weights to a string, it will be assumed that edge_attrs contains that string only, and igraph will store the edge weights in that attribute.
Returns
the graph that was constructed
def __add__(graph, other):
Copies the graph and extends the copy depending on the type of the other object given.
Parameters
graphUndocumented
otherif it is an integer, the copy is extended by the given number of vertices. If it is a string, the copy is extended by a single vertex whose name attribute will be equal to the given string. If it is a tuple with two elements, the copy is extended by a single edge. If it is a list of tuples, the copy is extended by multiple edges. If it is a Graph, a disjoint union is performed.
def __and__(graph, other):
Graph intersection operator.
Parameters
graphUndocumented
otherthe other graph to take the intersection with.
Returns
the intersected graph.
def __bool__(self):
Returns True if the graph has at least one vertex, False otherwise.
def __coerce__(self, other):

Coercion rules.

This method is needed to allow the graph to react to additions with lists, tuples, integers, strings, vertices, edges and so on.

def __iadd__(graph, other):
In-place addition (disjoint union).
See Also
__add__
def __init__(self, *args, **kwds):

__init__(n=0, edges=None, directed=False, graph_attrs=None, vertex_attrs=None, edge_attrs=None)

Constructs a graph from scratch.

Parameters
*argsUndocumented
**kwdsUndocumented
nthe number of vertices. Can be omitted, the default is zero. Note that if the edge list contains vertices with indexes larger than or equal to m, then the number of vertices will be adjusted accordingly.
edgesthe edge list where every list item is a pair of integers. If any of the integers is larger than n − 1, the number of vertices is adjusted accordingly. None means no edges.
directedwhether the graph should be directed
graph​_attrsthe attributes of the graph as a dictionary.
vertex​_attrsthe attributes of the vertices as a dictionary. Every dictionary value must be an iterable with exactly n items.
edge​_attrsthe attributes of the edges as a dictionary. Every dictionary value must be an iterable with exactly m items where m is the number of edges.
def __isub__(graph, other):
In-place subtraction (difference).
See Also
__sub__
def __mul__(graph, other):
Copies exact replicas of the original graph an arbitrary number of times.
Parameters
graphUndocumented
otherif it is an integer, multiplies the graph by creating the given number of identical copies and taking the disjoint union of them.
def __or__(graph, other):
Graph union operator.
Parameters
graphUndocumented
otherthe other graph to take the union with.
Returns
the union graph.
def __plot__(self, backend, context, *args, **kwds):

Plots the graph to the given Cairo context or matplotlib Axes.

The visual style of vertices and edges can be modified at three places in the following order of precedence (lower indices override higher indices):

  1. Keyword arguments of this function (or of plot() which is passed intact to Graph.__plot__().
  2. Vertex or edge attributes, specified later in the list of keyword arguments.
  3. igraph-wide plotting defaults (see igraph.config.Configuration)
  4. Built-in defaults.

E.g., if the vertex_size keyword attribute is not present, but there exists a vertex attribute named size, the sizes of the vertices will be specified by that attribute.

Besides the usual self-explanatory plotting parameters (context, bbox, palette), it accepts the following keyword arguments:

  • autocurve: whether to use curves instead of straight lines for multiple edges on the graph plot. This argument may be True or False; when omitted, True is assumed for graphs with less than 10.000 edges and False otherwise.

  • drawer_factory: a subclass of AbstractCairoGraphDrawer which will be used to draw the graph. You may also provide a function here which takes two arguments: the Cairo context to draw on and a bounding box (an instance of BoundingBox). If this keyword argument is missing, igraph will use the default graph drawer which should be suitable for most purposes. It is safe to omit this keyword argument unless you need to use a specific graph drawer.

  • keep_aspect_ratio: whether to keep the aspect ratio of the layout that igraph calculates to place the nodes. True means that the layout will be scaled proportionally to fit into the bounding box where the graph is to be drawn but the aspect ratio will be kept the same (potentially leaving empty space next to, below or above the graph). False means that the layout will be scaled independently along the X and Y axis in order to fill the entire bounding box. The default is False.

  • layout: the layout to be used. If not an instance of Layout, it will be passed to layout to calculate the layout. Note that if you want a deterministic layout that does not change with every plot, you must either use a deterministic layout function (like GraphBase.layout_circle) or calculate the layout in advance and pass a Layout object here.

  • margin: the top, right, bottom, left margins as a 4-tuple. If it has less than 4 elements or is a single float, the elements will be re-used until the length is at least 4.

  • mark_groups: whether to highlight some of the vertex groups by colored polygons. This argument can be one of the following:

    • False: no groups will be highlighted
    • True: only valid if the object plotted is a VertexClustering or VertexCover. The vertex groups in the clutering or cover will be highlighted such that the i-th group will be colored by the i-th color from the current palette. If used when plotting a graph, it will throw an error.
    • A dict mapping tuples of vertex indices to color names. The given vertex groups will be highlighted by the given colors.
    • A list containing pairs or an iterable yielding pairs, where the first element of each pair is a list of vertex indices and the second element is a color.
    • A VertexClustering or VertexCover instance. The vertex groups in the clustering or cover will be highlighted such that the i-th group will be colored by the i-th color from the current palette.

    In place of lists of vertex indices, you may also use VertexSeq instances.

    In place of color names, you may also use color indices into the current palette. None as a color name will mean that the corresponding group is ignored.

  • vertex_size: size of the vertices. The corresponding vertex attribute is called size. The default is 10. Vertex sizes are measured in the unit of the Cairo context on which igraph is drawing.

  • vertex_color: color of the vertices. The corresponding vertex attribute is color, the default is red. Colors can be specified either by common X11 color names (see the source code of igraph.drawing.colors for a list of known colors), by 3-tuples of floats (ranging between 0 and 255 for the R, G and B components), by CSS-style string specifications (#rrggbb) or by integer color indices of the specified palette.

  • vertex_frame_color: color of the frame (i.e. stroke) of the vertices. The corresponding vertex attribute is frame_color, the default is black. See vertex_color for the possible ways of specifying a color.

  • vertex_frame_width: the width of the frame (i.e. stroke) of the vertices. The corresponding vertex attribute is frame_width. The default is 1. Vertex frame widths are measured in the unit of the Cairo context on which igraph is drawing.

  • vertex_shape: shape of the vertices. Alternatively it can be specified by the shape vertex attribute. Possibilities are: square, {circle}, {triangle}, {triangle-down} or hidden. See the source code of igraph.drawing for a list of alternative shape names that are also accepted and mapped to these.

  • vertex_label: labels drawn next to the vertices. The corresponding vertex attribute is label.

  • vertex_label_dist: distance of the midpoint of the vertex label from the center of the corresponding vertex. The corresponding vertex attribute is label_dist.

  • vertex_label_color: color of the label. Corresponding vertex attribute: label_color. See vertex_color for color specification syntax.

  • vertex_label_size: font size of the label, specified in the unit of the Cairo context on which we are drawing. Corresponding vertex attribute: label_size.

  • vertex_label_angle: the direction of the line connecting the midpoint of the vertex with the midpoint of the label. This can be used to position the labels relative to the vertices themselves in conjunction with vertex_label_dist. Corresponding vertex attribute: label_angle. The default is -math.pi/2.

  • vertex_order: drawing order of the vertices. This must be a list or tuple containing vertex indices; vertices are then drawn according to this order.

  • vertex_order_by: an alternative way to specify the drawing order of the vertices; this attribute is interpreted as the name of a vertex attribute, and vertices are drawn such that those with a smaller attribute value are drawn first. You may also reverse the order by passing a tuple here; the first element of the tuple should be the name of the attribute, the second element specifies whether the order is reversed (True, False, "asc" and "desc" are accepted values).

  • edge_color: color of the edges. The corresponding edge attribute is color, the default is red. See vertex_color for color specification syntax.

  • edge_curved: whether the edges should be curved. Positive numbers correspond to edges curved in a counter-clockwise direction, negative numbers correspond to edges curved in a clockwise direction. Zero represents straight edges. True is interpreted as 0.5, False is interpreted as 0. The default is 0 which makes all the edges straight.

  • edge_width: width of the edges in the default unit of the Cairo context on which we are drawing. The corresponding edge attribute is width, the default is 1.

  • edge_arrow_size: arrow size of the edges. The corresponding edge attribute is arrow_size, the default is 1.

  • edge_arrow_width: width of the arrowhead on the edge. The corresponding edge attribute is arrow_width, the default is 1.

  • edge_order: drawing order of the edges. This must be a list or tuple containing edge indices; edges are then drawn according to this order.

  • edge_order_by: an alternative way to specify the drawing order of the edges; this attribute is interpreted as the name of an edge attribute, and edges are drawn such that those with a smaller attribute value are drawn first. You may also reverse the order by passing a tuple here; the first element of the tuple should be the name of the attribute, the second element specifies whether the order is reversed (True, False, "asc" and "desc" are accepted values).

def __reduce__(self):
Support for pickling.
def __str__(self):

Returns a string representation of the graph.

Behind the scenes, this method constructs a GraphSummary instance and invokes its __str__ method with a verbosity of 1 and attribute printing turned off.

See the documentation of GraphSummary for more details about the output.

def __sub__(graph, other):
Removes the given object(s) from the graph
Parameters
graphUndocumented
otherif it is an integer, removes the vertex with the given ID from the graph (note that the remaining vertices will get re-indexed!). If it is a tuple, removes the given edge. If it is a graph, takes the difference of the two graphs. Accepts lists of integers or lists of tuples as well, but they can't be mixed! Also accepts Edge and EdgeSeq objects.
def add_edge(graph, source, target, **kwds):

Adds a single edge to the graph.

Keyword arguments (except the source and target arguments) will be assigned to the edge as attributes.

The performance cost of adding a single edge or several edges to a graph is similar. Thus, when adding several edges, a single add_edges() call is more efficient than multiple add_edge() calls.

Parameters
graphUndocumented
sourcethe source vertex of the edge or its name.
targetthe target vertex of the edge or its name.
**kwdsUndocumented
Returns
the newly added edge as an Edge object. Use add_edges([(source, target)]) if you don't need the Edge object and want to avoid the overhead of creating it.
def add_edges(graph, es, attributes=None):
Adds some edges to the graph.
Parameters
graphUndocumented
esthe list of edges to be added. Every edge is represented with a tuple containing the vertex IDs or names of the two endpoints. Vertices are enumerated from zero.
attributesdict of sequences, all of length equal to the number of edges to be added, containing the attributes of the new edges.
def add_vertex(graph, name=None, **kwds):
Adds a single vertex to the graph. Keyword arguments will be assigned as vertex attributes. Note that name as a keyword argument is treated specially; if a graph has name as a vertex attribute, it allows one to refer to vertices by their names in most places where igraph expects a vertex ID.
Returns
the newly added vertex as a Vertex object. Use add_vertices(1) if you don't need the Vertex object and want to avoid the overhead of creating t.
def add_vertices(graph, n, attributes=None):

Adds some vertices to the graph.

Note that if n is a sequence of strings, indicating the names of the new vertices, and attributes has a key name, the two conflict. In that case the attribute will be applied.

Parameters
graphUndocumented
nthe number of vertices to be added, or the name of a single vertex to be added, or a sequence of strings, each corresponding to the name of a vertex to be added. Names will be assigned to the name vertex attribute.
attributesdict of sequences, all of length equal to the number of vertices to be added, containing the attributes of the new vertices. If n is a string (so a single vertex is added), then the values of this dict are the attributes themselves, but if n=1 then they have to be lists of length 1.
def all_st_cuts(graph, source, target):

Returns all the cuts between the source and target vertices in a directed graph.

This function lists all edge-cuts between a source and a target vertex. Every cut is listed exactly once.

Parameters
graphUndocumented
sourcethe source vertex ID
targetthe target vertex ID
Returns
a list of Cut objects.
Unknown Field: newfield
refReference
Unknown Field: ref
JS Provan and DR Shier: A paradigm for listing (s,t)-cuts in graphs. Algorithmica 15, 351--372, 1996.
def all_st_mincuts(graph, source, target, capacity=None):

Returns all the mincuts between the source and target vertices in a directed graph.

This function lists all minimum edge-cuts between a source and a target vertex.

Parameters
graphUndocumented
sourcethe source vertex ID
targetthe target vertex ID
capacitythe edge capacities (weights). If None, all edges have equal weight. May also be an attribute name.
Returns
a list of Cut objects.
Unknown Field: newfield
refReference
Unknown Field: ref
JS Provan and DR Shier: A paradigm for listing (s,t)-cuts in graphs. Algorithmica 15, 351--372, 1996.
def as_directed(graph, *args, **kwds):
Returns a directed copy of this graph. Arguments are passed on to GraphBase.to_directed() that is invoked on the copy.
def as_undirected(graph, *args, **kwds):
Returns an undirected copy of this graph. Arguments are passed on to GraphBase.to_undirected() that is invoked on the copy.
def biconnected_components(graph, return_articulation_points=False):
Calculates the biconnected components of the graph.
Parameters
graphUndocumented
return​_articulation​_pointswhether to return the articulation points as well
Returns
a VertexCover object describing the biconnected components, and optionally the list of articulation points as well
def bipartite_projection(graph, types='type', multiplicity=True, probe1=-1, which='both'):

Projects a bipartite graph into two one-mode graphs. Edge directions are ignored while projecting.

Examples:

>>> g = Graph.Full_Bipartite(10, 5)
>>> g1, g2 = g.bipartite_projection()
>>> g1.isomorphic(Graph.Full(10))
True
>>> g2.isomorphic(Graph.Full(5))
True
Parameters
graphUndocumented
typesan igraph vector containing the vertex types, or an attribute name. Anything that evalulates to False corresponds to vertices of the first kind, everything else to the second kind.
multiplicityif True, then igraph keeps the multiplicity of the edges in the projection in an edge attribute called "weight". E.g., if there is an A-C-B and an A-D-B triplet in the bipartite graph and there is no other X (apart from X=B and X=D) for which an A-X-B triplet would exist in the bipartite graph, the multiplicity of the A-B edge in the projection will be 2.
probe1this argument can be used to specify the order of the projections in the resulting list. If given and non-negative, then it is considered as a vertex ID; the projection containing the vertex will be the first one in the result.
whichthis argument can be used to specify which of the two projections should be returned if only one of them is needed. Passing 0 here means that only the first projection is returned, while 1 means that only the second projection is returned. (Note that we use 0 and 1 because Python indexing is zero-based). False is equivalent to 0 and True is equivalent to 1. Any other value means that both projections will be returned in a tuple.
Returns
a tuple containing the two projected one-mode graphs if which is not 1 or 2, or the projected one-mode graph specified by the which argument if its value is 0, 1, False or True.
def bipartite_projection_size(graph, types='type', *args, **kwds):
Calculates the number of vertices and edges in the bipartite projections of this graph according to the specified vertex types. This is useful if you have a bipartite graph and you want to estimate the amount of memory you would need to calculate the projections themselves.
Parameters
graphUndocumented
typesan igraph vector containing the vertex types, or an attribute name. Anything that evalulates to False corresponds to vertices of the first kind, everything else to the second kind.
*argsUndocumented
**kwdsUndocumented
Returns
a 4-tuple containing the number of vertices and edges in the first projection, followed by the number of vertices and edges in the second projection.
def blocks(graph, return_articulation_points=False):
Calculates the biconnected components of the graph.
Parameters
graphUndocumented
return​_articulation​_pointswhether to return the articulation points as well
Returns
a VertexCover object describing the biconnected components, and optionally the list of articulation points as well
def clear(graph):
Clears the graph, deleting all vertices, edges, and attributes.
See Also
GraphBase.delete_vertices and Graph.delete_edges.
def community_edge_betweenness(graph, clusters=None, directed=True, weights=None):

Community structure based on the betweenness of the edges in the network.

The idea is that the betweenness of the edges connecting two communities is typically high, as many of the shortest paths between nodes in separate communities go through them. So we gradually remove the edge with the highest betweenness and recalculate the betweennesses after every removal. This way sooner or later the network falls of to separate components. The result of the clustering will be represented by a dendrogram.

Parameters
graphUndocumented
clustersthe number of clusters we would like to see. This practically defines the "level" where we "cut" the dendrogram to get the membership vector of the vertices. If None, the dendrogram is cut at the level which maximizes the modularity when the graph is unweighted; otherwise the dendrogram is cut at at a single cluster (because cluster count selection based on modularities does not make sense for this method if not all the weights are equal).
directedwhether the directionality of the edges should be taken into account or not.
weightsname of an edge attribute or a list containing edge weights.
Returns
a VertexDendrogram object, initally cut at the maximum modularity or at the desired number of clusters.
def community_fastgreedy(graph, weights=None):

Community structure based on the greedy optimization of modularity.

This algorithm merges individual nodes into communities in a way that greedily maximizes the modularity score of the graph. It can be proven that if no merge can increase the current modularity score, the algorithm can be stopped since no further increase can be achieved.

This algorithm is said to run almost in linear time on sparse graphs.

Parameters
graphUndocumented
weightsedge attribute name or a list containing edge weights
Returns
an appropriate VertexDendrogram object.
Unknown Field: newfield
refReference
Unknown Field: ref
A Clauset, MEJ Newman and C Moore: Finding community structure in very large networks. Phys Rev E 70, 066111 (2004).
def community_infomap(graph, edge_weights=None, vertex_weights=None, trials=10):
Finds the community structure of the network according to the Infomap method of Martin Rosvall and Carl T. Bergstrom.
Parameters
graphUndocumented
edge​_weightsname of an edge attribute or a list containing edge weights.
vertex​_weightsname of an vertex attribute or a list containing vertex weights.
trialsthe number of attempts to partition the network.
Returns
an appropriate VertexClustering object with an extra attribute called codelength that stores the code length determined by the algorithm.
Unknown Field: newfield
refReference
Unknown Field: ref
M. Rosvall and C. T. Bergstrom: Maps of information flow reveal community structure in complex networks, PNAS 105, 1118 (2008). http://dx.doi.org/10.1073/pnas.0706851105, http://arxiv.org/abs/0707.0609.
M. Rosvall, D. Axelsson, and C. T. Bergstrom: The map equation, Eur. Phys. J. Special Topics 178, 13 (2009). http://dx.doi.org/10.1140/epjst/e2010-01179-1, http://arxiv.org/abs/0906.1405.
def community_label_propagation(graph, weights=None, initial=None, fixed=None):

Finds the community structure of the graph according to the label propagation method of Raghavan et al.

Initially, each vertex is assigned a different label. After that, each vertex chooses the dominant label in its neighbourhood in each iteration. Ties are broken randomly and the order in which the vertices are updated is randomized before every iteration. The algorithm ends when vertices reach a consensus. Note that since ties are broken randomly, there is no guarantee that the algorithm returns the same community structure after each run. In fact, they frequently differ. See the paper of Raghavan et al on how to come up with an aggregated community structure.

Parameters
graphUndocumented
weightsname of an edge attribute or a list containing edge weights
initialname of a vertex attribute or a list containing the initial vertex labels. Labels are identified by integers from zero to n − 1 where n is the number of vertices. Negative numbers may also be present in this vector, they represent unlabeled vertices.
fixeda list of booleans for each vertex. True corresponds to vertices whose labeling should not change during the algorithm. It only makes sense if initial labels are also given. Unlabeled vertices cannot be fixed. It may also be the name of a vertex attribute; each attribute value will be interpreted as a Boolean.
Returns
an appropriate VertexClustering object.
Unknown Field: newfield
refReference
Unknown Field: ref
Raghavan, U.N. and Albert, R. and Kumara, S. Near linear time algorithm to detect community structures in large-scale networks. Phys Rev E 76:036106, 2007. http://arxiv.org/abs/0709.2938.
def community_leading_eigenvector(graph, clusters=None, weights=None, arpack_options=None):

Newman's leading eigenvector method for detecting community structure.

This is the proper implementation of the recursive, divisive algorithm: each split is done by maximizing the modularity regarding the original network.

Parameters
graphUndocumented
clustersthe desired number of communities. If None, the algorithm tries to do as many splits as possible. Note that the algorithm won't split a community further if the signs of the leading eigenvector are all the same, so the actual number of discovered communities can be less than the desired one.
weightsname of an edge attribute or a list containing edge weights.
arpack​_optionsan ARPACKOptions object used to fine-tune the ARPACK eigenvector calculation. If omitted, the module-level variable called arpack_options is used.
Returns
an appropriate VertexClustering object.
Unknown Field: newfield
refReference
Unknown Field: ref
MEJ Newman: Finding community structure in networks using the eigenvectors of matrices, arXiv:physics/0605087
def community_leading_eigenvector_naive(graph, clusters=None, return_merges=False):

Naive implementation of Newman's eigenvector community structure detection.

This function splits the network into two components according to the leading eigenvector of the modularity matrix and then recursively takes the given number of steps by splitting the communities as individual networks. This is not the correct way, however, see the reference for explanation. Consider using the correct Graph.community_leading_eigenvector method instead.

Parameters
graphUndocumented
clustersthe desired number of communities. If None, the algorithm tries to do as many splits as possible. Note that the algorithm won't split a community further if the signs of the leading eigenvector are all the same, so the actual number of discovered communities can be less than the desired one.
return​_mergeswhether the returned object should be a dendrogram instead of a single clustering.
Returns
an appropriate VertexClustering or VertexDendrogram object.
Unknown Field: newfield
refReference
Unknown Field: ref
MEJ Newman: Finding community structure in networks using the eigenvectors of matrices, arXiv:physics/0605087
def community_leiden(graph, objective_function='CPM', weights=None, resolution_parameter=1.0, beta=0.01, initial_membership=None, n_iterations=2, node_weights=None):
Finds the community structure of the graph using the Leiden algorithm of Traag, van Eck & Waltman.
Parameters
graphUndocumented
objective​_functionwhether to use the Constant Potts Model (CPM) or modularity. Must be either "CPM" or "modularity".
weightsedge weights to be used. Can be a sequence or iterable or even an edge attribute name.
resolution​_parameterthe resolution parameter to use. Higher resolutions lead to more smaller communities, while lower resolutions lead to fewer larger communities.
betaparameter affecting the randomness in the Leiden algorithm. This affects only the refinement step of the algorithm.
initial​_membershipif provided, the Leiden algorithm will try to improve this provided membership. If no argument is provided, the aglorithm simply starts from the singleton partition.
n​_iterationsthe number of iterations to iterate the Leiden algorithm. Each iteration may improve the partition further. Using a negative number of iterations will run until a stable iteration is encountered (i.e. the quality was not increased during that iteration).
node​_weightsthe node weights used in the Leiden algorithm. If this is not provided, it will be automatically determined on the basis of whether you want to use CPM or modularity. If you do provide this, please make sure that you understand what you are doing.
Returns
an appropriate VertexClustering object.
Unknown Field: newfield
refReference
Unknown Field: ref
Traag, V. A., Waltman, L., & van Eck, N. J. (2019). From Louvain to Leiden: guaranteeing well-connected communities. Scientific reports, 9(1), 5233. doi: 10.1038/s41598-019-41695-z
def community_multilevel(graph, weights=None, return_levels=False):

Community structure based on the multilevel algorithm of Blondel et al.

This is a bottom-up algorithm: initially every vertex belongs to a separate community, and vertices are moved between communities iteratively in a way that maximizes the vertices' local contribution to the overall modularity score. When a consensus is reached (i.e. no single move would increase the modularity score), every community in the original graph is shrank to a single vertex (while keeping the total weight of the adjacent edges) and the process continues on the next level. The algorithm stops when it is not possible to increase the modularity any more after shrinking the communities to vertices.

This algorithm is said to run almost in linear time on sparse graphs.

Parameters
graphUndocumented
weightsedge attribute name or a list containing edge weights
return​_levelsif True, the communities at each level are returned in a list. If False, only the community structure with the best modularity is returned.
Returns
a list of VertexClustering objects, one corresponding to each level (if return_levels is True), or a VertexClustering corresponding to the best modularity.
Unknown Field: newfield
refReference
Unknown Field: ref
VD Blondel, J-L Guillaume, R Lambiotte and E Lefebvre: Fast unfolding of community hierarchies in large networks, J Stat Mech P10008 (2008), http://arxiv.org/abs/0803.0476
def community_optimal_modularity(graph, *args, **kwds):

Calculates the optimal modularity score of the graph and the corresponding community structure.

This function uses the GNU Linear Programming Kit to solve a large integer optimization problem in order to find the optimal modularity score and the corresponding community structure, therefore it is unlikely to work for graphs larger than a few (less than a hundred) vertices. Consider using one of the heuristic approaches instead if you have such a large graph.

Returns
the calculated membership vector and the corresponding modularity in a tuple.
def community_spinglass(graph, *args, **kwds):
Finds the community structure of the graph according to the spinglass community detection method of Reichardt & Bornholdt.
Parameters
graphUndocumented
*argsUndocumented
**kwdsUndocumented
weightsedge weights to be used. Can be a sequence or iterable or even an edge attribute name.
spinsinteger, the number of spins to use. This is the upper limit for the number of communities. It is not a problem to supply a (reasonably) big number here, in which case some spin states will be unpopulated.
parupdatewhether to update the spins of the vertices in parallel (synchronously) or not
start​_tempthe starting temperature
stop​_tempthe stop temperature
cool​_factcooling factor for the simulated annealing
update​_rulespecifies the null model of the simulation. Possible values are "config" (a random graph with the same vertex degrees as the input graph) or "simple" (a random graph with the same number of edges)
gammathe gamma argument of the algorithm, specifying the balance between the importance of present and missing edges within a community. The default value of 1.0 assigns equal importance to both of them.
implementationcurrently igraph contains two implementations of the spinglass community detection algorithm. The faster original implementation is the default. The other implementation is able to take into account negative weights, this can be chosen by setting implementation to "neg"
lambda_the lambda argument of the algorithm, which specifies the balance between the importance of present and missing negatively weighted edges within a community. Smaller values of lambda lead to communities with less negative intra-connectivity. If the argument is zero, the algorithm reduces to a graph coloring algorithm, using the number of spins as colors. This argument is ignored if the original implementation is used. Note the underscore at the end of the argument name; this is due to the fact that lambda is a reserved keyword in Python.
Returns
an appropriate VertexClustering object.
Unknown Field: newfield
refReference
Unknown Field: ref
Reichardt J and Bornholdt S: Statistical mechanics of community detection. Phys Rev E 74:016110 (2006). http://arxiv.org/abs/cond-mat/0603718.
Traag VA and Bruggeman J: Community detection in networks with positive and negative links. Phys Rev E 80:036115 (2009). http://arxiv.org/abs/0811.2329.
def community_walktrap(graph, weights=None, steps=4):

Community detection algorithm of Latapy & Pons, based on random walks.

The basic idea of the algorithm is that short random walks tend to stay in the same community. The result of the clustering will be represented as a dendrogram.

Parameters
graphUndocumented
weightsname of an edge attribute or a list containing edge weights
stepslength of random walks to perform
Returns
a VertexDendrogram object, initially cut at the maximum modularity.
Unknown Field: newfield
refReference
Unknown Field: ref
Pascal Pons, Matthieu Latapy: Computing communities in large networks using random walks, http://arxiv.org/abs/physics/0512106.
def components(graph, mode='strong'):
Calculates the (strong or weak) connected components for a given graph.
Parameters
graphUndocumented
modemust be either "strong" or "weak", depending on the connected components being sought. Optional, defaults to "strong".
Returns
a VertexClustering object
def count_automorphisms_vf2(graph, color=None, edge_color=None, node_compat_fn=None, edge_compat_fn=None):

Returns the number of automorphisms of the graph.

This function simply calls count_isomorphisms_vf2 with the graph itgraph. See count_isomorphisms_vf2 for an explanation of the parameters.

Returns
the number of automorphisms of the graph
See Also
Graph.count_isomorphisms_vf2
def degree_distribution(graph, bin_width=1, *args, **kwds):

Calculates the degree distribution of the graph.

Unknown keyword arguments are directly passed to GraphBase.degree.

Parameters
graphUndocumented
bin​_widththe bin width of the histogram
*argsUndocumented
**kwdsUndocumented
Returns
a histogram representing the degree distribution of the graph.
def delete_edges(graph, *args, **kwds):

Deletes some edges from the graph.

The set of edges to be deleted is determined by the positional and keyword arguments. If the function is called without any arguments, all edges are deleted. If any keyword argument is present, or the first positional argument is callable, an edge sequence is derived by calling EdgeSeq.select with the same positional and keyword arguments. Edges in the derived edge sequence will be removed. Otherwise the first positional argument is considered as follows:

  • None - deletes all edges (deprecated since 0.8.3)
  • a single integer - deletes the edge with the given ID
  • a list of integers - deletes the edges denoted by the given IDs
  • a list of 2-tuples - deletes the edges denoted by the given source-target vertex pairs. When multiple edges are present between a given source-target vertex pair, only one is removed.
Unknown Field: deprecated
delete_edges(None) has been replaced by delete_edges() - with no arguments - since igraph 0.8.3.
def dfs(self, vid, mode=OUT):
Conducts a depth first search (DFS) on the graph.
Parameters
vidthe root vertex ID
modeeither "in" or "out" or "all", ignored for undirected graphs.
Returns

a tuple with the following items:

  • The vertex IDs visited (in order)
  • The parent of every vertex in the DFS
def disjoint_union(graph, other):
Creates the disjoint union of two (or more) graphs.
Parameters
graphUndocumented
othergraph or list of graphs to be united with the current one.
Returns
the disjoint union graph
def dyad_census(self, *args, **kwds):

Calculates the dyad census of the graph.

Dyad census means classifying each pair of vertices of a directed graph into three categories: mutual (there is an edge from a to b and also from b to a), asymmetric (there is an edge from a to b or from b to a but not the other way round) and null (there is no connection between a and b).

Returns
a DyadCensus object.
Unknown Field: newfield
refReference
Unknown Field: ref
Holland, P.W. and Leinhardt, S. (1970). A Method for Detecting Structure in Sociometric Data. American Journal of Sociology, 70, 492-513.
def get_adjacency(self, type=GET_ADJACENCY_BOTH, attribute=None, default=0, eids=False):
Returns the adjacency matrix of a graph.
Parameters
typeeither GET_ADJACENCY_LOWER (uses the lower triangle of the matrix) or GET_ADJACENCY_UPPER (uses the upper triangle) or GET_ADJACENCY_BOTH (uses both parts). Ignored for directed graphs.
attributeif None, returns the ordinary adjacency matrix. When the name of a valid edge attribute is given here, the matrix returned will contain the default value at the places where there is no edge or the value of the given attribute where there is an edge. Multiple edges are not supported, the value written in the matrix in this case will be unpredictable. This parameter is ignored if eids is True
defaultthe default value written to the cells in the case of adjacency matrices with attributes.
eidsspecifies whether the edge IDs should be returned in the adjacency matrix. Since zero is a valid edge ID, the cells in the matrix that correspond to unconnected vertex pairs will contain -1 instead of 0 if eids is True. If eids is False, the number of edges will be returned in the matrix for each vertex pair.
Returns
the adjacency matrix as a Matrix.
def get_adjacency_sparse(self, attribute=None):
Returns the adjacency matrix of a graph as a SciPy CSR matrix.
Parameters
attributeif None, returns the ordinary adjacency matrix. When the name of a valid edge attribute is given here, the matrix returned will contain the default value at the places where there is no edge or the value of the given attribute where there is an edge.
Returns
the adjacency matrix as a scipy.sparse.csr_matrix.
def get_adjlist(self, mode='out'):

Returns the adjacency list representation of the graph.

The adjacency list representation is a list of lists. Each item of the outer list belongs to a single vertex of the graph. The inner list contains the neighbors of the given vertex.

Parameters
modeif "out", returns the successors of the vertex. If "in", returns the predecessors of the vertex. If "all"", both the predecessors and the successors will be returned. Ignored for undirected graphs.
def get_all_simple_paths(self, v, to=None, cutoff=-1, mode='out'):

Calculates all the simple paths from a given node to some other nodes (or all of them) in a graph.

A path is simple if its vertices are unique, i.e. no vertex is visited more than once.

Note that potentially there are exponentially many paths between two vertices of a graph, especially if your graph is lattice-like. In this case, you may run out of memory when using this function.

Parameters
vthe source for the calculated paths
toa vertex selector describing the destination for the calculated paths. This can be a single vertex ID, a list of vertex IDs, a single vertex name, a list of vertex names or a VertexSeq object. None means all the vertices.
cutoffmaximum length of path that is considered. If negative, paths of all lengths are considered.
modethe directionality of the paths. "in" means to calculate incoming paths, "out" means to calculate outgoing paths, "all" means to calculate both ones.
Returns
all of the simple paths from the given node to every other reachable node in the graph in a list. Note that in case of mode="in", the vertices in a path are returned in reversed order!
def get_automorphisms_vf2(graph, color=None, edge_color=None, node_compat_fn=None, edge_compat_fn=None):

Returns all the automorphisms of the graph

This function simply calls get_isomorphisms_vf2 with the graph itgraph. See get_isomorphisms_vf2 for an explanation of the parameters.

Returns
a list of lists, each item containing a possible mapping of the graph vertices to itgraph according to the automorphism
See Also
Graph.get_isomorphisms_vf2
def get_edge_dataframe(graph):

Export edges with attributes to pandas.DataFrame

If you want to use source and target vertex IDs as index, you can do:

>>> from string import ascii_letters
>>> graph = Graph.GRG(25, 0.4)
>>> graph.vs["name"] = ascii_letters[:graph.vcount()]
>>> df = graph.get_edge_dataframe()
>>> df.set_index(['source', 'target'], inplace=True)

The index will be a pandas.MultiIndex. You can use the drop=False option to keep the source and target columns.

If you want to use vertex names in the source and target columns:

>>> df = graph.get_edge_dataframe()
>>> df_vert = graph.get_vertex_dataframe()
>>> df['source'].replace(df_vert['name'], inplace=True)
>>> df['target'].replace(df_vert['name'], inplace=True)
>>> df_vert.set_index('name', inplace=True)  # Optional
Returns
a pandas.DataFrame representing edges and their attributes. The index uses edge IDs, from 0 to M - 1 where M is the number of edges. The first two columns of the dataframe represent the IDs of source and target vertices for each edge. These columns have names "source" and "target". If your edges have attributes with the same names, they will be present in the dataframe, but not in the first two columns.
def get_incidence(graph, types='type', *args, **kwds):
Returns the incidence matrix of a bipartite graph. The incidence matrix is an n times m matrix, where n and m are the number of vertices in the two vertex classes.
Parameters
graphUndocumented
typesan igraph vector containing the vertex types, or an attribute name. Anything that evalulates to False corresponds to vertices of the first kind, everything else to the second kind.
*argsUndocumented
**kwdsUndocumented
Returns
the incidence matrix and two lists in a triplet. The first list defines the mapping between row indices of the matrix and the original vertex IDs. The second list is the same for the column indices.
def get_inclist(graph, mode='out'):

Returns the incidence list representation of the graph.

The incidence list representation is a list of lists. Each item of the outer list belongs to a single vertex of the graph. The inner list contains the IDs of the incident edges of the given vertex.

Parameters
graphUndocumented
modeif "out", returns the successors of the vertex. If "in", returns the predecessors of the vertex. If "all", both the predecessors and the successors will be returned. Ignored for undirected graphs.
def get_vertex_dataframe(graph):

Export vertices with attributes to pandas.DataFrame

If you want to use vertex names as index, you can do:

>>> from string import ascii_letters
>>> graph = Graph.GRG(25, 0.4)
>>> graph.vs["name"] = ascii_letters[:graph.vcount()]
>>> df = graph.get_vertex_dataframe()
>>> df.set_index('name', inplace=True)
Returns
a pandas.DataFrame representing vertices and their attributes. The index uses vertex IDs, from 0 to N - 1 where N is the number of vertices.
def gomory_hu_tree(graph, capacity=None, flow='flow'):

Calculates the Gomory-Hu tree of an undirected graph with optional edge capacities.

The Gomory-Hu tree is a concise representation of the value of all the maximum flows (or minimum cuts) in a graph. The vertices of the tree correspond exactly to the vertices of the original graph in the same order. Edges of the Gomory-Hu tree are annotated by flow values. The value of the maximum flow (or minimum cut) between an arbitrary (u,v) vertex pair in the original graph is then given by the minimum flow value (i.e. edge annotation) along the shortest path between u and v in the Gomory-Hu tree.

Parameters
graphUndocumented
capacitythe edge capacities (weights). If None, all edges have equal weight. May also be an attribute name.
flowthe name of the edge attribute in the returned graph in which the flow values will be stored.
Returns
the Gomory-Hu tree as a Graph object.
def indegree(graph, *args, **kwds):

Returns the in-degrees in a list.

See GraphBase.degree for possible arguments.

def intersection(graph, other, byname='auto'):
Creates the intersection of two (or more) graphs.
Parameters
graphUndocumented
othergraph or list of graphs to be intersected with the current one.
bynamewhether to use vertex names instead of ids. See igraph.operators.intersection for details.
Returns
the intersection graph
def is_named(self):

Returns whether the graph is named.

A graph is named if and only if it has a "name" vertex attribute.

def is_weighted(self):

Returns whether the graph is weighted.

A graph is weighted if and only if it has a "weight" edge attribute.

def k_core(graph, *args):

Returns some k-cores of the graph.

The method accepts an arbitrary number of arguments representing the desired indices of the k-cores to be returned. The arguments can also be lists or tuples. The result is a single Graph object if an only integer argument was given, otherwise the result is a list of Graph objects representing the desired k-cores in the order the arguments were specified. If no argument is given, returns all k-cores in increasing order of k.

def layout(graph, layout=None, *args, **kwds):

Returns the layout of the graph according to a layout algorithm.

Parameters and keyword arguments not specified here are passed to the layout algorithm directly. See the documentation of the layout algorithms for the explanation of these parameters.

Registered layout names understood by this method are:

Parameters
graphUndocumented
layoutthe layout to use. This can be one of the registered layout names or a callable which returns either a Layout object or a list of lists containing the coordinates. If None, uses the value of the plotting.layout configuration key.
*argsUndocumented
**kwdsUndocumented
Returns
a Layout object.
def layout_auto(graph, *args, **kwds):

Chooses and runs a suitable layout function based on simple topological properties of the graph.

This function tries to choose an appropriate layout function for the graph using the following rules:

  1. If the graph has an attribute called layout, it will be used. It may either be a Layout instance, a list of coordinate pairs, the name of a layout function, or a callable function which generates the layout when called with the graph as a parameter.
  2. Otherwise, if the graph has vertex attributes called x and y, these will be used as coordinates in the layout. When a 3D layout is requested (by setting dim to 3), a vertex attribute named z will also be needed.
  3. Otherwise, if the graph is connected and has at most 100 vertices, the Kamada-Kawai layout will be used (see GraphBase.layout_kamada_kawai()).
  4. Otherwise, if the graph has at most 1000 vertices, the Fruchterman-Reingold layout will be used (see GraphBase.layout_fruchterman_reingold()).
  5. If everything else above failed, the DrL layout algorithm will be used (see GraphBase.layout_drl()).

All the arguments of this function except dim are passed on to the chosen layout function (in case we have to call some layout function).

Parameters
graphUndocumented
*argsUndocumented
**kwdsUndocumented
dimspecifies whether we would like to obtain a 2D or a 3D layout.
Returns
a Layout object.
def layout_sugiyama(graph, layers=None, weights=None, hgap=1, vgap=1, maxiter=100, return_extended_graph=False):

Places the vertices using a layered Sugiyama layout.

This is a layered layout that is most suitable for directed acyclic graphs, although it works on undirected or cyclic graphs as well.

Each vertex is assigned to a layer and each layer is placed on a horizontal line. Vertices within the same layer are then permuted using the barycenter heuristic that tries to minimize edge crossings.

Dummy vertices will be added on edges that span more than one layer. The returned layout therefore contains more rows than the number of nodes in the original graph; the extra rows correspond to the dummy vertices.

Parameters
graphUndocumented
layersa vector specifying a non-negative integer layer index for each vertex, or the name of a numeric vertex attribute that contains the layer indices. If None, a layering will be determined automatically. For undirected graphs, a spanning tree will be extracted and vertices will be assigned to layers using a breadth first search from the node with the largest degree. For directed graphs, cycles are broken by reversing the direction of edges in an approximate feedback arc set using the heuristic of Eades, Lin and Smyth, and then using longest path layering to place the vertices in layers.
weightsedge weights to be used. Can be a sequence or iterable or even an edge attribute name.
hgapminimum horizontal gap between vertices in the same layer.
vgapvertical gap between layers. The layer index will be multiplied by vgap to obtain the Y coordinate.
maxitermaximum number of iterations to take in the crossing reduction step. Increase this if you feel that you are getting too many edge crossings.
return​_extended​_graphspecifies that the extended graph with the added dummy vertices should also be returned. When this is True, the result will be a tuple containing the layout and the extended graph. The first |V| nodes of the extended graph will correspond to the nodes of the original graph, the remaining ones are dummy nodes. Plotting the extended graph with the returned layout and hidden dummy nodes will produce a layout that is similar to the original graph, but with the added edge bends. The extended graph also contains an edge attribute called _original_eid which specifies the ID of the edge in the original graph from which the edge of the extended graph was created.
Returns
the calculated layout, which may (and usually will) have more rows than the number of vertices; the remaining rows correspond to the dummy nodes introduced in the layering step. When return_extended_graph is True, it will also contain the extended graph.
Unknown Field: newfield
refReference
Unknown Field: ref
K Sugiyama, S Tagawa, M Toda: Methods for visual understanding of hierarchical system structures. IEEE Systems, Man and Cybernetics 11(2):109-125, 1981.
P Eades, X Lin and WF Smyth: A fast effective heuristic for the feedback arc set problem. Information Processing Letters 47:319-323, 1993.
def maxflow(graph, source, target, capacity=None):

Returns a maximum flow between the given source and target vertices in a graph.

A maximum flow from source to target is an assignment of non-negative real numbers to the edges of the graph, satisfying two properties:

  1. For each edge, the flow (i.e. the assigned number) is not more than the capacity of the edge (see the capacity argument)
  2. For every vertex except the source and the target, the incoming flow is the same as the outgoing flow.

The value of the flow is the incoming flow of the target or the outgoing flow of the source (which are equal). The maximum flow is the maximum possible such value.

Parameters
graphUndocumented
sourceUndocumented
targetUndocumented
capacitythe edge capacities (weights). If None, all edges have equal weight. May also be an attribute name.
Returns
a Flow object describing the maximum flow
def maximum_bipartite_matching(graph, types='type', weights=None, eps=None):

Finds a maximum matching in a bipartite graph.

A maximum matching is a set of edges such that each vertex is incident on at most one matched edge and the number (or weight) of such edges in the set is as large as possible.

Parameters
graphUndocumented
typesvertex types in a list or the name of a vertex attribute holding vertex types. Types should be denoted by zeros and ones (or False and True) for the two sides of the bipartite graph. If omitted, it defaults to type, which is the default vertex type attribute for bipartite graphs.
weightsedge weights to be used. Can be a sequence or iterable or even an edge attribute name.
epsa small real number used in equality tests in the weighted bipartite matching algorithm. Two real numbers are considered equal in the algorithm if their difference is smaller than this value. This is required to avoid the accumulation of numerical errors. If you pass None here, igraph will try to determine an appropriate value automatically.
Returns
an instance of Matching.
def mincut(graph, source=None, target=None, capacity=None):

Calculates the minimum cut between the given source and target vertices or within the whole graph.

The minimum cut is the minimum set of edges that needs to be removed to separate the source and the target (if they are given) or to disconnect the graph (if neither the source nor the target are given). The minimum is calculated using the weights (capacities) of the edges, so the cut with the minimum total capacity is calculated.

For undirected graphs and no source and target, the method uses the Stoer-Wagner algorithm. For a given source and target, the method uses the push-relabel algorithm; see the references below.

Parameters
graphUndocumented
sourcethe source vertex ID. If None, the target must also be None and the calculation will be done for the entire graph (i.e. all possible vertex pairs).
targetthe target vertex ID. If None, the source must also be None and the calculation will be done for the entire graph (i.e. all possible vertex pairs).
capacitythe edge capacities (weights). If None, all edges have equal weight. May also be an attribute name.
Returns
a Cut object describing the minimum cut
def modularity(self, membership, weights=None):

Calculates the modularity score of the graph with respect to a given clustering.

The modularity of a graph w.r.t. some division measures how good the division is, or how separated are the different vertex types from each other. It's defined as Q = 1 ⁄ (2m)*sum(Aij − ki*kj ⁄ (2m)delta(ci, cj), i, j). m is the number of edges, Aij is the element of the A adjacency matrix in row i and column j, ki is the degree of node i, kj is the degree of node j, and Ci and cj are the types of the two vertices (i and j). delta(x, y) is one iff x = y, 0 otherwise.

If edge weights are given, the definition of modularity is modified as follows: Aij becomes the weight of the corresponding edge, ki is the total weight of edges adjacent to vertex i, kj is the total weight of edges adjacent to vertex j and m is the total edge weight in the graph.

Parameters
membershipa membership list or a VertexClustering object
weightsoptional edge weights or None if all edges are weighed equally. Attribute names are also allowed.
Returns
the modularity score
Unknown Field: newfield
refReference
Unknown Field: ref
MEJ Newman and M Girvan: Finding and evaluating community structure in networks. Phys Rev E 69 026113, 2004.
def outdegree(graph, *args, **kwds):

Returns the out-degrees in a list.

See GraphBase.degree for possible arguments.

def pagerank(graph, vertices=None, directed=True, damping=0.85, weights=None, arpack_options=None, implementation='prpack', niter=1000, eps=0.001):
Calculates the PageRank values of a graph.
Parameters
graphUndocumented
verticesthe indices of the vertices being queried. None means all of the vertices.
directedwhether to consider directed paths.
dampingthe damping factor. 1 − damping is the PageRank value for nodes with no incoming links. It is also the probability of resetting the random walk to a uniform distribution in each step.
weightsedge weights to be used. Can be a sequence or iterable or even an edge attribute name.
arpack​_optionsan ARPACKOptions object used to fine-tune the ARPACK eigenvector calculation. If omitted, the module-level variable called arpack_options is used. This argument is ignored if not the ARPACK implementation is used, see the implementation argument.
implementation

which implementation to use to solve the PageRank eigenproblem. Possible values are:

  • "prpack": use the PRPACK library. This is a new implementation in igraph 0.7
  • "arpack": use the ARPACK library. This implementation was used from version 0.5, until version 0.7.
  • "power": use a simple power method. This is the implementation that was used before igraph version 0.5.
niterThe number of iterations to use in the power method implementation. It is ignored in the other implementations
epsThe power method implementation will consider the calculation as complete if the difference of PageRank values between iterations change less than this value for every node. It is ignored by the other implementations.
Returns
a list with the Google PageRank values of the specified vertices.
def path_length_hist(self, directed=True):
Returns the path length histogram of the graph
Parameters
directedwhether to consider directed paths. Ignored for undirected graphs.
Returns
a Histogram object. The object will also have an unconnected attribute that stores the number of unconnected vertex pairs (where the second vertex can not be reached from the first one). The latter one will be of type long (and not a simple integer), since this can be very large.
def spanning_tree(self, weights=None, return_tree=True):
Calculates a minimum spanning tree for a graph.
Parameters
weightsa vector containing weights for every edge in the graph. None means that the graph is unweighted.
return​_treewhether to return the minimum spanning tree (when return_tree is True) or to return the IDs of the edges in the minimum spanning tree instead (when return_tree is False). The default is True for historical reasons as this argument was introduced in igraph 0.6.
Returns
the spanning tree as a Graph object if return_tree is True or the IDs of the edges that constitute the spanning tree if return_tree is False.
Unknown Field: newfield
refReference
Unknown Field: ref
Prim, R.C.: Shortest connection networks and some generalizations. Bell System Technical Journal 36:1389-1401, 1957.
def summary(self, verbosity=0, width=None, *args, **kwds):

Returns the summary of the graph.

The output of this method is similar to the output of the __str__ method. If verbosity is zero, only the header line is returned (see __str__ for more details), otherwise the header line and the edge list is printed.

Behind the scenes, this method constructs a GraphSummary object and invokes its __str__ method.

Parameters
verbosityif zero, only the header line is returned (see __str__ for more details), otherwise the header line and the full edge list is printed.
widththe number of characters to use in one line. If None, no limit will be enforced on the line lengths.
*argsUndocumented
**kwdsUndocumented
Returns
the summary of the graph.
def to_dict_dict(graph, use_vids=True, edge_attrs=None, skip_none=False, vertex_name_attr='name'):

Export graph to dictionary of dicts of edge attributes

This function is the reverse of Graph.DictDict.

Example:

>>> g = Graph.Full(3)
>>> g.es['name'] = ['first_edge', 'second', 'third']
>>> g.to_dict_dict()
{0: {1: {'name': 'first_edge'}, 2: {'name': 'second'}}, 1: {2: {'name': 'third'}}}
Parameters
graphUndocumented
use​_vids:boolwhether to label vertices in the output data structure by their ids or their vertex_name_attr attribute. If use_vids=False but vertices lack a vertex_name_attr attribute, an AttributeError is raised.
edge​_attrs:Union[str, Sequence[str]]list of edge attributes to export. None (default) signified all attributes (unlike Graph.to_tuple_list). A string is acceptable to signify a single attribute and will be wrapped in a list internally.
skip​_none:boolwhether to skip, for each edge, attributes that have a value of None. This is useful if only some edges are expected to possess an attribute.
vertex​_name​_attr:strUndocumented
Returns
dictionary of dictionaries of dictionaries, with the outer keys vertex ids/names, the middle keys ids/names of their neighbors, and the innermost dictionary representing attributes of that edge.
Unknown Field: vertex_name_attr
only used with use_vids=False to choose what vertex attribute to use to name your vertices in the output data structure.
def to_dict_list(graph, use_vids=True, skip_none=False, vertex_name_attr='name'):

Export graph as two lists of dictionaries, for vertices and edges.

This function is the reverse of Graph.DictList.

Example:

>>> g = Graph([(0, 1), (1, 2)])
>>> g.vs["name"] = ["apple", "pear", "peach"]
>>> g.es["name"] = ["first_edge", "second"]
>>> g.to_dict_list()
([{"name": "apple"}, {"name": "pear"}, {"name": "peach"}],
 [{"source": 0, "target": 1, "name": "first_edge"},
  {"source" 0, "target": 2, name": "second"}])
>>> g.to_dict_list(use_vids=False)
([{"name": "apple"}, {"name": "pear"}, {"name": "peach"}],
 [{"source": "apple", "target": "pear", "name": "first_edge"},
  {"source" "apple", "target": "peach", name": "second"}])
Parameters
graphUndocumented
use​_vids:boolwhether to label vertices in the output data structure by their ids or their vertex_name_attr attribute. If use_vids=False but vertices lack a vertex_name_attr attribute, an AttributeError is raised.
skip​_none:boolwhether to skip, for each edge, attributes that have a value of None. This is useful if only some edges are expected to possess an attribute.
vertex​_name​_attr:strUndocumented
Returns
a tuple with two lists of dictionaries, representing the vertices and the edges, respectively, with their attributes.
Unknown Field: vertex_name_attr
only used with use_vids=False to choose what vertex attribute to use to name your vertices in the output data structure.
def to_graph_tool(graph, graph_attributes=None, vertex_attributes=None, edge_attributes=None):

Converts the graph to graph-tool

Data types: graph-tool only accepts specific data types. See the following web page for a list:

https://graph-tool.skewed.de/static/doc/quickstart.html

Note: because of the restricted data types in graph-tool, vertex and edge attributes require to be type-consistent across all vertices or edges. If you set the property for only some vertices/edges, the other will be tagged as None in igraph, so they can only be converted to graph-tool with the type 'object' and any other conversion will fail.

Parameters
graphUndocumented
graph​_attributesdictionary of graph attributes to transfer. Keys are attributes from the graph, values are data types (see below). None means no graph attributes are transferred.
vertex​_attributesdictionary of vertex attributes to transfer. Keys are attributes from the vertices, values are data types (see below). None means no vertex attributes are transferred.
edge​_attributesdictionary of edge attributes to transfer. Keys are attributes from the edges, values are data types (see below). None means no vertex attributes are transferred.
def to_list_dict(graph, use_vids=True, sequence_constructor=list, vertex_name_attr='name'):

Export graph to a dictionary of lists (or other sequences).

This function is the reverse of Graph.ListDict.

Example:

>>> g = Graph.Full(3)
>>> g.to_sequence_dict() -> {0: [1, 2], 1: [2]}
>>> g.to_sequence_dict(sequence_constructor=tuple) -> {0: (1, 2), 1: (2,)}
>>> g.vs['name'] = ['apple', 'pear', 'peach']
>>> g.to_sequence_dict(use_vids=False)
{'apple': ['pear', 'peach'], 'pear': ['peach']}
Parameters
graphUndocumented
use​_vids:boolwhether to label vertices in the output data structure by their ids or their vertex_name_attr attribute. If use_vids=False but vertices lack a vertex_name_attr attribute, an AttributeError is raised.
sequence​_constructor:callableconstructor for the data structure to be used as values of the dictionary. The default (list) makes a dict of lists, with each list representing the neighbors of the vertex specified in the respective dictionary key.
vertex​_name​_attr:strUndocumented
Returns
dictionary of sequences, keyed by vertices, with each value containing the neighbors of that vertex.
Unknown Field: vertex_name_attr
only used with use_vids=False to choose what vertex attribute to use to name your vertices in the output data structure.
def to_networkx(graph, create_using=None, vertex_attr_hashable='_nx_name'):

Converts the graph to networkx format.

igraph has ordered vertices and edges, but networkx does not. To keep track of the original order, the '_igraph_index' vertex property is added to both vertices and edges.

Parameters
graphUndocumented
create​_usingspecifies which NetworkX graph class to use when constructing the graph. None means to let igraph infer the most appropriate class based on whether the graph is directed and whether it has multi-edges.
vertex​_attr​_hashable:strvertex attribute used to name vertices in the exported network. The default "_nx_name" ensures round trip conversions to/from networkx are lossless.
def to_tuple_list(graph, use_vids=True, edge_attrs=None, vertex_name_attr='name'):

Export graph to a list of edge tuples

This function is the reverse of Graph.TupleList.

Example:

>>> g = Graph.Full(3)
>>> g.vs["name"] = ["apple", "pear", "peach"]
>>> g.es["name"] = ["first_edge", "second", "third"]
>>> # Get name of the edge
>>> g.to_tuple_list(edge_attrs=["name"])
[(0, 1, "first_edge"), (0, 2, "second"), (1, 2, "third")]
>>> # Use vertex names, no edge attributes
>>> g.to_tuple_list(use_vids=False)
[("apple", "pear"), ("apple", "peach"), ("pear", "peach")]
Parameters
graphUndocumented
use​_vids:boolwhether to label vertices in the output data structure by their ids or their vertex_name_attr attribute. If use_vids=False but vertices lack a vertex_name_attr attribute, an AttributeError is raised.
edge​_attrs:Union[str, Sequence[str]]list of edge attributes to export in addition to source and target vertex, which are always the first two elements of each tuple. None (default) is equivalent to an empty list. A string is acceptable to signify a single attribute and will be wrapped in a list internally.
vertex​_name​_attr:strUndocumented
Returns
a list of tuples, each representing an edge of the graph.
Unknown Field: vertex_name_attr
only used with use_vids=False to choose what vertex attribute to use to name your vertices in the output data structure.
def transitivity_avglocal_undirected(self, mode='nan', weights=None):

Calculates the average of the vertex transitivities of the graph.

In the unweighted case, the transitivity measures the probability that two neighbors of a vertex are connected. In case of the average local transitivity, this probability is calculated for each vertex and then the average is taken. Vertices with less than two neighbors require special treatment, they will either be left out from the calculation or they will be considered as having zero transitivity, depending on the mode parameter. The calculation is slightly more involved for weighted graphs; in this case, weights are taken into account according to the formula of Barrat et al (see the references).

Note that this measure is different from the global transitivity measure (see transitivity_undirected()) as it simply takes the average local transitivity across the whole network.

Parameters
modedefines how to treat vertices with degree less than two. If TRANSITIVITY_ZERO or "zero", these vertices will have zero transitivity. If TRANSITIVITY_NAN or "nan", these vertices will be excluded from the average.
weightsedge weights to be used. Can be a sequence or iterable or even an edge attribute name.
See Also
transitivity_undirected(), transitivity_local_undirected()
Unknown Field: newfield
refReference
Unknown Field: ref
Watts DJ and Strogatz S: Collective dynamics of small-world networks. Nature 393(6884):440-442, 1998.
Barrat A, Barthelemy M, Pastor-Satorras R and Vespignani A: The architecture of complex weighted networks. PNAS 101, 3747 (2004). http://arxiv.org/abs/cond-mat/0311416.
def triad_census(self, *args, **kwds):
Calculates the triad census of the graph.
Returns
a TriadCensus object.
Unknown Field: newfield
refReference
Unknown Field: ref
Davis, J.A. and Leinhardt, S. (1972). The Structure of Positive Interpersonal Relations in Small Groups. In: J. Berger (Ed.), Sociological Theories in Progress, Volume 2, 218-251. Boston: Houghton Mifflin.
def union(graph, other, byname='auto'):
Creates the union of two (or more) graphs.
Parameters
graphUndocumented
othergraph or list of graphs to be united with the current one.
bynamewhether to use vertex names instead of ids. See igraph.operators.union for details.
Returns
the union graph
def write(graph, f, format=None, *args, **kwds):

Unified writing function for graphs.

This method tries to identify the format of the graph given in the first parameter (based on extension) and calls the corresponding writer method.

The remaining arguments are passed to the writer method without any changes.

Parameters
graphUndocumented
fthe file containing the graph to be saved
format

the format of the file (if one wants to override the format determined from the filename extension, or the filename itself is a stream). None means auto-detection. Possible values are:

  • "adjacency": adjacency matrix format
  • "dimacs": DIMACS format
  • "dot", "graphviz": GraphViz DOT format
  • "edgelist", "edges" or "edge": numeric edge list format
  • "gml": GML format
  • "graphml" and "graphmlz": standard and gzipped GraphML format
  • "gw", "leda", "lgr": LEDA native format
  • "lgl": LGL format
  • "ncol": NCOL format
  • "net", "pajek": Pajek format
  • "pickle", "picklez": standard and gzipped Python pickled format
  • "svg": SVG format
*argsUndocumented
**kwdsUndocumented
Raises
IOErrorif the file format can't be identified and none was given.
def write_adjacency(graph, f, sep=' ', eol='\n', *args, **kwds):

Writes the adjacency matrix of the graph to the given file

All the remaining arguments not mentioned here are passed intact to Graph.get_adjacency.

Parameters
graphUndocumented
fthe name of the file to be written.
septhe string that separates the matrix elements in a row
eolthe string that separates the rows of the matrix. Please note that igraph is able to read back the written adjacency matrix if and only if this is a single newline character
*argsUndocumented
**kwdsUndocumented
def write_dimacs(graph, f, source=None, target=None, capacity='capacity'):
Writes the graph in DIMACS format to the given file.
Parameters
graphUndocumented
fthe name of the file to be written or a Python file handle.
sourcethe source vertex ID. If None, igraph will try to infer it from the source graph attribute.
targetthe target vertex ID. If None, igraph will try to infer it from the target graph attribute.
capacitythe capacities of the edges in a list or the name of an edge attribute that holds the capacities. If there is no such edge attribute, every edge will have a capacity of 1.
def write_graphmlz(graph, f, compresslevel=9):

Writes the graph to a zipped GraphML file.

The library uses the gzip compression algorithm, so the resulting file can be unzipped with regular gzip uncompression (like gunzip or zcat from Unix command line) or the Python gzip module.

Uses a temporary file to store intermediate GraphML data, so make sure you have enough free space to store the unzipped GraphML file as well.

Parameters
graphUndocumented
fthe name of the file to be written.
compresslevelthe level of compression. 1 is fastest and produces the least compression, and 9 is slowest and produces the most compression.
def write_pickle(graph, fname=None, version=-1):
Saves the graph in Python pickled format
Parameters
graphUndocumented
fnamethe name of the file or a stream to save to. If None, saves the graph to a string and returns the string.
versionpickle protocol version to be used. If -1, uses the highest protocol available
Returns
None if the graph was saved successfully to the given file, or a string if fname was None.
def write_picklez(graph, fname=None, version=-1):

Saves the graph in Python pickled format, compressed with gzip.

Saving in this format is a bit slower than saving in a Python pickle without compression, but the final file takes up much less space on the hard drive.

Parameters
graphUndocumented
fnamethe name of the file or a stream to save to.
versionpickle protocol version to be used. If -1, uses the highest protocol available
Returns
None if the graph was saved successfully to the given file.
def write_svg(graph, fname, layout='auto', width=None, height=None, labels='label', colors='color', shapes='shape', vertex_size=10, edge_colors='color', edge_stroke_widths='width', font_size=16, *args, **kwds):

Saves the graph as an SVG (Scalable Vector Graphics) file

The file will be Inkscape (http://inkscape.org) compatible. In Inkscape, as nodes are rearranged, the edges auto-update.

Parameters
graphUndocumented
fnamethe name of the file or a Python file handle
layoutthe layout of the graph. Can be either an explicitly specified layout (using a list of coordinate pairs) or the name of a layout algorithm (which should refer to a method in the Graph object, but without the layout_ prefix.
widththe preferred width in pixels (default: 400)
heightthe preferred height in pixels (default: 400)
labelsthe vertex labels. Either it is the name of a vertex attribute to use, or a list explicitly specifying the labels. It can also be None.
colorsthe vertex colors. Either it is the name of a vertex attribute to use, or a list explicitly specifying the colors. A color can be anything acceptable in an SVG file.
shapesthe vertex shapes. Either it is the name of a vertex attribute to use, or a list explicitly specifying the shapes as integers. Shape 0 means hidden (nothing is drawn), shape 1 is a circle, shape 2 is a rectangle and shape 3 is a rectangle that automatically sizes to the inner text.
vertex​_sizevertex size in pixels
edge​_colorsthe edge colors. Either it is the name of an edge attribute to use, or a list explicitly specifying the colors. A color can be anything acceptable in an SVG file.
edge​_stroke​_widthsthe stroke widths of the edges. Either it is the name of an edge attribute to use, or a list explicitly specifying the stroke widths. The stroke width can be anything acceptable in an SVG file.
font​_sizefont size. If it is a string, it is written into the SVG file as-is (so you can specify anything which is valid as the value of the font-size style). If it is a number, it is interpreted as pixel size and converted to the proper attribute value accordingly.
*argsUndocumented
**kwdsUndocumented
__hash__ =

Undocumented

__iter__ =

Undocumented

Formula =

Undocumented

@property
es =
The edge sequence of the graph
@property
vs =
The vertex sequence of the graph
@classmethod
def _reconstruct(cls, attrs, *args, **kwds):

Reconstructs a Graph object from Python's pickled format.

This method is for internal use only, it should not be called directly.

@property
_as_parameter_ =

Undocumented