class Graph(GraphBase):
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]
Adjacency
Generates a graph from its adjacency matrix.
Bipartite
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 ...
DataFrame
Generates a graph from one or two dataframes.
DictDict
Constructs a graph from a dict-of-dicts representation.
DictList
Constructs a graph from a list-of-dictionaries representation.
from_graph_tool
Converts the graph from graph-tool
from_networkx
Converts the graph from networkx
GRG
Generates a random geometric graph.
Incidence
Creates a bipartite graph from an incidence matrix.
ListDict
Constructs a graph from a dict-of-lists representation.
Read
Unified reading function for graphs.
Read_DIMACS
Reads a graph from a file conforming to the DIMACS minimum-cost flow file format.
Read_GraphMLz
Reads a graph from a zipped GraphML file.
Read_Pickle
Reads a graph from Python pickled format
Read_Picklez
Reads a graph from compressed Python pickled format, uncompressing it on-the-fly.
TupleList
Constructs a graph from a list-of-tuples representation.
__add__
Copies the graph and extends the copy depending on the type of the other object given.
__and__
Graph intersection operator.
__bool__
Returns True if the graph has at least one vertex, False otherwise.
__coerce__
Coercion rules.
__iadd__
In-place addition (disjoint union).
__init__
__init__(n=0, edges=None, directed=False, graph_attrs=None, vertex_attrs=None, edge_attrs=None)
__isub__
In-place subtraction (difference).
__mul__
Copies exact replicas of the original graph an arbitrary number of times.
__or__
Graph union operator.
__plot__
Plots the graph to the given Cairo context or matplotlib Axes.
__reduce__
Support for pickling.
__str__
Returns a string representation of the graph.
__sub__
Removes the given object(s) from the graph
add_edge
Adds a single edge to the graph.
add_edges
Adds some edges to the graph.
add_vertex
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.
add_vertices
Adds some vertices to the graph.
all_st_cuts
Returns all the cuts between the source and target vertices in a directed graph.
all_st_mincuts
Returns all the mincuts between the source and target vertices in a directed graph.
as_directed
Returns a directed copy of this graph. Arguments are passed on to GraphBase.to_directed() that is invoked on the copy.
as_undirected
Returns an undirected copy of this graph. Arguments are passed on to GraphBase.to_undirected() that is invoked on the copy.
biconnected_components
Calculates the biconnected components of the graph.
bipartite_projection
Projects a bipartite graph into two one-mode graphs. Edge directions are ignored while projecting.
bipartite_projection_size
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.
blocks
Calculates the biconnected components of the graph.
clear
Clears the graph, deleting all vertices, edges, and attributes.
clusters
Deprecated alias to Graph.connected_components() .
community_edge_betweenness
Community structure based on the betweenness of the edges in the network.
community_fastgreedy
Community structure based on the greedy optimization of modularity.
community_infomap
Finds the community structure of the network according to the Infomap method of Martin Rosvall and Carl T. Bergstrom.
community_label_propagation
Finds the community structure of the graph according to the label propagation method of Raghavan et al.
community_leading_eigenvector
Newman's leading eigenvector method for detecting community structure.
community_leading_eigenvector_naive
Naive implementation of Newman's eigenvector community structure detection.
community_leiden
Finds the community structure of the graph using the Leiden algorithm of Traag, van Eck & Waltman.
community_multilevel
Community structure based on the multilevel algorithm of Blondel et al.
community_optimal_modularity
Calculates the optimal modularity score of the graph and the corresponding community structure.
community_spinglass
Finds the community structure of the graph according to the spinglass community detection method of Reichardt & Bornholdt.
community_walktrap
Community detection algorithm of Latapy & Pons, based on random walks.
components
Calculates the (strong or weak) connected components for a given graph.
count_automorphisms_vf2
Returns the number of automorphisms of the graph.
degree_distribution
Calculates the degree distribution of the graph.
delete_edges
Deletes some edges from the graph.
dfs
Conducts a depth first search (DFS) on the graph.
disjoint_union
Creates the disjoint union of two (or more) graphs.
dyad_census
Calculates the dyad census of the graph.
get_adjacency
Returns the adjacency matrix of a graph.
get_adjacency_sparse
Returns the adjacency matrix of a graph as a SciPy CSR matrix.
get_adjlist
Returns the adjacency list representation of the graph.
get_all_simple_paths
Calculates all the simple paths from a given node to some other nodes (or all of them) in a graph.
get_automorphisms_vf2
Returns all the automorphisms of the graph
get_edge_dataframe
Export edges with attributes to pandas.DataFrame
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.
get_inclist
Returns the incidence list representation of the graph.
get_vertex_dataframe
Export vertices with attributes to pandas.DataFrame
gomory_hu_tree
Calculates the Gomory-Hu tree of an undirected graph with optional edge capacities.
indegree
Returns the in-degrees in a list.
intersection
Creates the intersection of two (or more) graphs.
is_named
Returns whether the graph is named.
is_weighted
Returns whether the graph is weighted.
k_core
Returns some k-cores of the graph.
layout
Returns the layout of the graph according to a layout algorithm.
layout_auto
Chooses and runs a suitable layout function based on simple topological properties of the graph.
layout_sugiyama
Places the vertices using a layered Sugiyama layout.
maxflow
Returns a maximum flow between the given source and target vertices in a graph.
maximum_bipartite_matching
Finds a maximum matching in a bipartite graph.
mincut
Calculates the minimum cut between the given source and target vertices or within the whole graph.
modularity
Calculates the modularity score of the graph with respect to a given clustering.
outdegree
Returns the out-degrees in a list.
pagerank
Calculates the PageRank values of a graph.
path_length_hist
Returns the path length histogram of the graph
shortest_paths
Deprecated alias to Graph.distances() .
spanning_tree
Calculates a minimum spanning tree for a graph.
summary
Returns the summary of the graph.
to_dict_dict
Export graph to dictionary of dicts of edge attributes
to_dict_list
Export graph as two lists of dictionaries, for vertices and edges.
to_graph_tool
Converts the graph to graph-tool
to_list_dict
Export graph to a dictionary of lists (or other sequences).
to_networkx
Converts the graph to networkx format.
to_tuple_list
Export graph to a list of edge tuples
transitivity_avglocal_undirected
Calculates the average of the vertex transitivities of the graph.
triad_census
Calculates the triad census of the graph.
union
Creates the union of two (or more) graphs.
write
Unified writing function for graphs.
write_adjacency
Writes the adjacency matrix of the graph to the given file
write_dimacs
Writes the graph in DIMACS format to the given file.
write_graphmlz
Writes the graph to a zipped GraphML file.
write_pickle
Saves the graph in Python pickled format
write_picklez
Saves the graph in Python pickled format, compressed with gzip.
write_svg
Saves the graph as an SVG (Scalable Vector Graphics) file
__hash__
Undocumented
__iter__
Undocumented
Formula
Undocumented
es
The edge sequence of the graph
vs
The vertex sequence of the graph
_reconstruct
Reconstructs a Graph object from Python's pickled format.
_as_parameter_
Undocumented
Inherited from GraphBase :
__new__
Create and return a new object. See help(type) for accurate signature.
all_minimal_st_separators
Returns a list containing all the minimal s-t separators of a graph.
are_connected
Decides whether two given vertices are directly connected.
articulation_points
Returns the list of articulation points in the graph.
assortativity
Returns the assortativity of the graph based on numeric properties of the vertices.
assortativity_degree
Returns the assortativity of a graph based on vertex degrees.
assortativity_nominal
Returns the assortativity of the graph based on vertex categories.
Asymmetric_Preference
Generates a graph based on asymmetric vertex types and connection probabilities.
Atlas
Generates a graph from the Graph Atlas.
attributes
No summary
authority_score
Calculates Kleinberg's authority score for the vertices of the graph
average_path_length
Calculates the average path length in a graph.
Barabasi
Generates a graph based on the Barabasi-Albert model.
betweenness
Calculates or estimates the betweenness of vertices in a graph.
bfs
Conducts a breadth first search (BFS) on the graph.
bfsiter
Constructs a breadth first search (BFS) iterator of the graph.
bibcoupling
Calculates bibliographic coupling scores for given vertices in a graph.
bridges
Returns the list of bridges in the graph.
canonical_permutation
Calculates the canonical permutation of a graph using the BLISS isomorphism algorithm.
chordal_completion
Returns the list of edges needed to be added to the graph to make it chordal.
clique_number
Returns the clique number of the graph.
cliques
Returns some or all cliques of the graph as a list of tuples.
closeness
Calculates the closeness centralities of given vertices in a graph.
cocitation
Calculates cocitation scores for given vertices in a graph.
cohesive_blocks
Calculates the cohesive block structure of the graph.
complementer
Returns the complementer of the graph
compose
Returns the composition of two graphs.
connected_components
Calculates the (strong or weak) connected components for a given graph.
constraint
Calculates Burt's constraint scores for given vertices in a graph.
contract_vertices
Contracts some vertices in the graph, i.e. replaces groups of vertices with single vertices. Edges are not affected.
convergence_degree
Undocumented (yet).
convergence_field_size
Undocumented (yet).
copy
Creates a copy of the graph.
coreness
Finds the coreness (shell index) of the vertices of the network.
count_isomorphisms_vf2
Determines the number of isomorphisms between the graph and another one
count_multiple
Counts the multiplicities of the given edges.
count_subisomorphisms_vf2
Determines the number of subisomorphisms between the graph and another one
De_Bruijn
Generates a de Bruijn graph with parameters (m, n)
decompose
Decomposes the graph into subgraphs.
degree
Returns some vertex degrees from the graph.
Degree_Sequence
Generates a graph with a given degree sequence.
delete_vertices
Deletes vertices and all its edges from the graph.
density
Calculates the density of the graph.
dfsiter
Constructs a depth first search (DFS) iterator of the graph.
diameter
Calculates the diameter of the graph.
difference
Subtracts the given graph from the original
distances
Calculates shortest path lengths for given vertices in a graph.
diversity
Calculates the structural diversity index of the vertices.
dominator
Returns the dominator tree from the given root node
eccentricity
Calculates the eccentricities of given vertices in a graph.
ecount
Counts the number of edges.
edge_attributes
No summary
edge_betweenness
Calculates or estimates the edge betweennesses in a graph.
edge_connectivity
Calculates the edge connectivity of the graph or between some vertices.
eigen_adjacency
Undocumented
eigenvector_centrality
Calculates the eigenvector centralities of the vertices in a graph.
Erdos_Renyi
Generates a graph based on the Erdos-Renyi model.
Establishment
Generates a graph based on a simple growing model with vertex types.
Famous
Generates a famous graph based on its name.
farthest_points
Returns two vertex IDs whose distance equals the actual diameter of the graph.
feedback_arc_set
Calculates an approximately or exactly minimal feedback arc set.
Forest_Fire
Generates a graph based on the forest fire model
Full
Generates a full graph (directed or undirected, with or without loops).
Full_Citation
Generates a full citation graph
fundamental_cycles
Finds a single fundamental cycle basis of the graph
get_all_shortest_paths
Calculates all of the shortest paths from/to a given node in a graph.
get_diameter
Returns a path with the actual diameter of the graph.
get_edgelist
Returns the edge list of a graph.
get_eid
Returns the edge ID of an arbitrary edge between vertices v1 and v2
get_eids
Returns the edge IDs of some edges between some vertices.
get_isomorphisms_vf2
Returns all isomorphisms between the graph and another one
get_shortest_paths
Calculates the shortest paths from/to a given node in a graph.
get_subisomorphisms_lad
Returns all subisomorphisms between the graph and another one using the LAD algorithm.
get_subisomorphisms_vf2
Returns all subisomorphisms between the graph and another one
girth
Returns the girth of the graph.
Growing_Random
Generates a growing random graph.
harmonic_centrality
Calculates the harmonic centralities of given vertices in a graph.
has_multiple
Checks whether the graph has multiple edges.
hub_score
Calculates Kleinberg's hub score for the vertices of the graph
incident
Returns the edges a given vertex is incident on.
independence_number
Returns the independence number of the graph.
independent_vertex_sets
Returns some or all independent vertex sets of the graph as a list of tuples.
induced_subgraph
Returns a subgraph spanned by the given vertices.
is_acyclic
Returns whether the graph is acyclic (i.e. contains no cycles).
is_bipartite
Decides whether the graph is bipartite or not.
is_chordal
Returns whether the graph is chordal or not.
is_connected
Decides whether the graph is connected.
is_dag
Checks whether the graph is a DAG (directed acyclic graph).
is_directed
Checks whether the graph is directed.
is_loop
Checks whether a specific set of edges contain loop edges
is_minimal_separator
Decides whether the given vertex set is a minimal separator.
is_multiple
Checks whether an edge is a multiple edge.
is_mutual
Checks whether an edge has an opposite pair.
is_separator
Decides whether the removal of the given vertices disconnects the graph.
is_simple
Checks whether the graph is simple (no loop or multiple edges).
is_tree
Checks whether the graph is a (directed or undirected) tree graph.
Isoclass
Generates a graph with a given isomorphism class.
isoclass
Returns the isomorphism class of the graph or its subgraph.
isomorphic
Checks whether the graph is isomorphic to another graph.
isomorphic_bliss
Checks whether the graph is isomorphic to another graph, using the BLISS isomorphism algorithm.
isomorphic_vf2
Checks whether the graph is isomorphic to another graph, using the VF2 isomorphism algorithm.
K_Regular
Generates a k-regular random graph
Kautz
Generates a Kautz graph with parameters (m, n)
knn
Calculates the average degree of the neighbors for each vertex, and the same quantity as the function of vertex degree.
laplacian
Returns the Laplacian matrix of a graph.
largest_cliques
Returns the largest cliques of the graph as a list of tuples.
largest_independent_vertex_sets
Returns the largest independent vertex sets of the graph as a list of tuples.
Lattice
Generates a regular lattice.
layout_bipartite
Place the vertices of a bipartite graph in two layers.
layout_circle
Places the vertices of the graph uniformly on a circle or a sphere.
layout_davidson_harel
Places the vertices on a 2D plane according to the Davidson-Harel layout algorithm.
layout_drl
Places the vertices on a 2D plane or in the 3D space ccording to the DrL layout algorithm.
layout_fruchterman_reingold
Places the vertices on a 2D plane according to the Fruchterman-Reingold algorithm.
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.
layout_grid
Places the vertices of a graph in a 2D or 3D grid.
layout_kamada_kawai
Places the vertices on a plane according to the Kamada-Kawai algorithm.
layout_lgl
Places the vertices on a 2D plane according to the Large Graph Layout.
layout_mds
Places the vertices in an Euclidean space with the given number of dimensions using multidimensional scaling.
layout_random
Places the vertices of the graph randomly.
layout_reingold_tilford
Places the vertices on a 2D plane according to the Reingold-Tilford layout algorithm.
layout_reingold_tilford_circular
Circular Reingold-Tilford layout for trees.
layout_star
Calculates a star-like layout for the graph.
layout_umap
No summary
LCF
Generates a graph from LCF notation.
linegraph
Returns the line graph of the graph.
list_triangles
Lists the triangles of the graph
maxdegree
Returns the maximum degree of a vertex set in the graph.
maxflow_value
Returns the value of the maximum flow between the source and target vertices.
maximal_cliques
Returns the maximal cliques of the graph as a list of tuples.
maximal_independent_vertex_sets
Returns the maximal independent vertex sets of the graph as a list of tuples.
maximum_cardinality_search
Conducts a maximum cardinality search on the graph. The function computes a rank alpha for each vertex such that visiting vertices in decreasing rank order corresponds to always choosing the vertex with the most already visited neighbors as the next one to visit.
mincut_value
Returns the minimum cut between the source and target vertices or within the whole graph.
minimum_cycle_basis
Computes a minimum cycle basis of the graph
minimum_size_separators
Returns a list containing all separator vertex sets of minimum size.
motifs_randesu
Counts the number of motifs in the graph
motifs_randesu_estimate
Counts the total number of motifs in the graph
motifs_randesu_no
Counts the total number of motifs in the graph
neighborhood
For each vertex specified by vertices, returns the vertices reachable from that vertex in at most order steps. If mindist is larger than zero, vertices that are reachable in less than mindist steps are excluded.
neighborhood_size
For each vertex specified by vertices, returns the number of vertices reachable from that vertex in at most order steps. If mindist is larger than zero, vertices that are reachable in less than mindist...
neighbors
Returns adjacent vertices to a given vertex.
permute_vertices
Permutes the vertices of the graph according to the given permutation and returns the new graph.
personalized_pagerank
Calculates the personalized PageRank values of a graph.
predecessors
Returns the predecessors of a given vertex.
Preference
Generates a graph based on vertex types and connection probabilities.
radius
Calculates the radius of the graph.
random_walk
Performs a random walk of a given length from a given node.
Read_DL
Reads an UCINET DL file and creates a graph based on it.
Read_Edgelist
Reads an edge list from a file and creates a graph based on it.
Read_GML
Reads a GML file and creates a graph based on it.
Read_GraphDB
Reads a GraphDB format file and creates a graph based on it.
Read_GraphML
Reads a GraphML format file and creates a graph based on it.
Read_Lgl
Reads an .lgl file used by LGL.
Read_Ncol
Reads an .ncol file used by LGL.
Read_Pajek
Reads a file in the Pajek format and creates a graph based on it. Only Pajek network files (.net extension) are supported, not project files (.paj).
Realize_Degree_Sequence
Generates a graph from a degree sequence.
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.
reciprocity
Reciprocity defines the proportion of mutual connections in a directed graph. It is most commonly defined as the probability that the opposite counterpart of a directed edge is also included in the graph...
reverse_edges
Reverses the direction of some edges in the graph.
rewire
Randomly rewires the graph while preserving the degree distribution.
rewire_edges
Rewires the edges of a graph with constant probability.
Ring
Generates a ring graph.
SBM
Generates a graph based on a stochastic blockmodel.
similarity_dice
Dice similarity coefficient of vertices.
similarity_inverse_log_weighted
Inverse log-weighted similarity coefficient of vertices.
similarity_jaccard
Jaccard similarity coefficient of vertices.
simplify
Simplifies a graph by removing self-loops and/or multiple edges.
st_mincut
Calculates the minimum cut between the source and target vertices in a graph.
Star
Generates a star graph.
Static_Fitness
Generates a non-growing graph with edge probabilities proportional to node fitnesses.
Static_Power_Law
Generates a non-growing graph with prescribed power-law degree distributions.
strength
Returns the strength (weighted degree) of some vertices from the graph
subcomponent
Determines the indices of vertices which are in the same component as a given vertex.
subgraph_edges
Returns a subgraph spanned by the given edges.
subisomorphic_lad
Checks whether a subgraph of the graph is isomorphic to another graph.
subisomorphic_vf2
Checks whether a subgraph of the graph is isomorphic to another graph.
successors
Returns the successors of a given vertex.
to_directed
Converts an undirected graph to directed.
to_prufer
Converts a tree graph into a Prufer sequence.
to_undirected
Converts a directed graph to undirected.
topological_sorting
Calculates a possible topological sorting of the graph.
transitivity_local_undirected
Calculates the local transitivity (clustering coefficient) of the given vertices in the graph.
transitivity_undirected
Calculates the global transitivity (clustering coefficient) of the graph.
Tree
Generates a tree in which almost all vertices have the same number of children.
Tree_Game
Generates a random tree by sampling uniformly from the set of labelled trees with a given number of nodes.
unfold_tree
Unfolds the graph using a BFS to a tree by duplicating vertices as necessary.
vcount
Counts the number of vertices.
vertex_attributes
No summary
vertex_connectivity
Calculates the vertex connectivity of the graph or between some vertices.
Watts_Strogatz
No summary
write_dot
Writes the graph in DOT format to the given file.
write_edgelist
Writes the edge list of a graph to a file.
write_gml
Writes the graph in GML format to the given file.
write_graphml
Writes the graph to a GraphML file.
write_leda
Writes the graph to a file in LEDA native format.
write_lgl
Writes the edge list of a graph to a file in .lgl format.
write_ncol
Writes the edge list of a graph to a file in .ncol format.
write_pajek
Writes the graph in Pajek format to the given file.
__graph_as_capsule
Returns the igraph graph encapsulated by the Python object as a PyCapsule
__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.
_Bipartite
Internal function, undocumented.
_Full_Bipartite
Internal function, undocumented.
_get_all_simple_paths
Internal function, undocumented.
_GRG
Internal function, undocumented.
_Incidence
Internal function, undocumented.
_is_matching
Internal function, undocumented.
_is_maximal_matching
Internal function, undocumented.
_layout_sugiyama
Internal function, undocumented.
_maximum_bipartite_matching
Internal function, undocumented.
_Random_Bipartite
Internal function, undocumented.
_raw_pointer
Returns the memory address of the igraph graph encapsulated by the Python object as an ordinary Python integer.
_spanning_tree
Internal function, undocumented.
_Weighted_Adjacency
Generates a graph from its adjacency matrix.
igraph.GraphBase.Adjacency Generates a graph from its adjacency 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).
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)
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]
Generates a graph from one or two dataframes.
bool whether the graph is directedbool whether 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.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.
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)
bool whether to create a directed graphstr Undocumenteddef 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.
bool whether the constructed graph will be directedstr the name of the distinguished key in the dicts in the vertex data source that contains the vertex names. Ignored if vertices is None.bool whether 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.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.
Converts the graph from graph-tool
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.
str attribute 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.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.
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]])ValueError if the weighted and multiple are passed together.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.
bool whether to create a directed graphstr Undocumenteda 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.
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.
IOError if the file format can't be identified and none was given.igraph.GraphBase.Read_DIMACS 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.
Reads a graph from a zipped GraphML file.
Reads a graph from Python pickled format
Reads a graph from compressed Python pickled format, uncompressing it on-the-fly.
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.
bool whether the constructed graph will be directedstr the name of the vertex attribute that will contain the vertex names.Copies the graph and extends the copy depending on the type of the other object given.
Graph , a disjoint union is performed.Graph intersection operator.
Returns True if the graph has at least one vertex, False otherwise.
Coercion rules.
This method is needed to allow the graph to react to additions with lists, tuples, integers, strings, vertices, edges and so on.
__init__(n=0, edges=None, directed=False, graph_attrs=None, vertex_attrs=None, edge_attrs=None)
Constructs a graph from scratch.
Copies exact replicas of the original graph an arbitrary number of times.
Graph union operator.
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):
- Keyword arguments of this function (or of
plot()which is passed intact to Graph.__plot__(). - Vertex or edge attributes, specified later in the list of keyword arguments.
- igraph-wide plotting defaults (see
igraph.config.Configuration) - 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
AbstractCairoGraphDrawerwhich 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 ofBoundingBox). 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 tolayoutto 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 (likeGraphBase.layout_circle) or calculate the layout in advance and pass aLayoutobject 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
VertexClusteringorVertexCover. 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
VertexClusteringorVertexCoverinstance. 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
VertexSeqinstances.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.colorsfor 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.drawingfor 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).
Support for pickling.
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.
Removes the given object(s) from the graph
Edge and EdgeSeq objects.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.
igraph.GraphBase.add_edges Adds some edges to the graph.
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.
igraph.GraphBase.add_vertices 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.
igraph.GraphBase.all_st_cuts 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.
Cut objects.igraph.GraphBase.all_st_mincuts 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.
Cut objects.Returns a directed copy of this graph. Arguments are passed on to GraphBase.to_directed() that is invoked on the copy.
Returns an undirected copy of this graph. Arguments are passed on to GraphBase.to_undirected() that is invoked on the copy.
igraph.GraphBase.biconnected_components Calculates the biconnected components of the graph.
VertexCover object describing the biconnected components, and optionally the list of articulation points as welligraph.GraphBase.bipartite_projection 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
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.
Calculates the biconnected components of the graph.
VertexCover object describing the biconnected components, and optionally the list of articulation points as wellClears the graph, deleting all vertices, edges, and attributes.
Deprecated alias to Graph.connected_components() .
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.
VertexDendrogram object, initally cut at the maximum modularity or at the desired number of clusters.igraph.GraphBase.community_fastgreedy 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.
VertexDendrogram object.igraph.GraphBase.community_infomap Finds the community structure of the network according to the Infomap method of Martin Rosvall and Carl T. Bergstrom.
VertexClustering object with an extra attribute called codelength that stores the code length determined by the algorithm.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.
Also note that the community _labels_ (numbers) have no semantic meaning and igraph is free to re-number communities. If you use fixed labels, igraph may still re-number the communities, but co-community membership constraints will be respected: if you had two vertices with fixed labels that belonged to the same community, they will still be in the same community at the end. Similarly, if you had two vertices with fixed labels that belonged to different communities, they will still be in different communities at the end.
VertexClustering object.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.
ARPACKOptions object used to fine-tune the ARPACK eigenvector calculation. If omitted, the module-level variable called arpack_options is used.VertexClustering object.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.
VertexClustering or VertexDendrogram object.igraph.GraphBase.community_leiden Finds the community structure of the graph using the Leiden algorithm of Traag, van Eck & Waltman.
VertexClustering object.igraph.GraphBase.community_multilevel 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.
VertexClustering objects, one corresponding to each level (if return_levels is True), or a VertexClustering corresponding to the best modularity.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.
igraph.GraphBase.community_spinglass Finds the community structure of the graph according to the spinglass community detection method of Reichardt & Bornholdt.
VertexClustering object.igraph.GraphBase.community_walktrap 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.
VertexDendrogram object, initially cut at the maximum modularity.Calculates the (strong or weak) connected components for a given graph.
VertexClustering objectReturns 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.
Calculates the degree distribution of the graph.
Unknown keyword arguments are directly passed to GraphBase.degree .
igraph.GraphBase.delete_edges 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.
Conducts a depth first search (DFS) on the graph.
a tuple with the following items:
- The vertex IDs visited (in order)
- The parent of every vertex in the DFS
Creates the disjoint union of two (or more) graphs.
igraph.GraphBase.dyad_census 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).
DyadCensus object.igraph.GraphBase.get_adjacency Returns the adjacency matrix of a graph.
Matrix .Returns the adjacency matrix of a graph as a SciPy CSR matrix.
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.
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.
VertexSeq object. None means all the vertices.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.
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
igraph.GraphBase.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.
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.
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)
igraph.GraphBase.gomory_hu_tree 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.
Graph object.Returns the in-degrees in a list.
See GraphBase.degree for possible arguments.
Creates the intersection of two (or more) graphs.
igraph.operators.intersection for details.Returns whether the graph is named.
A graph is named if and only if it has a "name" vertex attribute.
Returns whether the graph is weighted.
A graph is weighted if and only if it has a "weight" edge attribute.
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.
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:
- auto, automatic: automatic layout (see
Graph.layout_auto) - bipartite: bipartite layout (see
GraphBase.layout_bipartite) - circle, circular: circular layout (see
GraphBase.layout_circle) - dh, davidson_harel: Davidson-Harel layout (see
GraphBase.layout_davidson_harel) - drl: DrL layout for large graphs (see
GraphBase.layout_drl) - drl_3d: 3D DrL layout for large graphs (see
GraphBase.layout_drl) - fr, fruchterman_reingold: Fruchterman-Reingold layout (see
GraphBase.layout_fruchterman_reingold). - fr_3d, fr3d, fruchterman_reingold_3d: 3D Fruchterman- Reingold layout (see
GraphBase.layout_fruchterman_reingold). - grid: regular grid layout in 2D (see
GraphBase.layout_grid) - grid_3d: regular grid layout in 3D (see
GraphBase.layout_grid) - graphopt: the graphopt algorithm (see
GraphBase.layout_graphopt) - kk, kamada_kawai: Kamada-Kawai layout (see
GraphBase.layout_kamada_kawai) - kk_3d, kk3d, kamada_kawai_3d: 3D Kamada-Kawai layout (see
GraphBase.layout_kamada_kawai) - lgl, large, large_graph: Large Graph Layout (see
GraphBase.layout_lgl) - mds: multidimensional scaling layout (see
GraphBase.layout_mds) - random: random layout (see
GraphBase.layout_random) - random_3d: random 3D layout (see
GraphBase.layout_random) - rt, tree, reingold_tilford: Reingold-Tilford tree layout (see
GraphBase.layout_reingold_tilford) - rt_circular, reingold_tilford_circular: circular Reingold-Tilford tree layout (see
GraphBase.layout_reingold_tilford_circular) - sphere, spherical, circle_3d, circular_3d: spherical layout (see
GraphBase.layout_circle) - star: star layout (see
GraphBase.layout_star) - sugiyama: Sugiyama layout (see
Graph.layout_sugiyama)
Layout object or a list of lists containing the coordinates. If None, uses the value of the plotting.layout configuration key.Layout object.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:
- If the graph has an attribute called layout, it will be used. It may either be a
Layoutinstance, 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. - 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.
- Otherwise, if the graph is connected and has at most 100 vertices, the Kamada-Kawai layout will be used (see
GraphBase.layout_kamada_kawai()). - Otherwise, if the graph has at most 1000 vertices, the Fruchterman-Reingold layout will be used (see
GraphBase.layout_fruchterman_reingold()). - 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).
Layout object.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.
igraph.GraphBase.maxflow 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:
- For each edge, the flow (i.e. the assigned number) is not more than the capacity of the edge (see the capacity argument)
- 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.
Flow object describing the maximum flowFinds 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.
Matching .igraph.GraphBase.mincut 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.
Cut object describing the minimum cutigraph.GraphBase.modularity 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.
VertexClustering objectReturns the out-degrees in a list.
See GraphBase.degree for possible arguments.
Calculates the PageRank values of a graph.
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.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.
igraph.GraphBase.path_length_hist Returns the path length histogram of the graph
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.Deprecated alias to Graph.distances() .
Calculates a minimum spanning tree for a graph.
Graph object if return_tree is True or the IDs of the edges that constitute the spanning tree if return_tree is False.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.
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'}}}
bool whether 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.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.bool whether 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.str UndocumentedExport 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"}])
bool whether 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.bool whether 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.str UndocumentedConverts 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.
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']}
bool whether 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.callable constructor 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.str UndocumentedConverts 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.
str vertex attribute used to name vertices in the exported network. The default "_nx_name" ensures round trip conversions to/from networkx are lossless.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")]
bool whether 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.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.str UndocumentedCalculates 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.
igraph.GraphBase.triad_census Calculates the triad census of the graph.
TriadCensus object.Creates the union of two (or more) graphs.
igraph.operators.union for details.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.
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
IOError if the file format can't be identified and none was given.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 .
igraph.GraphBase.write_dimacs Writes the graph in DIMACS format to the given file.
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.
Saves the graph in Python pickled format
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.
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.
Graph object, but without the layout_ prefix.Undocumented
Undocumented
Undocumented
The edge sequence of the graph
The vertex sequence of the graph
Reconstructs a Graph object from Python's pickled format.
This method is for internal use only, it should not be called directly.
Undocumented