Title: | Network Analysis and Visualization |
---|---|
Description: | Routines for simple graphs and network analysis. It can handle large graphs very well and provides functions for generating random and regular graphs, graph visualization, centrality methods and much more. |
Authors: | Gábor Csárdi [aut] , Tamás Nepusz [aut] , Vincent Traag [aut] , Szabolcs Horvát [aut] , Fabio Zanini [aut] , Daniel Noom [aut], Kirill Müller [aut, cre] , Maëlle Salmon [ctb], Michael Antonov [ctb], Chan Zuckerberg Initiative [fnd] |
Maintainer: | Kirill Müller <[email protected]> |
License: | GPL (>= 2) |
Version: | 2.1.2 |
Built: | 2024-12-10 03:13:34 UTC |
Source: | https://github.com/igraph/rigraph |
Query and manipulate a graph as it were an adjacency matrix
## S3 method for class 'igraph' x[ i, j, ..., from, to, sparse = igraph_opt("sparsematrices"), edges = FALSE, drop = TRUE, attr = if (is_weighted(x)) "weight" else NULL ]
## S3 method for class 'igraph' x[ i, j, ..., from, to, sparse = igraph_opt("sparsematrices"), edges = FALSE, drop = TRUE, attr = if (is_weighted(x)) "weight" else NULL ]
x |
The graph. |
i |
Index. Vertex ids or names or logical vectors. See details below. |
j |
Index. Vertex ids or names or logical vectors. See details below. |
... |
Currently ignored. |
from |
A numeric or character vector giving vertex ids or
names. Together with the |
to |
A numeric or character vector giving vertex ids or
names. Together with the |
sparse |
Logical scalar, whether to return sparse matrices. |
edges |
Logical scalar, whether to return edge ids. |
drop |
Ignored. |
attr |
If not |
The single bracket indexes the (possibly weighted) adjacency matrix of the graph. Here is what you can do with it:
Check whether there is an edge between two vertices (
and
) in the graph:
graph[v, w]
A numeric scalar is returned, one if the edge exists, zero otherwise.
Extract the (sparse) adjacency matrix of the graph, or part of it:
graph[] graph[1:3,5:6] graph[c(1,3,5),]
The first variants returns the full adjacency matrix, the other two return part of it.
The from
and to
arguments can be used to check
the existence of many edges. In this case, both from
and
to
must be present and they must have the same length. They
must contain vertex ids or names. A numeric vector is returned, of
the same length as from
and to
, it contains ones
for existing edges edges and zeros for non-existing ones.
Example:
graph[from=1:3, to=c(2,3,5)]
.
For weighted graphs, the [
operator returns the edge
weights. For non-esistent edges zero weights are returned. Other
edge attributes can be queried as well, by giving the attr
argument.
Querying edge ids instead of the existance of edges or edge attributes. E.g.
graph[1, 2, edges=TRUE]
returns the id of the edge between vertices 1 and 2, or zero if there is no such edge.
Adding one or more edges to a graph. For this the element(s) of
the imaginary adjacency matrix must be set to a non-zero numeric
value (or TRUE
):
graph[1, 2] <- 1 graph[1:3,1] <- 1 graph[from=1:3, to=c(2,3,5)] <- TRUE
This does not affect edges that are already present in the graph, i.e. no multiple edges are created.
Adding weighted edges to a graph. The attr
argument
contains the name of the edge attribute to set, so it does not
have to be ‘weight’:
graph[1, 2, attr="weight"]<- 5 graph[from=1:3, to=c(2,3,5)] <- c(1,-1,4)
If an edge is already present in the network, then only its
weights or other attribute are updated. If the graph is already
weighted, then the attr="weight"
setting is implicit, and
one does not need to give it explicitly.
Deleting edges. The replacement syntax allow the deletion of
edges, by specifying FALSE
or NULL
as the
replacement value:
graph[v, w] <- FALSE
removes the edge from vertex to vertex
.
As this can be used to delete edges between two sets of vertices,
either pairwise:
graph[from=v, to=w] <- FALSE
or not:
graph[v, w] <- FALSE
if and
are vectors of edge ids or names.
‘[
’ allows logical indices and negative indices as well,
with the usual R semantics. E.g.
graph[degree(graph)==0, 1] <- 1
adds an edge from every isolate vertex to vertex one, and
G <- make_empty_graph(10) G[-1,1] <- TRUE
creates a star graph.
Of course, the indexing operators support vertex names,
so instead of a numeric vertex id a vertex can also be given to
‘[
’ and ‘[[
’.
A scalar or matrix. See details below.
Other structural queries:
[[.igraph()
,
adjacent_vertices()
,
are_adjacent()
,
ends()
,
get_edge_ids()
,
gorder()
,
gsize()
,
head_of()
,
incident()
,
incident_edges()
,
is_directed()
,
neighbors()
,
tail_of()
Query and manipulate a graph as it were an adjacency list
## S3 method for class 'igraph' x[[i, j, from, to, ..., directed = TRUE, edges = FALSE, exact = TRUE]]
## S3 method for class 'igraph' x[[i, j, from, to, ..., directed = TRUE, edges = FALSE, exact = TRUE]]
x |
The graph. |
i |
Index, integer, character or logical, see details below. |
j |
Index, integer, character or logical, see details below. |
from |
A numeric or character vector giving vertex ids or
names. Together with the |
to |
A numeric or character vector giving vertex ids or
names. Together with the |
... |
Additional arguments are not used currently. |
directed |
Logical scalar, whether to consider edge directions in directed graphs. It is ignored for undirected graphs. |
edges |
Logical scalar, whether to return edge ids. |
exact |
Ignored. |
The double bracket operator indexes the (imaginary) adjacency list of the graph. This can used for the following operations:
Querying the adjacent vertices for one or more vertices:
graph[[1:3,]] graph[[,1:3]]
The first form gives the successors, the second the predecessors or the 1:3 vertices. (For undirected graphs they are equivalent.)
Querying the incident edges for one or more vertices,
if the edges
argument is set to
TRUE
:
graph[[1:3, , edges=TRUE]] graph[[, 1:3, edges=TRUE]]
Querying the edge ids between two sets or vertices, if both indices are used. E.g.
graph[[v, w, edges=TRUE]]
gives the edge ids of all the edges that exist from vertices
to vertices
.
The alternative argument names from
and to
can be used
instead of the usual i
and j
, to make the code more
readable:
graph[[from = 1:3]] graph[[from = v, to = w, edges = TRUE]]
‘[[
’ operators allows logical indices and negative indices
as well, with the usual R semantics.
Vertex names are also supported, so instead of a numeric vertex id a
vertex can also be given to ‘[
’ and ‘[[
’.
Other structural queries:
[.igraph()
,
adjacent_vertices()
,
are_adjacent()
,
ends()
,
get_edge_ids()
,
gorder()
,
gsize()
,
head_of()
,
incident()
,
incident_edges()
,
is_directed()
,
neighbors()
,
tail_of()
igraph re-exports the %>%
operator of magrittr, because
we find it very useful. Please see the documentation in the
magrittr
package.
lhs |
Left hand side of the pipe. |
rhs |
Right hand side of the pipe. |
Result of applying the right hand side to the result of the left hand side.
make_ring(10) %>% add_edges(c(1, 6)) %>% plot()
make_ring(10) %>% add_edges(c(1, 6)) %>% plot()
Add vertices, edges or another graph to a graph
## S3 method for class 'igraph' e1 + e2
## S3 method for class 'igraph' e1 + e2
e1 |
First argument, probably an igraph graph, but see details below. |
e2 |
Second argument, see details below. |
The plus operator can be used to add vertices or edges to graph. The actual operation that is performed depends on the type of the right hand side argument.
If is is another igraph graph object and they are both
named graphs, then the union of the two graphs are calculated,
see union()
.
If it is another igraph graph object, but either of the two
are not named, then the disjoint union of
the two graphs is calculated, see disjoint_union()
.
If it is a numeric scalar, then the specified number of vertices are added to the graph.
If it is a character scalar or vector, then it is interpreted as the names of the vertices to add to the graph.
If it is an object created with the vertex()
or
vertices()
function, then new vertices are added to the
graph. This form is appropriate when one wants to add some vertex
attributes as well. The operands of the vertices()
function
specifies the number of vertices to add and their attributes as
well.
The unnamed arguments of vertices()
are concatenated and
used as the ‘name
’ vertex attribute (i.e. vertex
names), the named arguments will be added as additional vertex
attributes. Examples:
g <- g + vertex(shape="circle", color= "red") g <- g + vertex("foo", color="blue") g <- g + vertex("bar", "foobar") g <- g + vertices("bar2", "foobar2", color=1:2, shape="rectangle")
vertex()
is just an alias to vertices()
, and it is
provided for readability. The user should use it if a single vertex
is added to the graph.
If it is an object created with the edge()
or
edges()
function, then new edges will be added to the
graph. The new edges and possibly their attributes can be specified as
the arguments of the edges()
function.
The unnamed arguments of edges()
are concatenated and used
as vertex ids of the end points of the new edges. The named
arguments will be added as edge attributes.
Examples:
g <- make_empty_graph() + vertices(letters[1:10]) + vertices("foo", "bar", "bar2", "foobar2") g <- g + edge("a", "b") g <- g + edges("foo", "bar", "bar2", "foobar2") g <- g + edges(c("bar", "foo", "foobar2", "bar2"), color="red", weight=1:2)
See more examples below.
edge()
is just an alias to edges()
and it is provided
for readability. The user should use it if a single edge is added to
the graph.
If it is an object created with the path()
function, then
new edges that form a path are added. The edges and possibly their
attributes are specified as the arguments to the path()
function. The non-named arguments are concatenated and interpreted
as the vertex ids along the path. The remaining arguments are added
as edge attributes.
Examples:
g <- make_empty_graph() + vertices(letters[1:10]) g <- g + path("a", "b", "c", "d") g <- g + path("e", "f", "g", weight=1:2, color="red") g <- g + path(c("f", "c", "j", "d"), width=1:3, color="green")
It is important to note that, although the plus operator is commutative, i.e. is possible to write
graph <- "foo" + make_empty_graph()
it is not associative, e.g.
graph <- "foo" + "bar" + make_empty_graph()
results a syntax error, unless parentheses are used:
graph <- "foo" + ( "bar" + make_empty_graph() )
For clarity, we suggest to always put the graph object on the left hand side of the operator:
graph <- make_empty_graph() + "foo" + "bar"
Other functions for manipulating graph structure:
add_edges()
,
add_vertices()
,
complementer()
,
compose()
,
connect()
,
contract()
,
delete_edges()
,
delete_vertices()
,
difference()
,
difference.igraph()
,
disjoint_union()
,
edge()
,
igraph-minus
,
intersection()
,
intersection.igraph()
,
path()
,
permute()
,
rep.igraph()
,
reverse_edges()
,
simplify()
,
union()
,
union.igraph()
,
vertex()
# 10 vertices named a,b,c,... and no edges g <- make_empty_graph() + vertices(letters[1:10]) # Add edges to make it a ring g <- g + path(letters[1:10], letters[1], color = "grey") # Add some extra random edges g <- g + edges(sample(V(g), 10, replace = TRUE), color = "red") g$layout <- layout_in_circle plot(g)
# 10 vertices named a,b,c,... and no edges g <- make_empty_graph() + vertices(letters[1:10]) # Add edges to make it a ring g <- g + path(letters[1:10], letters[1], color = "grey") # Add some extra random edges g <- g + edges(sample(V(g), 10, replace = TRUE), color = "red") g$layout <- layout_in_circle plot(g)
The new edges are given as a vertex sequence, e.g. internal
numeric vertex ids, or vertex names. The first edge points from
edges[1]
to edges[2]
, the second from edges[3]
to edges[4]
, etc.
add_edges(graph, edges, ..., attr = list())
add_edges(graph, edges, ..., attr = list())
graph |
The input graph |
edges |
The edges to add, a vertex sequence with even number of vertices. |
... |
Additional arguments, they must be named, and they will be added as edge attributes, for the newly added edges. See also details below. |
attr |
A named list, its elements will be added as edge attributes, for the newly added edges. See also details below. |
If attributes are supplied, and they are not present in the graph,
their values for the original edges of the graph are set to NA
.
The graph, with the edges (and attributes) added.
Other functions for manipulating graph structure:
+.igraph()
,
add_vertices()
,
complementer()
,
compose()
,
connect()
,
contract()
,
delete_edges()
,
delete_vertices()
,
difference()
,
difference.igraph()
,
disjoint_union()
,
edge()
,
igraph-minus
,
intersection()
,
intersection.igraph()
,
path()
,
permute()
,
rep.igraph()
,
reverse_edges()
,
simplify()
,
union()
,
union.igraph()
,
vertex()
g <- make_empty_graph(n = 5) %>% add_edges(c( 1, 2, 2, 3, 3, 4, 4, 5 )) %>% set_edge_attr("color", value = "red") %>% add_edges(c(5, 1), color = "green") E(g)[[]] plot(g)
g <- make_empty_graph(n = 5) %>% add_edges(c( 1, 2, 2, 3, 3, 4, 4, 5 )) %>% set_edge_attr("color", value = "red") %>% add_edges(c(5, 1), color = "green") E(g)[[]] plot(g)
Add layout to graph
add_layout_(graph, ..., overwrite = TRUE)
add_layout_(graph, ..., overwrite = TRUE)
graph |
The input graph. |
... |
Additional arguments are passed to |
overwrite |
Whether to overwrite the layout of the graph, if it already has one. |
The input graph, with the layout added.
layout_()
for a description of the layout API.
Other graph layouts:
component_wise()
,
layout_()
,
layout_as_bipartite()
,
layout_as_star()
,
layout_as_tree()
,
layout_in_circle()
,
layout_nicely()
,
layout_on_grid()
,
layout_on_sphere()
,
layout_randomly()
,
layout_with_dh()
,
layout_with_fr()
,
layout_with_gem()
,
layout_with_graphopt()
,
layout_with_kk()
,
layout_with_lgl()
,
layout_with_mds()
,
layout_with_sugiyama()
,
merge_coords()
,
norm_coords()
,
normalize()
(make_star(11) + make_star(11)) %>% add_layout_(as_star(), component_wise()) %>% plot()
(make_star(11) + make_star(11)) %>% add_layout_(as_star(), component_wise()) %>% plot()
If attributes are supplied, and they are not present in the graph,
their values for the original vertices of the graph are set to
NA
.
add_vertices(graph, nv, ..., attr = list())
add_vertices(graph, nv, ..., attr = list())
graph |
The input graph. |
nv |
The number of vertices to add. |
... |
Additional arguments, they must be named, and they will be added as vertex attributes, for the newly added vertices. See also details below. |
attr |
A named list, its elements will be added as vertex attributes, for the newly added vertices. See also details below. |
The graph, with the vertices (and attributes) added.
Other functions for manipulating graph structure:
+.igraph()
,
add_edges()
,
complementer()
,
compose()
,
connect()
,
contract()
,
delete_edges()
,
delete_vertices()
,
difference()
,
difference.igraph()
,
disjoint_union()
,
edge()
,
igraph-minus
,
intersection()
,
intersection.igraph()
,
path()
,
permute()
,
rep.igraph()
,
reverse_edges()
,
simplify()
,
union()
,
union.igraph()
,
vertex()
g <- make_empty_graph() %>% add_vertices(3, color = "red") %>% add_vertices(2, color = "green") %>% add_edges(c( 1, 2, 2, 3, 3, 4, 4, 5 )) g V(g)[[]] plot(g)
g <- make_empty_graph() %>% add_vertices(3, color = "red") %>% add_vertices(2, color = "green") %>% add_edges(c( 1, 2, 2, 3, 3, 4, 4, 5 )) g V(g)[[]] plot(g)
This function is similar to neighbors()
, but it queries
the adjacent vertices for multiple vertices at once.
adjacent_vertices(graph, v, mode = c("out", "in", "all", "total"))
adjacent_vertices(graph, v, mode = c("out", "in", "all", "total"))
graph |
Input graph. |
v |
The vertices to query. |
mode |
Whether to query outgoing (‘out’), incoming (‘in’) edges, or both types (‘all’). This is ignored for undirected graphs. |
A list of vertex sequences.
Other structural queries:
[.igraph()
,
[[.igraph()
,
are_adjacent()
,
ends()
,
get_edge_ids()
,
gorder()
,
gsize()
,
head_of()
,
incident()
,
incident_edges()
,
is_directed()
,
neighbors()
,
tail_of()
g <- make_graph("Zachary") adjacent_vertices(g, c(1, 34))
g <- make_graph("Zachary") adjacent_vertices(g, c(1, 34))
This function lists all simple paths from one source vertex to another vertex or vertices. A path is simple if contains no repeated vertices.
all_simple_paths( graph, from, to = V(graph), mode = c("out", "in", "all", "total"), cutoff = -1 )
all_simple_paths( graph, from, to = V(graph), mode = c("out", "in", "all", "total"), cutoff = -1 )
graph |
The input graph. |
from |
The source vertex. |
to |
The target vertex of vertices. Defaults to all vertices. |
mode |
Character constant, gives whether the shortest paths to or
from the given vertices should be calculated for directed graphs. If
|
cutoff |
Maximum length of the paths that are considered. If negative, no cutoff is used. |
Note that potentially there are exponentially many paths between two vertices of a graph, and you may run out of memory when using this function, if your graph is lattice-like.
This function ignores multiple and loop edges.
A list of integer vectors, each integer vector is a path from the source vertex to one of the target vertices. A path is given by its vertex ids.
Other paths:
diameter()
,
distance_table()
,
eccentricity()
,
graph_center()
,
radius()
g <- make_ring(10) all_simple_paths(g, 1, 5) all_simple_paths(g, 1, c(3, 5))
g <- make_ring(10) all_simple_paths(g, 1, 5) all_simple_paths(g, 1, c(3, 5))
alpha_centrality()
calculates the alpha centrality of some (or all)
vertices in a graph.
alpha_centrality( graph, nodes = V(graph), alpha = 1, loops = FALSE, exo = 1, weights = NULL, tol = 1e-07, sparse = TRUE )
alpha_centrality( graph, nodes = V(graph), alpha = 1, loops = FALSE, exo = 1, weights = NULL, tol = 1e-07, sparse = TRUE )
graph |
The input graph, can be directed or undirected. In undirected graphs, edges are treated as if they were reciprocal directed ones. |
nodes |
Vertex sequence, the vertices for which the alpha centrality values are returned. (For technical reasons they will be calculated for all vertices, anyway.) |
alpha |
Parameter specifying the relative importance of endogenous versus exogenous factors in the determination of centrality. See details below. |
loops |
Whether to eliminate loop edges from the graph before the calculation. |
exo |
The exogenous factors, in most cases this is either a constant – the same factor for every node, or a vector giving the factor for every vertex. Note that too long vectors will be truncated and too short vectors will be replicated to match the number of vertices. |
weights |
A character scalar that gives the name of the edge attribute
to use in the adjacency matrix. If it is |
tol |
Tolerance for near-singularities during matrix inversion, see
|
sparse |
Logical scalar, whether to use sparse matrices for the calculation. The ‘Matrix’ package is required for sparse matrix support |
The alpha centrality measure can be considered as a generalization of eigenvector centrality to directed graphs. It was proposed by Bonacich in 2001 (see reference below).
The alpha centrality of the vertices in a graph is defined as the solution of the following matrix equation:
where is the (not necessarily symmetric) adjacency matrix of the
graph,
is the vector of exogenous sources of status of the
vertices and
is the relative importance of the
endogenous versus exogenous factors.
A numeric vector contaning the centrality scores for the selected vertices.
Singular adjacency matrices cause problems for this algorithm, the routine may fail is certain cases.
Gabor Csardi [email protected]
Bonacich, P. and Lloyd, P. (2001). “Eigenvector-like measures of centrality for asymmetric relations” Social Networks, 23, 191-201.
eigen_centrality()
and power_centrality()
Centrality measures
authority_score()
,
betweenness()
,
closeness()
,
diversity()
,
eigen_centrality()
,
harmonic_centrality()
,
hits_scores()
,
page_rank()
,
power_centrality()
,
spectrum()
,
strength()
,
subgraph_centrality()
# The examples from Bonacich's paper g.1 <- make_graph(c(1, 3, 2, 3, 3, 4, 4, 5)) g.2 <- make_graph(c(2, 1, 3, 1, 4, 1, 5, 1)) g.3 <- make_graph(c(1, 2, 2, 3, 3, 4, 4, 1, 5, 1)) alpha_centrality(g.1) alpha_centrality(g.2) alpha_centrality(g.3, alpha = 0.5)
# The examples from Bonacich's paper g.1 <- make_graph(c(1, 3, 2, 3, 3, 4, 4, 5)) g.2 <- make_graph(c(2, 1, 3, 1, 4, 1, 5, 1)) g.3 <- make_graph(c(1, 2, 2, 3, 3, 4, 4, 1, 5, 1)) alpha_centrality(g.1) alpha_centrality(g.2) alpha_centrality(g.3, alpha = 0.5)
The order of the vertices only matters in directed graphs,
where the existence of a directed (v1, v2)
edge is queried.
are_adjacent(graph, v1, v2)
are_adjacent(graph, v1, v2)
graph |
The graph. |
v1 |
The first vertex, tail in directed graphs. |
v2 |
The second vertex, head in directed graphs. |
A logical scalar, TRUE
if edge (v1, v2)
exists in the graph.
Other structural queries:
[.igraph()
,
[[.igraph()
,
adjacent_vertices()
,
ends()
,
get_edge_ids()
,
gorder()
,
gsize()
,
head_of()
,
incident()
,
incident_edges()
,
is_directed()
,
neighbors()
,
tail_of()
ug <- make_ring(10) ug are_adjacent(ug, 1, 2) are_adjacent(ug, 2, 1) dg <- make_ring(10, directed = TRUE) dg are_adjacent(ug, 1, 2) are_adjacent(ug, 2, 1)
ug <- make_ring(10) ug are_adjacent(ug, 1, 2) are_adjacent(ug, 2, 1) dg <- make_ring(10, directed = TRUE) dg are_adjacent(ug, 1, 2) are_adjacent(ug, 2, 1)
Interface to the ARPACK library for calculating eigenvectors of sparse matrices
arpack_defaults() arpack( func, extra = NULL, sym = FALSE, options = arpack_defaults(), env = parent.frame(), complex = !sym )
arpack_defaults() arpack( func, extra = NULL, sym = FALSE, options = arpack_defaults(), env = parent.frame(), complex = !sym )
func |
The function to perform the matrix-vector multiplication. ARPACK
requires to perform these by the user. The function gets the vector |
extra |
Extra argument to supply to |
sym |
Logical scalar, whether the input matrix is symmetric. Always
supply |
options |
Options to ARPACK, a named list to overwrite some of the default option values. See details below. |
env |
The environment in which |
complex |
Whether to convert the eigenvectors returned by ARPACK into R
complex vectors. By default this is not done for symmetric problems (these
only have real eigenvectors/values), but only non-symmetric ones. If you
have a non-symmetric problem, but you're sure that the results will be real,
then supply |
ARPACK is a library for solving large scale eigenvalue problems. The
package is designed to compute a few eigenvalues and corresponding
eigenvectors of a general by
matrix
. It is most
appropriate for large sparse or structured matrices
where structured
means that a matrix-vector product
w <- Av
requires order
rather than the usual order
floating point operations.
This function is an interface to ARPACK. igraph does not contain all ARPACK routines, only the ones dealing with symmetric and non-symmetric eigenvalue problems using double precision real numbers.
The eigenvalue calculation in ARPACK (in the simplest case) involves the
calculation of the product where
is the matrix we work with
and
is an arbitrary vector. The function supplied in the
fun
argument is expected to perform this product. If the product can be done
efficiently, e.g. if the matrix is sparse, then arpack()
is usually
able to calculate the eigenvalues very quickly.
The options
argument specifies what kind of calculation to perform.
It is a list with the following members, they correspond directly to ARPACK
parameters. On input it has the following fields:
Character constant, possible values: ‘I
’, standard
eigenvalue problem, ; and ‘
G
’,
generalized eigenvalue problem, .
Currently only ‘
I
’ is supported.
Numeric scalar. The
dimension of the eigenproblem. You only need to set this if you call
arpack()
directly. (I.e. not needed for
eigen_centrality()
, page_rank()
, etc.)
Specify which eigenvalues/vectors to compute, character constant with exactly two characters.
Possible values for symmetric input matrices:
Compute nev
largest (algebraic) eigenvalues.
Compute nev
smallest (algebraic)
eigenvalues.
Compute nev
largest (in
magnitude) eigenvalues.
Compute nev
smallest
(in magnitude) eigenvalues.
Compute nev
eigenvalues, half from each end of the spectrum. When nev
is odd,
compute one more from the high end than from the low end.
Possible values for non-symmetric input matrices:
Compute nev
eigenvalues of largest
magnitude.
Compute nev
eigenvalues of
smallest magnitude.
Compute nev
eigenvalues
of largest real part.
Compute nev
eigenvalues of smallest real part.
Compute
nev
eigenvalues of largest imaginary part.
Compute nev
eigenvalues of smallest imaginary
part.
This parameter is sometimes overwritten by the various functions, e.g.
page_rank()
always sets ‘LM
’.
Numeric scalar. The number of eigenvalues to be computed.
Numeric scalar. Stopping criterion: the relative accuracy of the
Ritz value is considered acceptable if its error is less than tol
times its estimated value. If this is set to zero then machine precision is
used.
Number of Lanczos vectors to be generated.
Numberic scalar. It should be set to zero in the current implementation.
Either zero or one. If zero then the shifts
are provided by the user via reverse communication. If one then exact shifts
with respect to the reduced tridiagonal matrix . Please always set
this to one.
Maximum number of Arnoldi update iterations allowed.
Blocksize to be used in the recurrence. Please always leave this on the default value, one.
The type of the eigenproblem to be solved. Possible values if the input matrix is symmetric:
,
is
symmetric.
,
is
symmetric,
is symmetric positive definite.
,
is symmetric,
is symmetric positive
semi-definite.
,
is
symmetric positive semi-definite,
is symmetric indefinite.
,
is symmetric,
is symmetric positive semi-definite. (Cayley transformed mode.)
Please
note that only mode==1
was tested and other values might not work
properly.
Possible values if the input matrix is not symmetric:
.
,
is symmetric positive definite.
,
is symmetric
semi-definite.
,
is
symmetric semi-definite.
Please note that only mode==1
was tested
and other values might not work properly.
Not used currently. Later it be used to set a starting vector.
Not used currently.
Not use currently.
On output the following additional fields are added:
Error flag of ARPACK. Possible values:
Normal exit.
Maximum number of iterations taken.
No shifts could be applied during a cycle of the Implicitly
restarted Arnoldi iteration. One possibility is to increase the size of
ncv
relative to nev
.
ARPACK can return more error conditions than these, but they are converted to regular igraph errors.
Number of Arnoldi iterations taken.
Number of “converged” Ritz values. This represents the number of Ritz values that satisfy the convergence critetion.
Total number of matrix-vector multiplications.
Not used currently.
Total number of steps of re-orthogonalization.
Please see the ARPACK documentation for additional details.
A named list with the following members:
values |
Numeric vector, the desired eigenvalues. |
vectors |
Numeric matrix, the desired
eigenvectors as columns. If |
options |
A named
list with the supplied |
Rich Lehoucq, Kristi Maschhoff, Danny Sorensen, Chao Yang for ARPACK, Gabor Csardi [email protected] for the R interface.
D.C. Sorensen, Implicit Application of Polynomial Filters in a k-Step Arnoldi Method. SIAM J. Matr. Anal. Apps., 13 (1992), pp 357-385.
R.B. Lehoucq, Analysis and Implementation of an Implicitly Restarted Arnoldi Iteration. Rice University Technical Report TR95-13, Department of Computational and Applied Mathematics.
B.N. Parlett & Y. Saad, Complex Shift and Invert Strategies for Real Matrices. Linear Algebra and its Applications, vol 88/89, pp 575-595, (1987).
eigen_centrality()
, page_rank()
,
hub_score()
, cluster_leading_eigen()
are some of the
functions in igraph that use ARPACK.
# Identity matrix f <- function(x, extra = NULL) x arpack(f, options = list(n = 10, nev = 2, ncv = 4), sym = TRUE) # Graph laplacian of a star graph (undirected), n>=2 # Note that this is a linear operation f <- function(x, extra = NULL) { y <- x y[1] <- (length(x) - 1) * x[1] - sum(x[-1]) for (i in 2:length(x)) { y[i] <- x[i] - x[1] } y } arpack(f, options = list(n = 10, nev = 1, ncv = 3), sym = TRUE) # double check eigen(laplacian_matrix(make_star(10, mode = "undirected"))) ## First three eigenvalues of the adjacency matrix of a graph ## We need the 'Matrix' package for this if (require(Matrix)) { set.seed(42) g <- sample_gnp(1000, 5 / 1000) M <- as_adjacency_matrix(g, sparse = TRUE) f2 <- function(x, extra = NULL) { cat(".") as.vector(M %*% x) } baev <- arpack(f2, sym = TRUE, options = list( n = vcount(g), nev = 3, ncv = 8, which = "LM", maxiter = 2000 )) }
# Identity matrix f <- function(x, extra = NULL) x arpack(f, options = list(n = 10, nev = 2, ncv = 4), sym = TRUE) # Graph laplacian of a star graph (undirected), n>=2 # Note that this is a linear operation f <- function(x, extra = NULL) { y <- x y[1] <- (length(x) - 1) * x[1] - sum(x[-1]) for (i in 2:length(x)) { y[i] <- x[i] - x[1] } y } arpack(f, options = list(n = 10, nev = 1, ncv = 3), sym = TRUE) # double check eigen(laplacian_matrix(make_star(10, mode = "undirected"))) ## First three eigenvalues of the adjacency matrix of a graph ## We need the 'Matrix' package for this if (require(Matrix)) { set.seed(42) g <- sample_gnp(1000, 5 / 1000) M <- as_adjacency_matrix(g, sparse = TRUE) f2 <- function(x, extra = NULL) { cat(".") as.vector(M %*% x) } baev <- arpack(f2, sym = TRUE, options = list( n = vcount(g), nev = 3, ncv = 8, which = "LM", maxiter = 2000 )) }
articulation_points()
finds the articulation points (or cut vertices)
articulation_points(graph) bridges(graph)
articulation_points(graph) bridges(graph)
graph |
The input graph. It is treated as an undirected graph, even if it is directed. |
Articulation points or cut vertices are vertices whose removal increases the number of connected components in a graph. Similarly, bridges or cut-edges are edges whose removal increases the number of connected components in a graph. If the original graph was connected, then the removal of a single articulation point or a single bridge makes it disconnected. If a graph contains no articulation points, then its vertex connectivity is at least two.
For articulation_points()
, a numeric vector giving the vertex
IDs of the articulation points of the input graph. For bridges()
, a
numeric vector giving the edge IDs of the bridges of the input graph.
igraph_articulation_points()
, igraph_bridges()
.
Gabor Csardi [email protected]
biconnected_components()
, components()
,
is_connected()
, vertex_connectivity()
,
edge_connectivity()
Connected components
biconnected_components()
,
component_distribution()
,
decompose()
,
is_biconnected()
g <- disjoint_union(make_full_graph(5), make_full_graph(5)) clu <- components(g)$membership g <- add_edges(g, c(match(1, clu), match(2, clu))) articulation_points(g) g <- make_graph("krackhardt_kite") bridges(g)
g <- disjoint_union(make_full_graph(5), make_full_graph(5)) clu <- components(g)$membership g <- add_edges(g, c(match(1, clu), match(2, clu))) articulation_points(g) g <- make_graph("krackhardt_kite") bridges(g)
Create adjacency lists from a graph, either for adjacent edges or for neighboring vertices
as_adj_list( graph, mode = c("all", "out", "in", "total"), loops = c("twice", "once", "ignore"), multiple = TRUE ) as_adj_edge_list( graph, mode = c("all", "out", "in", "total"), loops = c("twice", "once", "ignore") )
as_adj_list( graph, mode = c("all", "out", "in", "total"), loops = c("twice", "once", "ignore"), multiple = TRUE ) as_adj_edge_list( graph, mode = c("all", "out", "in", "total"), loops = c("twice", "once", "ignore") )
graph |
The input graph. |
mode |
Character scalar, it gives what kind of adjacent edges/vertices
to include in the lists. ‘ |
loops |
Character scalar, one of |
multiple |
Logical scalar, set to |
as_adj_list()
returns a list of numeric vectors, which include the ids
of neighbor vertices (according to the mode
argument) of all
vertices.
as_adj_edge_list()
returns a list of numeric vectors, which include the
ids of adjacent edges (according to the mode
argument) of all
vertices.
If igraph_opt("return.vs.es")
is true (default), the numeric
vectors of the adjacency lists are coerced to igraph.vs
, this can be
a very expensive operation on large graphs.
A list of igraph.vs
or a list of numeric vectors depending on
the value of igraph_opt("return.vs.es")
, see details for performance
characteristics.
Gabor Csardi [email protected]
as_edgelist()
, as_adjacency_matrix()
Other conversion:
as.matrix.igraph()
,
as_adjacency_matrix()
,
as_biadjacency_matrix()
,
as_data_frame()
,
as_directed()
,
as_edgelist()
,
as_graphnel()
,
as_long_data_frame()
,
graph_from_adj_list()
,
graph_from_graphnel()
g <- make_ring(10) as_adj_list(g) as_adj_edge_list(g)
g <- make_ring(10) as_adj_list(g) as_adj_edge_list(g)
Sometimes it is useful to work with a standard representation of a graph, like an adjacency matrix.
as_adjacency_matrix( graph, type = c("both", "upper", "lower"), attr = NULL, edges = deprecated(), names = TRUE, sparse = igraph_opt("sparsematrices") )
as_adjacency_matrix( graph, type = c("both", "upper", "lower"), attr = NULL, edges = deprecated(), names = TRUE, sparse = igraph_opt("sparsematrices") )
as_adjacency_matrix()
returns the adjacency matrix of a graph, a
regular matrix if sparse
is FALSE
, or a sparse matrix, as
defined in the ‘Matrix
’ package, if sparse
if
TRUE
.
A vcount(graph)
by vcount(graph)
(usually) numeric
matrix.
graph_from_adjacency_matrix()
, read_graph()
Other conversion:
as.matrix.igraph()
,
as_adj_list()
,
as_biadjacency_matrix()
,
as_data_frame()
,
as_directed()
,
as_edgelist()
,
as_graphnel()
,
as_long_data_frame()
,
graph_from_adj_list()
,
graph_from_graphnel()
g <- sample_gnp(10, 2 / 10) as_adjacency_matrix(g) V(g)$name <- letters[1:vcount(g)] as_adjacency_matrix(g) E(g)$weight <- runif(ecount(g)) as_adjacency_matrix(g, attr = "weight")
g <- sample_gnp(10, 2 / 10) as_adjacency_matrix(g) V(g)$name <- letters[1:vcount(g)] as_adjacency_matrix(g) E(g)$weight <- runif(ecount(g)) as_adjacency_matrix(g, attr = "weight")
This function can return a sparse or dense bipartite adjacency matrix of a bipartite
network. The bipartite adjacency matrix is an times
matrix,
and
are the number of vertices of the two kinds.
as_biadjacency_matrix( graph, types = NULL, attr = NULL, names = TRUE, sparse = FALSE )
as_biadjacency_matrix( graph, types = NULL, attr = NULL, names = TRUE, sparse = FALSE )
graph |
The input graph. The direction of the edges is ignored in directed graphs. |
types |
An optional vertex type vector to use instead of the
|
attr |
Either |
names |
Logical scalar, if |
sparse |
Logical scalar, if it is |
Bipartite graphs have a type
vertex attribute in igraph, this is
boolean and FALSE
for the vertices of the first kind and TRUE
for vertices of the second kind.
Some authors refer to the bipartite adjacency matrix as the "bipartite incidence matrix". igraph 1.6.0 and later does not use this naming to avoid confusion with the edge-vertex incidence matrix.
A sparse or dense matrix.
Gabor Csardi [email protected]
graph_from_biadjacency_matrix()
for the opposite operation.
Other conversion:
as.matrix.igraph()
,
as_adj_list()
,
as_adjacency_matrix()
,
as_data_frame()
,
as_directed()
,
as_edgelist()
,
as_graphnel()
,
as_long_data_frame()
,
graph_from_adj_list()
,
graph_from_graphnel()
g <- make_bipartite_graph(c(0, 1, 0, 1, 0, 0), c(1, 2, 2, 3, 3, 4)) as_biadjacency_matrix(g)
g <- make_bipartite_graph(c(0, 1, 0, 1, 0, 0), c(1, 2, 2, 3, 3, 4)) as_biadjacency_matrix(g)
This function creates an igraph graph from one or two data frames containing the (symbolic) edge list and edge/vertex attributes.
as_data_frame(x, what = c("edges", "vertices", "both")) graph_from_data_frame(d, directed = TRUE, vertices = NULL) from_data_frame(...)
as_data_frame(x, what = c("edges", "vertices", "both")) graph_from_data_frame(d, directed = TRUE, vertices = NULL) from_data_frame(...)
x |
An igraph object. |
what |
Character constant, whether to return info about vertices, edges, or both. The default is ‘edges’. |
d |
A data frame containing a symbolic edge list in the first two
columns. Additional columns are considered as edge attributes. Since
version 0.7 this argument is coerced to a data frame with
|
directed |
Logical scalar, whether or not to create a directed graph. |
vertices |
A data frame with vertex metadata, or |
... |
Passed to |
graph_from_data_frame()
creates igraph graphs from one or two data frames.
It has two modes of operation, depending whether the vertices
argument is NULL
or not.
If vertices
is NULL
, then the first two columns of d
are used as a symbolic edge list and additional columns as edge attributes.
The names of the attributes are taken from the names of the columns.
If vertices
is not NULL
, then it must be a data frame giving
vertex metadata. The first column of vertices
is assumed to contain
symbolic vertex names, this will be added to the graphs as the
‘name
’ vertex attribute. Other columns will be added as
additional vertex attributes. If vertices
is not NULL
then the
symbolic edge list given in d
is checked to contain only vertex names
listed in vertices
.
Typically, the data frames are exported from some spreadsheet software like
Excel and are imported into R via read.table()
,
read.delim()
or read.csv()
.
All edges in the data frame are included in the graph, which may include multiple parallel edges and loops.
as_data_frame()
converts the igraph graph into one or more data
frames, depending on the what
argument.
If the what
argument is edges
(the default), then the edges of
the graph and also the edge attributes are returned. The edges will be in
the first two columns, named from
and to
. (This also denotes
edge direction for directed graphs.) For named graphs, the vertex names
will be included in these columns, for other graphs, the numeric vertex ids.
The edge attributes will be in the other columns. It is not a good idea to
have an edge attribute named from
or to
, because then the
column named in the data frame will not be unique. The edges are listed in
the order of their numeric ids.
If the what
argument is vertices
, then vertex attributes are
returned. Vertices are listed in the order of their numeric vertex ids.
If the what
argument is both
, then both vertex and edge data
is returned, in a list with named entries vertices
and edges
.
An igraph graph object for graph_from_data_frame()
, and either a
data frame or a list of two data frames named edges
and
vertices
for as.data.frame
.
For graph_from_data_frame()
NA
elements in the first two
columns ‘d’ are replaced by the string “NA” before creating
the graph. This means that all NA
s will correspond to a single
vertex.
NA
elements in the first column of ‘vertices’ are also
replaced by the string “NA”, but the rest of ‘vertices’ is not
touched. In other words, vertex names (=the first column) cannot be
NA
, but other vertex attributes can.
Gabor Csardi [email protected]
graph_from_literal()
for another way to create graphs, read.table()
to read in tables
from files.
Other conversion:
as.matrix.igraph()
,
as_adj_list()
,
as_adjacency_matrix()
,
as_biadjacency_matrix()
,
as_directed()
,
as_edgelist()
,
as_graphnel()
,
as_long_data_frame()
,
graph_from_adj_list()
,
graph_from_graphnel()
Other biadjacency:
graph_from_biadjacency_matrix()
## A simple example with a couple of actors ## The typical case is that these tables are read in from files.... actors <- data.frame( name = c( "Alice", "Bob", "Cecil", "David", "Esmeralda" ), age = c(48, 33, 45, 34, 21), gender = c("F", "M", "F", "M", "F") ) relations <- data.frame( from = c( "Bob", "Cecil", "Cecil", "David", "David", "Esmeralda" ), to = c("Alice", "Bob", "Alice", "Alice", "Bob", "Alice"), same.dept = c(FALSE, FALSE, TRUE, FALSE, FALSE, TRUE), friendship = c(4, 5, 5, 2, 1, 1), advice = c(4, 5, 5, 4, 2, 3) ) g <- graph_from_data_frame(relations, directed = TRUE, vertices = actors) print(g, e = TRUE, v = TRUE) ## The opposite operation as_data_frame(g, what = "vertices") as_data_frame(g, what = "edges")
## A simple example with a couple of actors ## The typical case is that these tables are read in from files.... actors <- data.frame( name = c( "Alice", "Bob", "Cecil", "David", "Esmeralda" ), age = c(48, 33, 45, 34, 21), gender = c("F", "M", "F", "M", "F") ) relations <- data.frame( from = c( "Bob", "Cecil", "Cecil", "David", "David", "Esmeralda" ), to = c("Alice", "Bob", "Alice", "Alice", "Bob", "Alice"), same.dept = c(FALSE, FALSE, TRUE, FALSE, FALSE, TRUE), friendship = c(4, 5, 5, 2, 1, 1), advice = c(4, 5, 5, 4, 2, 3) ) g <- graph_from_data_frame(relations, directed = TRUE, vertices = actors) print(g, e = TRUE, v = TRUE) ## The opposite operation as_data_frame(g, what = "vertices") as_data_frame(g, what = "edges")
as_directed()
converts an undirected graph to directed,
as_undirected()
does the opposite, it converts a directed graph to
undirected.
as_directed(graph, mode = c("mutual", "arbitrary", "random", "acyclic")) as_undirected( graph, mode = c("collapse", "each", "mutual"), edge.attr.comb = igraph_opt("edge.attr.comb") )
as_directed(graph, mode = c("mutual", "arbitrary", "random", "acyclic")) as_undirected( graph, mode = c("collapse", "each", "mutual"), edge.attr.comb = igraph_opt("edge.attr.comb") )
graph |
The graph to convert. |
mode |
Character constant, defines the conversion algorithm. For
|
edge.attr.comb |
Specifies what to do with edge attributes, if
|
Conversion algorithms for as_directed()
:
The number of edges in the graph stays the same, an arbitrarily directed edge is created for each undirected edge, but the direction of the edge is deterministic (i.e. it always points the same way if you call the function multiple times).
Two directed edges are created for each undirected edge, one in each direction.
The number of edges in the graph stays the same, and a randomly directed edge is created for each undirected edge. You will get different results if you call the function multiple times with the same graph.
The number of edges in the graph stays the same, and a directed edge is created for each undirected edge such that the resulting graph is guaranteed to be acyclic. This is achieved by ensuring that edges always point from a lower index vertex to a higher index. Note that the graph may include cycles of length 1 if the original graph contained loop edges.
Conversion algorithms for as_undirected()
:
The number of edges remains constant, an undirected edge is created for each directed one, this version might create graphs with multiple edges.
One undirected edge will be created for each pair of vertices which are connected with at least one directed edge, no multiple edges will be created.
One undirected edge will be created for each pair of mutual edges. Non-mutual edges are ignored. This mode might create multiple edges if there are more than one mutual edge pairs between the same pair of vertices.
A new graph object.
Gabor Csardi [email protected]
simplify()
for removing multiple and/or loop edges from
a graph.
Other conversion:
as.matrix.igraph()
,
as_adj_list()
,
as_adjacency_matrix()
,
as_biadjacency_matrix()
,
as_data_frame()
,
as_edgelist()
,
as_graphnel()
,
as_long_data_frame()
,
graph_from_adj_list()
,
graph_from_graphnel()
g <- make_ring(10) as_directed(g, "mutual") g2 <- make_star(10) as_undirected(g) # Combining edge attributes g3 <- make_ring(10, directed = TRUE, mutual = TRUE) E(g3)$weight <- seq_len(ecount(g3)) ug3 <- as_undirected(g3) print(ug3, e = TRUE) x11(width = 10, height = 5) layout(rbind(1:2)) plot(g3, layout = layout_in_circle, edge.label = E(g3)$weight) plot(ug3, layout = layout_in_circle, edge.label = E(ug3)$weight) g4 <- make_graph(c( 1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 4, 6, 7, 7, 6, 7, 8, 7, 8, 8, 7, 8, 9, 8, 9, 9, 8, 9, 8, 9, 9, 10, 10, 10, 10 )) E(g4)$weight <- seq_len(ecount(g4)) ug4 <- as_undirected(g4, mode = "mutual", edge.attr.comb = list(weight = length) ) print(ug4, e = TRUE)
g <- make_ring(10) as_directed(g, "mutual") g2 <- make_star(10) as_undirected(g) # Combining edge attributes g3 <- make_ring(10, directed = TRUE, mutual = TRUE) E(g3)$weight <- seq_len(ecount(g3)) ug3 <- as_undirected(g3) print(ug3, e = TRUE) x11(width = 10, height = 5) layout(rbind(1:2)) plot(g3, layout = layout_in_circle, edge.label = E(g3)$weight) plot(ug3, layout = layout_in_circle, edge.label = E(ug3)$weight) g4 <- make_graph(c( 1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 4, 6, 7, 7, 6, 7, 8, 7, 8, 8, 7, 8, 9, 8, 9, 9, 8, 9, 8, 9, 9, 10, 10, 10, 10 )) E(g4)$weight <- seq_len(ecount(g4)) ug4 <- as_undirected(g4, mode = "mutual", edge.attr.comb = list(weight = length) ) print(ug4, e = TRUE)
Sometimes it is useful to work with a standard representation of a graph, like an edge list.
as_edgelist(graph, names = TRUE)
as_edgelist(graph, names = TRUE)
graph |
The graph to convert. |
names |
Whether to return a character matrix containing vertex
names (i.e. the |
as_edgelist()
returns the list of edges in a graph.
A ecount(graph)
by 2 numeric matrix.
graph_from_adjacency_matrix()
, read_graph()
Other conversion:
as.matrix.igraph()
,
as_adj_list()
,
as_adjacency_matrix()
,
as_biadjacency_matrix()
,
as_data_frame()
,
as_directed()
,
as_graphnel()
,
as_long_data_frame()
,
graph_from_adj_list()
,
graph_from_graphnel()
g <- sample_gnp(10, 2 / 10) as_edgelist(g) V(g)$name <- LETTERS[seq_len(gorder(g))] as_edgelist(g)
g <- sample_gnp(10, 2 / 10) as_edgelist(g) V(g)$name <- LETTERS[seq_len(gorder(g))] as_edgelist(g)
The graphNEL class is defined in the graph
package, it is another
way to represent graphs. These functions are provided to convert between
the igraph and the graphNEL objects.
as_graphnel(graph)
as_graphnel(graph)
graph |
An igraph graph object. |
as_graphnel()
converts an igraph graph to a graphNEL graph. It
converts all graph/vertex/edge attributes. If the igraph graph has a
vertex attribute ‘name
’, then it will be used to assign
vertex names in the graphNEL graph. Otherwise numeric igraph vertex ids
will be used for this purpose.
as_graphnel()
returns a graphNEL graph object.
graph_from_graphnel()
for the other direction,
as_adjacency_matrix()
, graph_from_adjacency_matrix()
,
as_adj_list()
and graph_from_adj_list()
for
other graph representations.
Other conversion:
as.matrix.igraph()
,
as_adj_list()
,
as_adjacency_matrix()
,
as_biadjacency_matrix()
,
as_data_frame()
,
as_directed()
,
as_edgelist()
,
as_long_data_frame()
,
graph_from_adj_list()
,
graph_from_graphnel()
## Undirected g <- make_ring(10) V(g)$name <- letters[1:10] GNEL <- as_graphnel(g) g2 <- graph_from_graphnel(GNEL) g2 ## Directed g3 <- make_star(10, mode = "in") V(g3)$name <- letters[1:10] GNEL2 <- as_graphnel(g3) g4 <- graph_from_graphnel(GNEL2) g4
## Undirected g <- make_ring(10) V(g)$name <- letters[1:10] GNEL <- as_graphnel(g) g2 <- graph_from_graphnel(GNEL) g2 ## Directed g3 <- make_star(10, mode = "in") V(g3)$name <- letters[1:10] GNEL2 <- as_graphnel(g3) g4 <- graph_from_graphnel(GNEL2) g4
Convert a vertex or edge sequence to an ordinary vector
as_ids(seq) ## S3 method for class 'igraph.vs' as_ids(seq) ## S3 method for class 'igraph.es' as_ids(seq)
as_ids(seq) ## S3 method for class 'igraph.vs' as_ids(seq) ## S3 method for class 'igraph.es' as_ids(seq)
seq |
The vertex or edge sequence. |
For graphs without names, a numeric vector is returned, containing the internal numeric vertex or edge ids.
For graphs with names, and vertex sequences, the vertex names are returned in a character vector.
For graphs with names and edge sequences, a character vector is
returned, with the ‘bar’ notation: a|b
means an edge from
vertex a
to vertex b
.
A character or numeric vector, see details below.
Other vertex and edge sequences:
E()
,
V()
,
igraph-es-attributes
,
igraph-es-indexing
,
igraph-es-indexing2
,
igraph-vs-attributes
,
igraph-vs-indexing
,
igraph-vs-indexing2
,
print.igraph.es()
,
print.igraph.vs()
g <- make_ring(10) as_ids(V(g)) as_ids(E(g)) V(g)$name <- letters[1:10] as_ids(V(g)) as_ids(E(g))
g <- make_ring(10) as_ids(V(g)) as_ids(E(g)) V(g)$name <- letters[1:10] as_ids(V(g)) as_ids(E(g))
A long data frame contains all metadata about both the vertices
and edges of the graph. It contains one row for each edge, and
all metadata about that edge and its incident vertices are included
in that row. The names of the columns that contain the metadata
of the incident vertices are prefixed with from_
and to_
.
The first two columns are always named from
and to
and
they contain the numeric ids of the incident vertices. The rows are
listed in the order of numeric vertex ids.
as_long_data_frame(graph)
as_long_data_frame(graph)
graph |
Input graph |
A long data frame.
Other conversion:
as.matrix.igraph()
,
as_adj_list()
,
as_adjacency_matrix()
,
as_biadjacency_matrix()
,
as_data_frame()
,
as_directed()
,
as_edgelist()
,
as_graphnel()
,
graph_from_adj_list()
,
graph_from_graphnel()
g <- make_( ring(10), with_vertex_(name = letters[1:10], color = "red"), with_edge_(weight = 1:10, color = "green") ) as_long_data_frame(g)
g <- make_( ring(10), with_vertex_(name = letters[1:10], color = "red"), with_edge_(weight = 1:10, color = "green") ) as_long_data_frame(g)
This is useful if you want to use functions defined on membership vectors, but your membership vector does not come from an igraph clustering method.
as_membership(x)
as_membership(x)
x |
The input vector. |
The input vector, with the membership
class added.
Community detection
cluster_edge_betweenness()
,
cluster_fast_greedy()
,
cluster_fluid_communities()
,
cluster_infomap()
,
cluster_label_prop()
,
cluster_leading_eigen()
,
cluster_leiden()
,
cluster_louvain()
,
cluster_optimal()
,
cluster_spinglass()
,
cluster_walktrap()
,
compare()
,
groups()
,
make_clusters()
,
membership()
,
modularity.igraph()
,
plot_dendrogram()
,
split_join_distance()
,
voronoi_cells()
## Compare to the correct clustering g <- (make_full_graph(10) + make_full_graph(10)) %>% rewire(each_edge(p = 0.2)) correct <- rep(1:2, each = 10) %>% as_membership() fc <- cluster_fast_greedy(g) compare(correct, fc) compare(correct, membership(fc))
## Compare to the correct clustering g <- (make_full_graph(10) + make_full_graph(10)) %>% rewire(each_edge(p = 0.2)) correct <- rep(1:2, each = 10) %>% as_membership() fc <- cluster_fast_greedy(g) compare(correct, fc) compare(correct, membership(fc))
These functions convert various objects to igraph graphs.
as.igraph(x, ...)
as.igraph(x, ...)
x |
The object to convert. |
... |
Additional arguments. None currently. |
You can use as.igraph()
to convert various objects to igraph graphs.
Right now the following objects are supported:
codeigraphHRG
These objects are created by the fit_hrg()
and
consensus_tree()
functions.
All these functions return an igraph graph.
Gabor Csardi [email protected].
g <- make_full_graph(5) + make_full_graph(5) hrg <- fit_hrg(g) as.igraph(hrg)
g <- make_full_graph(5) + make_full_graph(5) hrg <- fit_hrg(g) as.igraph(hrg)
Get adjacency or edgelist representation of the network stored as an
igraph
object.
## S3 method for class 'igraph' as.matrix(x, matrix.type = c("adjacency", "edgelist"), ...)
## S3 method for class 'igraph' as.matrix(x, matrix.type = c("adjacency", "edgelist"), ...)
x |
object of class igraph, the network |
matrix.type |
character, type of matrix to return, currently "adjacency" or "edgelist" are supported |
... |
other arguments to/from other methods |
If matrix.type
is "edgelist"
, then a two-column numeric edge list
matrix is returned. The value of attrname
is ignored.
If matrix.type
is "adjacency"
, then a square adjacency matrix is
returned. For adjacency matrices, you can use the attr
keyword argument
to use the values of an edge attribute in the matrix cells. See the
documentation of as_adjacency_matrix for more details.
Other arguments passed through ...
are passed to either
as_adjacency_matrix()
or as_edgelist()
depending on the value of matrix.type
.
Depending on the value of matrix.type
either a square
adjacency matrix or a two-column numeric matrix representing the edgelist.
Michal Bojanowski, originally from the intergraph
package
Other conversion:
as_adj_list()
,
as_adjacency_matrix()
,
as_biadjacency_matrix()
,
as_data_frame()
,
as_directed()
,
as_edgelist()
,
as_graphnel()
,
as_long_data_frame()
,
graph_from_adj_list()
,
graph_from_graphnel()
g <- make_graph("zachary") as.matrix(g, "adjacency") as.matrix(g, "edgelist") # use edge attribute "weight" E(g)$weight <- rep(1:10, length.out = ecount(g)) as.matrix(g, "adjacency", sparse = FALSE, attr = "weight")
g <- make_graph("zachary") as.matrix(g, "adjacency") as.matrix(g, "edgelist") # use edge attribute "weight" E(g)$weight <- rep(1:10, length.out = ecount(g)) as.matrix(g, "adjacency", sparse = FALSE, attr = "weight")
The assortativity coefficient is positive if similar vertices (based on some external property) tend to connect to each, and negative otherwise.
assortativity( graph, values, ..., values.in = NULL, directed = TRUE, normalized = TRUE, types1 = NULL, types2 = NULL ) assortativity_nominal(graph, types, directed = TRUE, normalized = TRUE) assortativity_degree(graph, directed = TRUE)
assortativity( graph, values, ..., values.in = NULL, directed = TRUE, normalized = TRUE, types1 = NULL, types2 = NULL ) assortativity_nominal(graph, types, directed = TRUE, normalized = TRUE) assortativity_degree(graph, directed = TRUE)
graph |
The input graph, it can be directed or undirected. |
values |
The vertex values, these can be arbitrary numeric values. |
... |
These dots are for future extensions and must be empty. |
values.in |
A second value vector to use for the incoming edges when
calculating assortativity for a directed graph.
Supply |
directed |
Logical scalar, whether to consider edge directions for
directed graphs.
This argument is ignored for undirected graphs.
Supply
|
normalized |
Boolean, whether to compute the normalized assortativity. The non-normalized nominal assortativity is identical to modularity. The non-normalized value-based assortativity is simply the covariance of the values at the two ends of edges. |
types1 , types2
|
|
types |
Vector giving the vertex types. They as assumed to be integer
numbers, starting with one. Non-integer values are converted to integers
with |
The assortativity coefficient measures the level of homophyly of the graph, based on some vertex labeling or values assigned to vertices. If the coefficient is high, that means that connected vertices tend to have the same labels or similar assigned values.
M.E.J. Newman defined two kinds of assortativity coefficients, the first one
is for categorical labels of vertices. assortativity_nominal()
calculates this measure. It is defined as
where is the fraction of edges connecting vertices of
type
and
,
and
.
The second assortativity variant is based on values assigned to the
vertices. assortativity()
calculates this measure. It is defined as
for undirected graphs () and as
for directed ones. Here ,
, moreover,
,
and
are the standard deviations of
,
and
, respectively.
The reason of the difference is that in directed networks the relationship is not symmetric, so it is possible to assign different values to the outgoing and the incoming end of the edges.
assortativity_degree()
uses vertex degree as vertex values
and calls assortativity()
.
Undirected graphs are effectively treated as directed ones with all-reciprocal edges. Thus, self-loops are taken into account twice in undirected graphs.
A single real number.
igraph_assortativity()
, igraph_assortativity_nominal()
, igraph_assortativity_degree()
.
Gabor Csardi [email protected]
M. E. J. Newman: Mixing patterns in networks, Phys. Rev. E 67, 026126 (2003) https://arxiv.org/abs/cond-mat/0209450
M. E. J. Newman: Assortative mixing in networks, Phys. Rev. Lett. 89, 208701 (2002) https://arxiv.org/abs/cond-mat/0205405
# random network, close to zero assortativity_degree(sample_gnp(10000, 3 / 10000)) # BA model, tends to be dissortative assortativity_degree(sample_pa(10000, m = 4))
# random network, close to zero assortativity_degree(sample_gnp(10000, 3 / 10000)) # BA model, tends to be dissortative assortativity_degree(sample_pa(10000, m = 4))
Kleinberg's authority centrality scores.
Kleinberg's hub centrality scores.
authority_score( graph, scale = TRUE, weights = NULL, options = arpack_defaults() ) hub_score(graph, scale = TRUE, weights = NULL, options = arpack_defaults())
authority_score( graph, scale = TRUE, weights = NULL, options = arpack_defaults() ) hub_score(graph, scale = TRUE, weights = NULL, options = arpack_defaults())
graph |
The input graph. |
scale |
Logical scalar, whether to scale the result to have a maximum score of one. If no scaling is used then the result vector has unit length in the Euclidean norm. |
weights |
Optional positive weight vector for calculating weighted
scores. If the graph has a |
options |
A named list, to override some ARPACK options. See
|
Centrality measures
alpha_centrality()
,
betweenness()
,
closeness()
,
diversity()
,
eigen_centrality()
,
harmonic_centrality()
,
hits_scores()
,
page_rank()
,
power_centrality()
,
spectrum()
,
strength()
,
subgraph_centrality()
Compute the generating set of the automorphism group of a graph.
automorphism_group( graph, colors = NULL, sh = c("fm", "f", "fs", "fl", "flm", "fsm"), details = FALSE )
automorphism_group( graph, colors = NULL, sh = c("fm", "f", "fs", "fl", "flm", "fsm"), details = FALSE )
graph |
The input graph, it is treated as undirected. |
colors |
The colors of the individual vertices of the graph; only
vertices having the same color are allowed to match each other in an
automorphism. When omitted, igraph uses the |
sh |
The splitting heuristics for the BLISS algorithm. Possible values
are: ‘ |
details |
Specifies whether to provide additional details about the BLISS internals in the result. |
An automorphism of a graph is a permutation of its vertices which brings the graph into itself. The automorphisms of a graph form a group and there exists a subset of this group (i.e. a set of permutations) such that every other permutation can be expressed as a combination of these permutations. These permutations are called the generating set of the automorphism group.
This function calculates a possible generating set of the automorphism of a graph using the BLISS algorithm. See also the BLISS homepage at http://www.tcs.hut.fi/Software/bliss/index.html. The calculated generating set is not necessarily minimal, and it may depend on the splitting heuristics used by BLISS.
When details
is FALSE
, a list of vertex permutations
that form a generating set of the automorphism group of the input graph.
When details
is TRUE
, a named list with two members:
generators |
Returns the generators themselves |
info |
Additional
information about the BLISS internals. See |
Tommi Junttila (http://users.ics.aalto.fi/tjunttil/) for BLISS, Gabor Csardi [email protected] for the igraph glue code and Tamas Nepusz [email protected] for this manual page.
Tommi Junttila and Petteri Kaski: Engineering an Efficient Canonical Labeling Tool for Large and Sparse Graphs, Proceedings of the Ninth Workshop on Algorithm Engineering and Experiments and the Fourth Workshop on Analytic Algorithms and Combinatorics. 2007.
canonical_permutation()
, permute()
,
count_automorphisms()
Other graph automorphism:
count_automorphisms()
## A ring has n*2 automorphisms, and a possible generating set is one that ## "turns" the ring by one vertex to the left or right g <- make_ring(10) automorphism_group(g)
## A ring has n*2 automorphisms, and a possible generating set is one that ## "turns" the ring by one vertex to the left or right g <- make_ring(10) automorphism_group(g)
The vertex and edge betweenness are (roughly) defined by the number of geodesics (shortest paths) going through a vertex or an edge.
betweenness( graph, v = V(graph), directed = TRUE, weights = NULL, normalized = FALSE, cutoff = -1 ) edge_betweenness( graph, e = E(graph), directed = TRUE, weights = NULL, cutoff = -1 )
betweenness( graph, v = V(graph), directed = TRUE, weights = NULL, normalized = FALSE, cutoff = -1 ) edge_betweenness( graph, e = E(graph), directed = TRUE, weights = NULL, cutoff = -1 )
graph |
The graph to analyze. |
v |
The vertices for which the vertex betweenness will be calculated. |
directed |
Logical, whether directed paths should be considered while determining the shortest paths. |
weights |
Optional positive weight vector for calculating weighted
betweenness. If the graph has a |
normalized |
Logical scalar, whether to normalize the betweenness
scores. If
where
|
cutoff |
The maximum shortest path length to consider when calculating betweenness. If negative, then there is no such limit. |
e |
The edges for which the edge betweenness will be calculated. |
The vertex betweenness of vertex v
is defined by
The edge betweenness of edge e
is defined by
betweenness()
calculates vertex betweenness, edge_betweenness()
calculates edge betweenness.
Here is the total number of shortest paths between vertices
and
while
is the number of those shortest paths
which pass though vertex
.
Both functions allow you to consider only paths of length cutoff
or
smaller; this can be run for larger graphs, as the running time is not
quadratic (if cutoff
is small). If cutoff
is negative (the default),
then the function calculates the exact betweenness scores. Since igraph 1.6.0,
a cutoff
value of zero is treated literally, i.e. paths of length larger
than zero are ignored.
For calculating the betweenness a similar algorithm to the one proposed by Brandes (see References) is used.
A numeric vector with the betweenness score for each vertex in
v
for betweenness()
.
A numeric vector with the edge betweenness score for each edge in e
for edge_betweenness()
.
edge_betweenness()
might give false values for graphs with
multiple edges.
Gabor Csardi [email protected]
Freeman, L.C. (1979). Centrality in Social Networks I: Conceptual Clarification. Social Networks, 1, 215-239. doi:10.1016/0378-8733(78)90021-7
Ulrik Brandes, A Faster Algorithm for Betweenness Centrality. Journal of Mathematical Sociology 25(2):163-177, 2001. doi:10.1080/0022250X.2001.9990249
closeness()
, degree()
, harmonic_centrality()
Centrality measures
alpha_centrality()
,
authority_score()
,
closeness()
,
diversity()
,
eigen_centrality()
,
harmonic_centrality()
,
hits_scores()
,
page_rank()
,
power_centrality()
,
spectrum()
,
strength()
,
subgraph_centrality()
g <- sample_gnp(10, 3 / 10) betweenness(g) edge_betweenness(g)
g <- sample_gnp(10, 3 / 10) betweenness(g) edge_betweenness(g)
Breadth-first search is an algorithm to traverse a graph. We start from a root vertex and spread along every edge “simultaneously”.
bfs( graph, root, mode = c("out", "in", "all", "total"), unreachable = TRUE, restricted = NULL, order = TRUE, rank = FALSE, father = FALSE, pred = FALSE, succ = FALSE, dist = FALSE, callback = NULL, extra = NULL, rho = parent.frame(), neimode = deprecated() )
bfs( graph, root, mode = c("out", "in", "all", "total"), unreachable = TRUE, restricted = NULL, order = TRUE, rank = FALSE, father = FALSE, pred = FALSE, succ = FALSE, dist = FALSE, callback = NULL, extra = NULL, rho = parent.frame(), neimode = deprecated() )
The callback function must have the following arguments:
The input graph is passed to the callback function here.
A named numeric vector, with the following entries: ‘vid’, the vertex that was just visited, ‘pred’, its predecessor (zero if this is the first vertex), ‘succ’, its successor (zero if this is the last vertex), ‘rank’, the rank of the current vertex, ‘dist’, its distance from the root of the search tree.
The extra argument.
The callback must return FALSE
to continue the search or TRUE
to terminate it. See examples below on how to
use the callback function.
A named list with the following entries:
root |
Numeric scalar. The root vertex that was used as the starting point of the search. |
neimode |
Character scalar. The |
order |
Numeric vector. The vertex ids, in the order in which they were visited by the search. |
rank |
Numeric vector. The rank for each vertex, zero for unreachable vertices. |
father |
Numeric vector. The father of each vertex, i.e. the vertex it was discovered from. |
pred |
Numeric vector. The previously visited vertex for each vertex, or 0 if there was no such vertex. |
succ |
Numeric vector. The next vertex that was visited after the current one, or 0 if there was no such vertex. |
dist |
Numeric vector, for each vertex its distance from the
root of the search tree. Unreachable vertices have a negative distance
as of igraph 1.6.0, this used to be |
Note that order
, rank
, father
, pred
, succ
and dist
might be NULL
if their corresponding argument is
FALSE
, i.e. if their calculation is not requested.
Gabor Csardi [email protected]
dfs()
for depth-first search.
Other structural.properties:
component_distribution()
,
connect()
,
constraint()
,
coreness()
,
degree()
,
dfs()
,
distance_table()
,
edge_density()
,
feedback_arc_set()
,
girth()
,
is_acyclic()
,
is_dag()
,
is_matching()
,
k_shortest_paths()
,
knn()
,
reciprocity()
,
subcomponent()
,
subgraph()
,
topo_sort()
,
transitivity()
,
unfold_tree()
,
which_multiple()
,
which_mutual()
## Two rings bfs(make_ring(10) %du% make_ring(10), root = 1, "out", order = TRUE, rank = TRUE, father = TRUE, pred = TRUE, succ = TRUE, dist = TRUE ) ## How to use a callback f <- function(graph, data, extra) { print(data) FALSE } tmp <- bfs(make_ring(10) %du% make_ring(10), root = 1, "out", callback = f ) ## How to use a callback to stop the search ## We stop after visiting all vertices in the initial component f <- function(graph, data, extra) { data["succ"] == -1 } bfs(make_ring(10) %du% make_ring(10), root = 1, callback = f)
## Two rings bfs(make_ring(10) %du% make_ring(10), root = 1, "out", order = TRUE, rank = TRUE, father = TRUE, pred = TRUE, succ = TRUE, dist = TRUE ) ## How to use a callback f <- function(graph, data, extra) { print(data) FALSE } tmp <- bfs(make_ring(10) %du% make_ring(10), root = 1, "out", callback = f ) ## How to use a callback to stop the search ## We stop after visiting all vertices in the initial component f <- function(graph, data, extra) { data["succ"] == -1 } bfs(make_ring(10) %du% make_ring(10), root = 1, callback = f)
Finding the biconnected components of a graph
biconnected_components(graph)
biconnected_components(graph)
graph |
The input graph. It is treated as an undirected graph, even if it is directed. |
A graph is biconnected if the removal of any single vertex (and its adjacent edges) does not disconnect it.
A biconnected component of a graph is a maximal biconnected subgraph of it. The biconnected components of a graph can be given by the partition of its edges: every edge is a member of exactly one biconnected component. Note that this is not true for vertices: the same vertex can be part of many biconnected components.
A named list with three components:
no |
Numeric scalar, an integer giving the number of biconnected components in the graph. |
tree_edges |
The components themselves, a list of numeric vectors. Each vector is a set of edge ids giving the edges in a biconnected component. These edges define a spanning tree of the component. |
component_edges |
A list of numeric vectors. It gives all edges in the components. |
components |
A list of numeric vectors, the vertices of the components. |
articulation_points |
The articulation points of the
graph. See |
igraph_biconnected_components()
.
Gabor Csardi [email protected]
articulation_points()
, components()
,
is_connected()
, vertex_connectivity()
Connected components
articulation_points()
,
component_distribution()
,
decompose()
,
is_biconnected()
g <- disjoint_union(make_full_graph(5), make_full_graph(5)) clu <- components(g)$membership g <- add_edges(g, c(which(clu == 1), which(clu == 2))) bc <- biconnected_components(g)
g <- disjoint_union(make_full_graph(5), make_full_graph(5)) clu <- components(g)$membership g <- add_edges(g, c(which(clu == 1), which(clu == 2))) bc <- biconnected_components(g)
This function decides whether the vertices of a network can be mapped to two vertex types in a way that no vertices of the same type are connected.
bipartite_mapping(graph)
bipartite_mapping(graph)
graph |
The input graph. |
A bipartite graph in igraph has a ‘type
’ vertex attribute
giving the two vertex types.
This function simply checks whether a graph could be bipartite. It tries to find a mapping that gives a possible division of the vertices into two classes, such that no two vertices of the same class are connected by an edge.
The existence of such a mapping is equivalent of having no circuits of odd length in the graph. A graph with loop edges cannot bipartite.
Note that the mapping is not necessarily unique, e.g. if the graph has at least two components, then the vertices in the separate components can be mapped independently.
A named list with two elements:
res |
A logical scalar,
|
type |
A possible vertex type mapping, a logical vector. If no such mapping exists, then an empty vector. |
Gabor Csardi [email protected]
Bipartite graphs
bipartite_projection()
,
is_bipartite()
,
make_bipartite_graph()
## Rings with an even number of vertices are bipartite g <- make_ring(10) bipartite_mapping(g) ## All star graphs are bipartite g2 <- make_star(10) bipartite_mapping(g2) ## A graph containing a triangle is not bipartite g3 <- make_ring(10) g3 <- add_edges(g3, c(1, 3)) bipartite_mapping(g3)
## Rings with an even number of vertices are bipartite g <- make_ring(10) bipartite_mapping(g) ## All star graphs are bipartite g2 <- make_star(10) bipartite_mapping(g2) ## A graph containing a triangle is not bipartite g3 <- make_ring(10) g3 <- add_edges(g3, c(1, 3)) bipartite_mapping(g3)
A bipartite graph is projected into two one-mode networks
bipartite_projection( graph, types = NULL, multiplicity = TRUE, probe1 = NULL, which = c("both", "true", "false"), remove.type = TRUE ) bipartite_projection_size(graph, types = NULL)
bipartite_projection( graph, types = NULL, multiplicity = TRUE, probe1 = NULL, which = c("both", "true", "false"), remove.type = TRUE ) bipartite_projection_size(graph, types = NULL)
graph |
The input graph. It can be directed, but edge directions are ignored during the computation. |
types |
An optional vertex type vector to use instead of the
‘ |
multiplicity |
If |
probe1 |
This argument can be used to specify the order of the
projections in the resulting list. If given, then it is considered as a
vertex id (or a symbolic vertex name); the projection containing this vertex
will be the first one in the result list. This argument is ignored if only
one projection is requested in argument |
which |
A character scalar to specify which projection(s) to calculate. The default is to calculate both. |
remove.type |
Logical scalar, whether to remove the |
Bipartite graphs have a type
vertex attribute in igraph, this is
boolean and FALSE
for the vertices of the first kind and TRUE
for vertices of the second kind.
bipartite_projection_size()
calculates the number of vertices and edges
in the two projections of the bipartite graphs, without calculating the
projections themselves. This is useful to check how much memory the
projections would need if you have a large bipartite graph.
bipartite_projection()
calculates the actual projections. You can use
the probe1
argument to specify the order of the projections in the
result. By default vertex type FALSE
is the first and TRUE
is
the second.
bipartite_projection()
keeps vertex attributes.
A list of two undirected graphs. See details above.
igraph_bipartite_projection_size()
.
Gabor Csardi [email protected]
Bipartite graphs
bipartite_mapping()
,
is_bipartite()
,
make_bipartite_graph()
## Projection of a full bipartite graph is a full graph g <- make_full_bipartite_graph(10, 5) proj <- bipartite_projection(g) graph.isomorphic(proj[[1]], make_full_graph(10)) graph.isomorphic(proj[[2]], make_full_graph(5)) ## The projection keeps the vertex attributes M <- matrix(0, nrow = 5, ncol = 3) rownames(M) <- c("Alice", "Bob", "Cecil", "Dan", "Ethel") colnames(M) <- c("Party", "Skiing", "Badminton") M[] <- sample(0:1, length(M), replace = TRUE) M g2 <- graph_from_biadjacency_matrix(M) g2$name <- "Event network" proj2 <- bipartite_projection(g2) print(proj2[[1]], g = TRUE, e = TRUE) print(proj2[[2]], g = TRUE, e = TRUE)
## Projection of a full bipartite graph is a full graph g <- make_full_bipartite_graph(10, 5) proj <- bipartite_projection(g) graph.isomorphic(proj[[1]], make_full_graph(10)) graph.isomorphic(proj[[2]], make_full_graph(5)) ## The projection keeps the vertex attributes M <- matrix(0, nrow = 5, ncol = 3) rownames(M) <- c("Alice", "Bob", "Cecil", "Dan", "Ethel") colnames(M) <- c("Party", "Skiing", "Badminton") M[] <- sample(0:1, length(M), replace = TRUE) M g2 <- graph_from_biadjacency_matrix(M) g2$name <- "Event network" proj2 <- bipartite_projection(g2) print(proj2[[1]], g = TRUE, e = TRUE) print(proj2[[2]], g = TRUE, e = TRUE)
Concatenate edge sequences
## S3 method for class 'igraph.es' c(..., recursive = FALSE)
## S3 method for class 'igraph.es' c(..., recursive = FALSE)
... |
The edge sequences to concatenate. They must all refer to the same graph. |
recursive |
Ignored, included for S3 compatibility with the
base |
An edge sequence, the input sequences concatenated.
Other vertex and edge sequence operations:
c.igraph.vs()
,
difference.igraph.es()
,
difference.igraph.vs()
,
igraph-es-indexing
,
igraph-es-indexing2
,
igraph-vs-indexing
,
igraph-vs-indexing2
,
intersection.igraph.es()
,
intersection.igraph.vs()
,
rev.igraph.es()
,
rev.igraph.vs()
,
union.igraph.es()
,
union.igraph.vs()
,
unique.igraph.es()
,
unique.igraph.vs()
g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) c(E(g)[1], E(g)["A|B"], E(g)[1:4])
g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) c(E(g)[1], E(g)["A|B"], E(g)[1:4])
Concatenate vertex sequences
## S3 method for class 'igraph.vs' c(..., recursive = FALSE)
## S3 method for class 'igraph.vs' c(..., recursive = FALSE)
... |
The vertex sequences to concatenate. They must refer to the same graph. |
recursive |
Ignored, included for S3 compatibility with
the base |
A vertex sequence, the input sequences concatenated.
Other vertex and edge sequence operations:
c.igraph.es()
,
difference.igraph.es()
,
difference.igraph.vs()
,
igraph-es-indexing
,
igraph-es-indexing2
,
igraph-vs-indexing
,
igraph-vs-indexing2
,
intersection.igraph.es()
,
intersection.igraph.vs()
,
rev.igraph.es()
,
rev.igraph.vs()
,
union.igraph.es()
,
union.igraph.vs()
,
unique.igraph.es()
,
unique.igraph.vs()
g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) c(V(g)[1], V(g)["A"], V(g)[1:4])
g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) c(V(g)[1], V(g)["A"], V(g)[1:4])
The canonical permutation brings every isomorphic graphs into the same (labeled) graph.
canonical_permutation( graph, colors = NULL, sh = c("fm", "f", "fs", "fl", "flm", "fsm") )
canonical_permutation( graph, colors = NULL, sh = c("fm", "f", "fs", "fl", "flm", "fsm") )
graph |
The input graph, treated as undirected. |
colors |
The colors of the individual vertices of the graph; only
vertices having the same color are allowed to match each other in an
automorphism. When omitted, igraph uses the |
sh |
Type of the heuristics to use for the BLISS algorithm. See details for possible values. |
canonical_permutation()
computes a permutation which brings the graph
into canonical form, as defined by the BLISS algorithm. All isomorphic
graphs have the same canonical form.
See the paper below for the details about BLISS. This and more information is available at http://www.tcs.hut.fi/Software/bliss/index.html.
The possible values for the sh
argument are:
First non-singleton cell.
First largest non-singleton cell.
First smallest non-singleton cell.
First maximally non-trivially connectec non-singleton cell.
Largest maximally non-trivially connected non-singleton cell.
Smallest maximally non-trivially connected non-singleton cell.
See the paper in references for details about these.
A list with the following members:
labeling |
The canonical permutation which takes the input graph into canonical form. A numeric vector, the first element is the new label of vertex 0, the second element for vertex 1, etc. |
info |
Some information about the BLISS computation. A named list with the following members:
|
igraph_canonical_permutation()
.
Tommi Junttila for BLISS, Gabor Csardi [email protected] for the igraph and R interfaces.
Tommi Junttila and Petteri Kaski: Engineering an Efficient Canonical Labeling Tool for Large and Sparse Graphs, Proceedings of the Ninth Workshop on Algorithm Engineering and Experiments and the Fourth Workshop on Analytic Algorithms and Combinatorics. 2007.
permute()
to apply a permutation to a graph,
graph.isomorphic()
for deciding graph isomorphism, possibly
based on canonical labels.
Other graph isomorphism:
count_isomorphisms()
,
count_subgraph_isomorphisms()
,
graph_from_isomorphism_class()
,
isomorphic()
,
isomorphism_class()
,
isomorphisms()
,
subgraph_isomorphic()
,
subgraph_isomorphisms()
## Calculate the canonical form of a random graph g1 <- sample_gnm(10, 20) cp1 <- canonical_permutation(g1) cf1 <- permute(g1, cp1$labeling) ## Do the same with a random permutation of it g2 <- permute(g1, sample(vcount(g1))) cp2 <- canonical_permutation(g2) cf2 <- permute(g2, cp2$labeling) ## Check that they are the same el1 <- as_edgelist(cf1) el2 <- as_edgelist(cf2) el1 <- el1[order(el1[, 1], el1[, 2]), ] el2 <- el2[order(el2[, 1], el2[, 2]), ] all(el1 == el2)
## Calculate the canonical form of a random graph g1 <- sample_gnm(10, 20) cp1 <- canonical_permutation(g1) cf1 <- permute(g1, cp1$labeling) ## Do the same with a random permutation of it g2 <- permute(g1, sample(vcount(g1))) cp2 <- canonical_permutation(g2) cf2 <- permute(g2, cp2$labeling) ## Check that they are the same el1 <- as_edgelist(cf1) el2 <- as_edgelist(cf2) el1 <- el1[order(el1[, 1], el1[, 2]), ] el2 <- el2[order(el2[, 1], el2[, 2]), ] all(el1 == el2)
This is a color blind friendly palette from https://jfly.uni-koeln.de/color/. It has 8 colors.
categorical_pal(n)
categorical_pal(n)
n |
The number of colors in the palette. We simply take the first
|
This is the suggested palette for visualizations where vertex colors mark categories, e.g. community membership.
A character vector of RGB color codes.
library(igraphdata) data(karate) karate <- karate add_layout_(with_fr()) set_vertex_attr("size", value = 10) cl_k <- cluster_optimal(karate) V(karate)$color <- membership(cl_k) karate$palette <- categorical_pal(length(cl_k)) plot(karate)
Other palettes:
diverging_pal()
,
r_pal()
,
sequential_pal()
See centralize()
for a summary of graph centralization.
centr_betw(graph, directed = TRUE, normalized = TRUE)
centr_betw(graph, directed = TRUE, normalized = TRUE)
graph |
The input graph. |
directed |
logical scalar, whether to use directed shortest paths for calculating betweenness. |
normalized |
Logical scalar. Whether to normalize the graph level centrality score by dividing by the theoretical maximum. |
A named list with the following components:
res |
The node-level centrality scores. |
centralization |
The graph level centrality index. |
theoretical_max |
The maximum theoretical graph level
centralization score for a graph with the given number of vertices,
using the same parameters. If the |
Other centralization related:
centr_betw_tmax()
,
centr_clo()
,
centr_clo_tmax()
,
centr_degree()
,
centr_degree_tmax()
,
centr_eigen()
,
centr_eigen_tmax()
,
centralize()
# A BA graph is quite centralized g <- sample_pa(1000, m = 4) centr_degree(g)$centralization centr_clo(g, mode = "all")$centralization centr_betw(g, directed = FALSE)$centralization centr_eigen(g, directed = FALSE)$centralization
# A BA graph is quite centralized g <- sample_pa(1000, m = 4) centr_degree(g)$centralization centr_clo(g, mode = "all")$centralization centr_betw(g, directed = FALSE)$centralization centr_eigen(g, directed = FALSE)$centralization
See centralize()
for a summary of graph centralization.
centr_betw_tmax(graph = NULL, nodes = 0, directed = TRUE)
centr_betw_tmax(graph = NULL, nodes = 0, directed = TRUE)
graph |
The input graph. It can also be |
nodes |
The number of vertices. This is ignored if the graph is given. |
directed |
Logical scalar, whether to use directed shortest paths for calculating betweenness. Ignored if an undirected graph was given. |
Real scalar, the theoretical maximum (unnormalized) graph betweenness centrality score for graphs with given order and other parameters.
igraph_centralization_betweenness_tmax()
.
Other centralization related:
centr_betw()
,
centr_clo()
,
centr_clo_tmax()
,
centr_degree()
,
centr_degree_tmax()
,
centr_eigen()
,
centr_eigen_tmax()
,
centralize()
# A BA graph is quite centralized g <- sample_pa(1000, m = 4) centr_betw(g, normalized = FALSE)$centralization %>% `/`(centr_betw_tmax(g)) centr_betw(g, normalized = TRUE)$centralization
# A BA graph is quite centralized g <- sample_pa(1000, m = 4) centr_betw(g, normalized = FALSE)$centralization %>% `/`(centr_betw_tmax(g)) centr_betw(g, normalized = TRUE)$centralization
See centralize()
for a summary of graph centralization.
centr_clo(graph, mode = c("out", "in", "all", "total"), normalized = TRUE)
centr_clo(graph, mode = c("out", "in", "all", "total"), normalized = TRUE)
graph |
The input graph. |
mode |
This is the same as the |
normalized |
Logical scalar. Whether to normalize the graph level centrality score by dividing by the theoretical maximum. |
A named list with the following components:
res |
The node-level centrality scores. |
centralization |
The graph level centrality index. |
theoretical_max |
The maximum theoretical graph level
centralization score for a graph with the given number of vertices,
using the same parameters. If the |
igraph_centralization_closeness()
.
Other centralization related:
centr_betw()
,
centr_betw_tmax()
,
centr_clo_tmax()
,
centr_degree()
,
centr_degree_tmax()
,
centr_eigen()
,
centr_eigen_tmax()
,
centralize()
# A BA graph is quite centralized g <- sample_pa(1000, m = 4) centr_degree(g)$centralization centr_clo(g, mode = "all")$centralization centr_betw(g, directed = FALSE)$centralization centr_eigen(g, directed = FALSE)$centralization
# A BA graph is quite centralized g <- sample_pa(1000, m = 4) centr_degree(g)$centralization centr_clo(g, mode = "all")$centralization centr_betw(g, directed = FALSE)$centralization centr_eigen(g, directed = FALSE)$centralization
See centralize()
for a summary of graph centralization.
centr_clo_tmax(graph = NULL, nodes = 0, mode = c("out", "in", "all", "total"))
centr_clo_tmax(graph = NULL, nodes = 0, mode = c("out", "in", "all", "total"))
graph |
The input graph. It can also be |
nodes |
The number of vertices. This is ignored if the graph is given. |
mode |
This is the same as the |
Real scalar, the theoretical maximum (unnormalized) graph closeness centrality score for graphs with given order and other parameters.
igraph_centralization_closeness_tmax()
.
Other centralization related:
centr_betw()
,
centr_betw_tmax()
,
centr_clo()
,
centr_degree()
,
centr_degree_tmax()
,
centr_eigen()
,
centr_eigen_tmax()
,
centralize()
# A BA graph is quite centralized g <- sample_pa(1000, m = 4) centr_clo(g, normalized = FALSE)$centralization %>% `/`(centr_clo_tmax(g)) centr_clo(g, normalized = TRUE)$centralization
# A BA graph is quite centralized g <- sample_pa(1000, m = 4) centr_clo(g, normalized = FALSE)$centralization %>% `/`(centr_clo_tmax(g)) centr_clo(g, normalized = TRUE)$centralization
See centralize()
for a summary of graph centralization.
centr_degree( graph, mode = c("all", "out", "in", "total"), loops = TRUE, normalized = TRUE )
centr_degree( graph, mode = c("all", "out", "in", "total"), loops = TRUE, normalized = TRUE )
graph |
The input graph. |
mode |
This is the same as the |
loops |
Logical scalar, whether to consider loops edges when calculating the degree. |
normalized |
Logical scalar. Whether to normalize the graph level centrality score by dividing by the theoretical maximum. |
A named list with the following components:
res |
The node-level centrality scores. |
centralization |
The graph level centrality index. |
theoretical_max |
The maximum theoretical graph level
centralization score for a graph with the given number of vertices,
using the same parameters. If the |
igraph_centralization_degree()
.
Other centralization related:
centr_betw()
,
centr_betw_tmax()
,
centr_clo()
,
centr_clo_tmax()
,
centr_degree_tmax()
,
centr_eigen()
,
centr_eigen_tmax()
,
centralize()
# A BA graph is quite centralized g <- sample_pa(1000, m = 4) centr_degree(g)$centralization centr_clo(g, mode = "all")$centralization centr_betw(g, directed = FALSE)$centralization centr_eigen(g, directed = FALSE)$centralization
# A BA graph is quite centralized g <- sample_pa(1000, m = 4) centr_degree(g)$centralization centr_clo(g, mode = "all")$centralization centr_betw(g, directed = FALSE)$centralization centr_eigen(g, directed = FALSE)$centralization
See centralize()
for a summary of graph centralization.
centr_degree_tmax( graph = NULL, nodes = 0, mode = c("all", "out", "in", "total"), loops )
centr_degree_tmax( graph = NULL, nodes = 0, mode = c("all", "out", "in", "total"), loops )
graph |
The input graph. It can also be |
nodes |
The number of vertices. This is ignored if the graph is given. |
mode |
This is the same as the |
loops |
Logical scalar, whether to consider loops edges when calculating the degree. |
Real scalar, the theoretical maximum (unnormalized) graph degree centrality score for graphs with given order and other parameters.
Other centralization related:
centr_betw()
,
centr_betw_tmax()
,
centr_clo()
,
centr_clo_tmax()
,
centr_degree()
,
centr_eigen()
,
centr_eigen_tmax()
,
centralize()
# A BA graph is quite centralized g <- sample_pa(1000, m = 4) centr_degree(g, normalized = FALSE)$centralization %>% `/`(centr_degree_tmax(g, loops = FALSE)) centr_degree(g, normalized = TRUE)$centralization
# A BA graph is quite centralized g <- sample_pa(1000, m = 4) centr_degree(g, normalized = FALSE)$centralization %>% `/`(centr_degree_tmax(g, loops = FALSE)) centr_degree(g, normalized = TRUE)$centralization
See centralize()
for a summary of graph centralization.
centr_eigen( graph, directed = FALSE, scale = TRUE, options = arpack_defaults(), normalized = TRUE )
centr_eigen( graph, directed = FALSE, scale = TRUE, options = arpack_defaults(), normalized = TRUE )
graph |
The input graph. |
directed |
logical scalar, whether to use directed shortest paths for calculating eigenvector centrality. |
scale |
Whether to rescale the eigenvector centrality scores, such that the maximum score is one. |
options |
This is passed to |
normalized |
Logical scalar. Whether to normalize the graph level centrality score by dividing by the theoretical maximum. |
A named list with the following components:
vector |
The node-level centrality scores. |
value |
The corresponding eigenvalue. |
options |
ARPACK options, see the return value of
|
centralization |
The graph level centrality index. |
theoretical_max |
The same as above, the theoretical maximum centralization score for a graph with the same number of vertices. |
igraph_centralization_eigenvector_centrality()
.
Other centralization related:
centr_betw()
,
centr_betw_tmax()
,
centr_clo()
,
centr_clo_tmax()
,
centr_degree()
,
centr_degree_tmax()
,
centr_eigen_tmax()
,
centralize()
# A BA graph is quite centralized g <- sample_pa(1000, m = 4) centr_degree(g)$centralization centr_clo(g, mode = "all")$centralization centr_betw(g, directed = FALSE)$centralization centr_eigen(g, directed = FALSE)$centralization # The most centralized graph according to eigenvector centrality g0 <- make_graph(c(2, 1), n = 10, dir = FALSE) g1 <- make_star(10, mode = "undirected") centr_eigen(g0)$centralization centr_eigen(g1)$centralization
# A BA graph is quite centralized g <- sample_pa(1000, m = 4) centr_degree(g)$centralization centr_clo(g, mode = "all")$centralization centr_betw(g, directed = FALSE)$centralization centr_eigen(g, directed = FALSE)$centralization # The most centralized graph according to eigenvector centrality g0 <- make_graph(c(2, 1), n = 10, dir = FALSE) g1 <- make_star(10, mode = "undirected") centr_eigen(g0)$centralization centr_eigen(g1)$centralization
See centralize()
for a summary of graph centralization.
centr_eigen_tmax(graph = NULL, nodes = 0, directed = FALSE, scale = TRUE)
centr_eigen_tmax(graph = NULL, nodes = 0, directed = FALSE, scale = TRUE)
graph |
The input graph. It can also be |
nodes |
The number of vertices. This is ignored if the graph is given. |
directed |
logical scalar, whether to consider edge directions during the calculation. Ignored in undirected graphs. |
scale |
Whether to rescale the eigenvector centrality scores, such that the maximum score is one. |
Real scalar, the theoretical maximum (unnormalized) graph eigenvector centrality score for graphs with given vertex count and other parameters.
igraph_centralization_eigenvector_centrality_tmax()
.
Other centralization related:
centr_betw()
,
centr_betw_tmax()
,
centr_clo()
,
centr_clo_tmax()
,
centr_degree()
,
centr_degree_tmax()
,
centr_eigen()
,
centralize()
# A BA graph is quite centralized g <- sample_pa(1000, m = 4) centr_eigen(g, normalized = FALSE)$centralization %>% `/`(centr_eigen_tmax(g)) centr_eigen(g, normalized = TRUE)$centralization
# A BA graph is quite centralized g <- sample_pa(1000, m = 4) centr_eigen(g, normalized = FALSE)$centralization %>% `/`(centr_eigen_tmax(g)) centr_eigen(g, normalized = TRUE)$centralization
Centralization is a method for creating a graph level centralization measure from the centrality scores of the vertices.
centralize(scores, theoretical.max = 0, normalized = TRUE)
centralize(scores, theoretical.max = 0, normalized = TRUE)
scores |
The vertex level centrality scores. |
theoretical.max |
Real scalar. The graph-level centralization measure of
the most centralized graph with the same number of vertices as the graph
under study. This is only used if the |
normalized |
Logical scalar. Whether to normalize the graph level centrality score by dividing by the supplied theoretical maximum. |
Centralization is a general method for calculating a graph-level centrality score based on node-level centrality measure. The formula for this is
where is the centrality of vertex
.
The graph-level centralization measure can be normalized by dividing by the maximum theoretical score for a graph with the same number of vertices, using the same parameters, e.g. directedness, whether we consider loop edges, etc.
For degree, closeness and betweenness the most centralized structure is some version of the star graph, in-star, out-star or undirected star.
For eigenvector centrality the most centralized structure is the graph with a single edge (and potentially many isolates).
centralize()
implements general centralization formula to calculate
a graph-level score from vertex-level scores.
A real scalar, the centralization of the graph from which
scores
were derived.
Freeman, L.C. (1979). Centrality in Social Networks I: Conceptual Clarification. Social Networks 1, 215–239.
Wasserman, S., and Faust, K. (1994). Social Network Analysis: Methods and Applications. Cambridge University Press.
Other centralization related:
centr_betw()
,
centr_betw_tmax()
,
centr_clo()
,
centr_clo_tmax()
,
centr_degree()
,
centr_degree_tmax()
,
centr_eigen()
,
centr_eigen_tmax()
# A BA graph is quite centralized g <- sample_pa(1000, m = 4) centr_degree(g)$centralization centr_clo(g, mode = "all")$centralization centr_eigen(g, directed = FALSE)$centralization # Calculate centralization from pre-computed scores deg <- degree(g) tmax <- centr_degree_tmax(g, loops = FALSE) centralize(deg, tmax) # The most centralized graph according to eigenvector centrality g0 <- make_graph(c(2, 1), n = 10, dir = FALSE) g1 <- make_star(10, mode = "undirected") centr_eigen(g0)$centralization centr_eigen(g1)$centralization
# A BA graph is quite centralized g <- sample_pa(1000, m = 4) centr_degree(g)$centralization centr_clo(g, mode = "all")$centralization centr_eigen(g, directed = FALSE)$centralization # Calculate centralization from pre-computed scores deg <- degree(g) tmax <- centr_degree_tmax(g, loops = FALSE) centralize(deg, tmax) # The most centralized graph according to eigenvector centrality g0 <- make_graph(c(2, 1), n = 10, dir = FALSE) g1 <- make_star(10, mode = "undirected") centr_eigen(g0)$centralization centr_eigen(g1)$centralization
These functions find all, the largest or all the maximal cliques in an undirected graph. The size of the largest clique can also be calculated.
cliques(graph, min = 0, max = 0) largest_cliques(graph) max_cliques(graph, min = NULL, max = NULL, subset = NULL, file = NULL) count_max_cliques(graph, min = NULL, max = NULL, subset = NULL) clique_num(graph) largest_weighted_cliques(graph, vertex.weights = NULL) weighted_clique_num(graph, vertex.weights = NULL) clique_size_counts(graph, min = 0, max = 0, maximal = FALSE)
cliques(graph, min = 0, max = 0) largest_cliques(graph) max_cliques(graph, min = NULL, max = NULL, subset = NULL, file = NULL) count_max_cliques(graph, min = NULL, max = NULL, subset = NULL) clique_num(graph) largest_weighted_cliques(graph, vertex.weights = NULL) weighted_clique_num(graph, vertex.weights = NULL) clique_size_counts(graph, min = 0, max = 0, maximal = FALSE)
graph |
The input graph, directed graphs will be considered as undirected ones, multiple edges and loops are ignored. |
min |
Numeric constant, lower limit on the size of the cliques to find.
|
max |
Numeric constant, upper limit on the size of the cliques to find.
|
subset |
If not |
file |
If not |
vertex.weights |
Vertex weight vector. If the graph has a |
maximal |
Specifies whether to look for all weighted cliques ( |
cliques()
find all complete subgraphs in the input graph, obeying the
size limitations given in the min
and max
arguments.
largest_cliques()
finds all largest cliques in the input graph. A
clique is largest if there is no other clique including more vertices.
max_cliques()
finds all maximal cliques in the input graph. A
clique is maximal if it cannot be extended to a larger clique. The largest
cliques are always maximal, but a maximal clique is not necessarily the
largest.
count_max_cliques()
counts the maximal cliques.
clique_num()
calculates the size of the largest clique(s).
clique_size_counts()
returns a numeric vector representing a histogram
of clique sizes, between the given minimum and maximum clique size.
cliques()
, largest_cliques()
and clique_num()
return a list containing numeric vectors of vertex ids. Each list element is
a clique, i.e. a vertex sequence of class igraph.vs()
.
max_cliques()
returns NULL
, invisibly, if its file
argument is not NULL
. The output is written to the specified file in
this case.
clique_num()
and count_max_cliques()
return an integer
scalar.
clique_size_counts()
returns a numeric vector with the clique sizes such that
the i-th item belongs to cliques of size i. Trailing zeros are currently
truncated, but this might change in future versions.
igraph_cliques()
, igraph_largest_cliques()
, igraph_clique_number()
, igraph_largest_weighted_cliques()
, igraph_weighted_clique_number()
, igraph_maximal_cliques_hist()
, igraph_clique_size_hist()
.
Tamas Nepusz [email protected] and Gabor Csardi [email protected]
For maximal cliques the following algorithm is implemented: David Eppstein, Maarten Loffler, Darren Strash: Listing All Maximal Cliques in Sparse Graphs in Near-optimal Time. https://arxiv.org/abs/1006.5440
Other cliques:
ivs()
,
weighted_cliques()
# this usually contains cliques of size six g <- sample_gnp(100, 0.3) clique_num(g) cliques(g, min = 6) largest_cliques(g) # To have a bit less maximal cliques, about 100-200 usually g <- sample_gnp(100, 0.03) max_cliques(g)
# this usually contains cliques of size six g <- sample_gnp(100, 0.3) clique_num(g) cliques(g, min = 6) largest_cliques(g) # To have a bit less maximal cliques, about 100-200 usually g <- sample_gnp(100, 0.03) max_cliques(g)
Closeness centrality measures how many steps is required to access every other vertex from a given vertex.
closeness( graph, vids = V(graph), mode = c("out", "in", "all", "total"), weights = NULL, normalized = FALSE, cutoff = -1 )
closeness( graph, vids = V(graph), mode = c("out", "in", "all", "total"), weights = NULL, normalized = FALSE, cutoff = -1 )
graph |
The graph to analyze. |
vids |
The vertices for which closeness will be calculated. |
mode |
Character string, defined the types of the paths used for measuring the distance in directed graphs. “in” measures the paths to a vertex, “out” measures paths from a vertex, all uses undirected paths. This argument is ignored for undirected graphs. |
weights |
Optional positive weight vector for calculating weighted
closeness. If the graph has a |
normalized |
Logical scalar, whether to calculate the normalized closeness, i.e. the inverse average distance to all reachable vertices. The non-normalized closeness is the inverse of the sum of distances to all reachable vertices. |
cutoff |
The maximum path length to consider when calculating the closeness. If zero or negative then there is no such limit. |
The closeness centrality of a vertex is defined as the inverse of the sum of distances to all the other vertices in the graph:
If there is no (directed) path between vertex v
and i
, then
i
is omitted from the calculation. If no other vertices are reachable
from v
, then its closeness is returned as NaN.
cutoff
or smaller. This can be run for larger graphs, as the running
time is not quadratic (if cutoff
is small). If cutoff
is
negative (which is the default), then the function calculates the exact
closeness scores. Since igraph 1.6.0, a cutoff
value of zero is treated
literally, i.e. path with a length greater than zero are ignored.
Closeness centrality is meaningful only for connected graphs. In disconnected
graphs, consider using the harmonic centrality with
harmonic_centrality()
Numeric vector with the closeness values of all the vertices in
v
.
Gabor Csardi [email protected]
Freeman, L.C. (1979). Centrality in Social Networks I: Conceptual Clarification. Social Networks, 1, 215-239.
Centrality measures
alpha_centrality()
,
authority_score()
,
betweenness()
,
diversity()
,
eigen_centrality()
,
harmonic_centrality()
,
hits_scores()
,
page_rank()
,
power_centrality()
,
spectrum()
,
strength()
,
subgraph_centrality()
g <- make_ring(10) g2 <- make_star(10) closeness(g) closeness(g2, mode = "in") closeness(g2, mode = "out") closeness(g2, mode = "all")
g <- make_ring(10) g2 <- make_star(10) closeness(g) closeness(g2, mode = "in") closeness(g2, mode = "out") closeness(g2, mode = "all")
Community structure detection based on the betweenness of the edges in the network. This method is also known as the Girvan-Newman algorithm.
cluster_edge_betweenness( graph, weights = NULL, directed = TRUE, edge.betweenness = TRUE, merges = TRUE, bridges = TRUE, modularity = TRUE, membership = TRUE )
cluster_edge_betweenness( graph, weights = NULL, directed = TRUE, edge.betweenness = TRUE, merges = TRUE, bridges = TRUE, modularity = TRUE, membership = TRUE )
graph |
The graph to analyze. |
weights |
The weights of the edges. It must be a positive numeric vector,
|
directed |
Logical constant, whether to calculate directed edge betweenness for directed graphs. It is ignored for undirected graphs. |
edge.betweenness |
Logical constant, whether to return the edge betweenness of the edges at the time of their removal. |
merges |
Logical constant, whether to return the merge matrix
representing the hierarchical community structure of the network. This
argument is called |
bridges |
Logical constant, whether to return a list the edge removals which actually splitted a component of the graph. |
modularity |
Logical constant, whether to calculate the maximum modularity score, considering all possibly community structures along the edge-betweenness based edge removals. |
membership |
Logical constant, whether to calculate the membership vector corresponding to the highest possible modularity score. |
The idea behind this method is that the betweenness of the edges connecting two communities is typically high, as many of the shortest paths between vertices in separate communities pass through them. The algorithm successively removes edges with the highest betweenness, recalculating betweenness values after each removal. This way eventually the network splits into two components, then one of these components splits again, and so on, until all edges are removed. The resulting hierarhical partitioning of the vertices can be encoded as a dendrogram.
cluster_edge_betweenness()
returns various information collected
through the run of the algorithm. Specifically, removed.edges
contains
the edge IDs in order of the edges' removal; edge.betweenness
contains
the betweenness of each of these at the time of their removal; and
bridges
contains the IDs of edges whose removal caused a split.
cluster_edge_betweenness()
returns a
communities()
object, please see the communities()
manual page for details.
Gabor Csardi [email protected]
M Newman and M Girvan: Finding and evaluating community structure in networks, Physical Review E 69, 026113 (2004)
edge_betweenness()
for the definition and calculation
of the edge betweenness, cluster_walktrap()
,
cluster_fast_greedy()
,
cluster_leading_eigen()
for other community detection
methods.
See communities()
for extracting the results of the community
detection.
Community detection
as_membership()
,
cluster_fast_greedy()
,
cluster_fluid_communities()
,
cluster_infomap()
,
cluster_label_prop()
,
cluster_leading_eigen()
,
cluster_leiden()
,
cluster_louvain()
,
cluster_optimal()
,
cluster_spinglass()
,
cluster_walktrap()
,
compare()
,
groups()
,
make_clusters()
,
membership()
,
modularity.igraph()
,
plot_dendrogram()
,
split_join_distance()
,
voronoi_cells()
g <- sample_pa(100, m = 2, directed = FALSE) eb <- cluster_edge_betweenness(g) g <- make_full_graph(10) %du% make_full_graph(10) g <- add_edges(g, c(1, 11)) eb <- cluster_edge_betweenness(g) eb
g <- sample_pa(100, m = 2, directed = FALSE) eb <- cluster_edge_betweenness(g) g <- make_full_graph(10) %du% make_full_graph(10) g <- add_edges(g, c(1, 11)) eb <- cluster_edge_betweenness(g) eb
This function tries to find dense subgraph, also called communities in graphs via directly optimizing a modularity score.
cluster_fast_greedy( graph, merges = TRUE, modularity = TRUE, membership = TRUE, weights = NULL )
cluster_fast_greedy( graph, merges = TRUE, modularity = TRUE, membership = TRUE, weights = NULL )
graph |
The input graph. It must be undirected and must not have multi-edges. |
merges |
Logical scalar, whether to return the merge matrix. |
modularity |
Logical scalar, whether to return a vector containing the modularity after each merge. |
membership |
Logical scalar, whether to calculate the membership vector corresponding to the maximum modularity score, considering all possible community structures along the merges. |
weights |
The weights of the edges. It must be a positive numeric vector,
|
This function implements the fast greedy modularity optimization algorithm for finding community structure, see A Clauset, MEJ Newman, C Moore: Finding community structure in very large networks, http://www.arxiv.org/abs/cond-mat/0408187 for the details.
cluster_fast_greedy()
returns a communities()
object, please see the communities()
manual page for details.
Tamas Nepusz [email protected] and Gabor Csardi [email protected] for the R interface.
A Clauset, MEJ Newman, C Moore: Finding community structure in very large networks, http://www.arxiv.org/abs/cond-mat/0408187
communities()
for extracting the results.
See also cluster_walktrap()
,
cluster_spinglass()
,
cluster_leading_eigen()
and
cluster_edge_betweenness()
, cluster_louvain()
cluster_leiden()
for other methods.
Community detection
as_membership()
,
cluster_edge_betweenness()
,
cluster_fluid_communities()
,
cluster_infomap()
,
cluster_label_prop()
,
cluster_leading_eigen()
,
cluster_leiden()
,
cluster_louvain()
,
cluster_optimal()
,
cluster_spinglass()
,
cluster_walktrap()
,
compare()
,
groups()
,
make_clusters()
,
membership()
,
modularity.igraph()
,
plot_dendrogram()
,
split_join_distance()
,
voronoi_cells()
g <- make_full_graph(5) %du% make_full_graph(5) %du% make_full_graph(5) g <- add_edges(g, c(1, 6, 1, 11, 6, 11)) fc <- cluster_fast_greedy(g) membership(fc) sizes(fc)
g <- make_full_graph(5) %du% make_full_graph(5) %du% make_full_graph(5) g <- add_edges(g, c(1, 6, 1, 11, 6, 11)) fc <- cluster_fast_greedy(g) membership(fc) sizes(fc)
The algorithm detects communities based on the simple idea of several fluids interacting in a non-homogeneous environment (the graph topology), expanding and contracting based on their interaction and density.
cluster_fluid_communities(graph, no.of.communities)
cluster_fluid_communities(graph, no.of.communities)
graph |
The input graph. The graph must be simple and connected. Empty graphs are not supported as well as single vertex graphs. Edge directions are ignored. Weights are not considered. |
no.of.communities |
The number of communities to be found. Must be greater than 0 and fewer than number of vertices in the graph. |
cluster_fluid_communities()
returns a communities()
object, please see the communities()
manual page for details.
Ferran Parés
Parés F, Gasulla DG, et. al. (2018) Fluid Communities: A Competitive, Scalable and Diverse Community Detection Algorithm. In: Complex Networks & Their Applications VI: Proceedings of Complex Networks 2017 (The Sixth International Conference on Complex Networks and Their Applications), Springer, vol 689, p 229, doi: 10.1007/978-3-319-72150-7_19
See communities()
for extracting the membership,
modularity scores, etc. from the results.
Other community detection algorithms: cluster_walktrap()
,
cluster_spinglass()
,
cluster_leading_eigen()
,
cluster_edge_betweenness()
,
cluster_fast_greedy()
,
cluster_label_prop()
cluster_louvain()
,
cluster_leiden()
Community detection
as_membership()
,
cluster_edge_betweenness()
,
cluster_fast_greedy()
,
cluster_infomap()
,
cluster_label_prop()
,
cluster_leading_eigen()
,
cluster_leiden()
,
cluster_louvain()
,
cluster_optimal()
,
cluster_spinglass()
,
cluster_walktrap()
,
compare()
,
groups()
,
make_clusters()
,
membership()
,
modularity.igraph()
,
plot_dendrogram()
,
split_join_distance()
,
voronoi_cells()
g <- make_graph("Zachary") comms <- cluster_fluid_communities(g, 2)
g <- make_graph("Zachary") comms <- cluster_fluid_communities(g, 2)
Find community structure that minimizes the expected description length of a random walker trajectory. If the graph is directed, edge directions will be taken into account.
cluster_infomap( graph, e.weights = NULL, v.weights = NULL, nb.trials = 10, modularity = TRUE )
cluster_infomap( graph, e.weights = NULL, v.weights = NULL, nb.trials = 10, modularity = TRUE )
graph |
The input graph. Edge directions will be taken into account. |
e.weights |
If not |
v.weights |
If not |
nb.trials |
The number of attempts to partition the network (can be any integer value equal or larger than 1). |
modularity |
Logical scalar, whether to calculate the modularity score of the detected community structure. |
Please see the details of this method in the references given below.
cluster_infomap()
returns a communities()
object,
please see the communities()
manual page for details.
Martin Rosvall wrote the original C++ code. This was ported to be more igraph-like by Emmanuel Navarro. The R interface and some cosmetics was done by Gabor Csardi [email protected].
The original paper: M. Rosvall and C. T. Bergstrom, Maps of information flow reveal community structure in complex networks, PNAS 105, 1118 (2008) doi:10.1073/pnas.0706851105, https://arxiv.org/abs/0707.0609
A more detailed paper: M. Rosvall, D. Axelsson, and C. T. Bergstrom, The map equation, Eur. Phys. J. Special Topics 178, 13 (2009). doi:10.1140/epjst/e2010-01179-1, https://arxiv.org/abs/0906.1405.
Other community finding methods and communities()
.
Community detection
as_membership()
,
cluster_edge_betweenness()
,
cluster_fast_greedy()
,
cluster_fluid_communities()
,
cluster_label_prop()
,
cluster_leading_eigen()
,
cluster_leiden()
,
cluster_louvain()
,
cluster_optimal()
,
cluster_spinglass()
,
cluster_walktrap()
,
compare()
,
groups()
,
make_clusters()
,
membership()
,
modularity.igraph()
,
plot_dendrogram()
,
split_join_distance()
,
voronoi_cells()
## Zachary's karate club g <- make_graph("Zachary") imc <- cluster_infomap(g) membership(imc) communities(imc)
## Zachary's karate club g <- make_graph("Zachary") imc <- cluster_infomap(g) membership(imc) communities(imc)
This is a fast, nearly linear time algorithm for detecting community structure in networks. In works by labeling the vertices with unique labels and then updating the labels by majority voting in the neighborhood of the vertex.
cluster_label_prop( graph, weights = NULL, ..., mode = c("out", "in", "all"), initial = NULL, fixed = NULL )
cluster_label_prop( graph, weights = NULL, ..., mode = c("out", "in", "all"), initial = NULL, fixed = NULL )
graph |
The input graph. Note that the algorithm was originally
defined for undirected graphs. You are advised to set ‘mode’ to
|
weights |
The weights of the edges. It must be a positive numeric vector,
|
... |
These dots are for future extensions and must be empty. |
mode |
Logical, whether to consider edge directions for the label propagation, and if so, in which direction the labels should propagate. Ignored for undirected graphs. "all" means to ignore edge directions (even in directed graphs). "out" means to propagate labels along the natural direction of the edges. "in" means to propagate labels backwards (i.e. from head to tail). |
initial |
The initial state. If |
fixed |
Logical vector denoting which labels are fixed. Of course this makes sense only if you provided an initial state, otherwise this element will be ignored. Also note that vertices without labels cannot be fixed. |
This function implements the community detection method described in: 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). This version extends the original method by the ability to take edge weights into consideration and also by allowing some labels to be fixed.
From the abstract of the paper: “In our algorithm every node is initialized with a unique label and at every step each node adopts the label that most of its neighbors currently have. In this iterative process densely connected groups of nodes form a consensus on a unique label to form communities.”
cluster_label_prop()
returns a
communities()
object, please see the communities()
manual page for details.
Tamas Nepusz [email protected] for the C implementation, Gabor Csardi [email protected] for this manual page.
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)
communities()
for extracting the actual results.
cluster_fast_greedy()
, cluster_walktrap()
,
cluster_spinglass()
, cluster_louvain()
and
cluster_leiden()
for other community detection methods.
Community detection
as_membership()
,
cluster_edge_betweenness()
,
cluster_fast_greedy()
,
cluster_fluid_communities()
,
cluster_infomap()
,
cluster_leading_eigen()
,
cluster_leiden()
,
cluster_louvain()
,
cluster_optimal()
,
cluster_spinglass()
,
cluster_walktrap()
,
compare()
,
groups()
,
make_clusters()
,
membership()
,
modularity.igraph()
,
plot_dendrogram()
,
split_join_distance()
,
voronoi_cells()
g <- sample_gnp(10, 5 / 10) %du% sample_gnp(9, 5 / 9) g <- add_edges(g, c(1, 12)) cluster_label_prop(g)
g <- sample_gnp(10, 5 / 10) %du% sample_gnp(9, 5 / 9) g <- add_edges(g, c(1, 12)) cluster_label_prop(g)
This function tries to find densely connected subgraphs in a graph by calculating the leading non-negative eigenvector of the modularity matrix of the graph.
cluster_leading_eigen( graph, steps = -1, weights = NULL, start = NULL, options = arpack_defaults(), callback = NULL, extra = NULL, env = parent.frame() )
cluster_leading_eigen( graph, steps = -1, weights = NULL, start = NULL, options = arpack_defaults(), callback = NULL, extra = NULL, env = parent.frame() )
graph |
The input graph. Should be undirected as the method needs a symmetric matrix. |
steps |
The number of steps to take, this is actually the number of tries to make a step. It is not a particularly useful parameter. |
weights |
The weights of the edges. It must be a positive numeric vector,
|
start |
|
options |
A named list to override some ARPACK options. |
callback |
If not |
extra |
Additional argument to supply to the callback function. |
env |
The environment in which the callback function is evaluated. |
The function documented in these section implements the ‘leading eigenvector’ method developed by Mark Newman, see the reference below.
The heart of the method is the definition of the modularity matrix,
B
, which is B=A-P
, A
being the adjacency matrix of the
(undirected) network, and P
contains the probability that certain
edges are present according to the ‘configuration model’. In other
words, a P[i,j]
element of P
is the probability that there is
an edge between vertices i
and j
in a random network in which
the degrees of all vertices are the same as in the input graph.
The leading eigenvector method works by calculating the eigenvector of the modularity matrix for the largest positive eigenvalue and then separating vertices into two community based on the sign of the corresponding element in the eigenvector. If all elements in the eigenvector are of the same sign that means that the network has no underlying comuunity structure. Check Newman's paper to understand why this is a good method for detecting community structure.
cluster_leading_eigen()
returns a named list with the
following members:
membership |
The membership vector at the end of the algorithm, when no more splits are possible. |
merges |
The merges
matrix starting from the state described by the |
options |
Information about the underlying ARPACK computation, see
|
The callback
argument can be used to
supply a function that is called after each eigenvector calculation. The
following arguments are supplied to this function:
The actual membership vector, with zero-based indexing.
The community that the algorithm just tried to split, community numbering starts with zero here.
The eigenvalue belonging to the leading eigenvector the algorithm just found.
The leading eigenvector the algorithm just found.
An R function that can be used to multiple the actual modularity matrix with an arbitrary vector. Supply the vector as an argument to perform this multiplication. This function can be used with ARPACK.
The extra
argument that was passed to
cluster_leading_eigen()
.
The callback function should return a scalar number. If this number is non-zero, then the clustering is terminated.
Gabor Csardi [email protected]
MEJ Newman: Finding community structure using the eigenvectors of matrices, Physical Review E 74 036104, 2006.
modularity()
, cluster_walktrap()
,
cluster_edge_betweenness()
,
cluster_fast_greedy()
, as.dendrogram()
Community detection
as_membership()
,
cluster_edge_betweenness()
,
cluster_fast_greedy()
,
cluster_fluid_communities()
,
cluster_infomap()
,
cluster_label_prop()
,
cluster_leiden()
,
cluster_louvain()
,
cluster_optimal()
,
cluster_spinglass()
,
cluster_walktrap()
,
compare()
,
groups()
,
make_clusters()
,
membership()
,
modularity.igraph()
,
plot_dendrogram()
,
split_join_distance()
,
voronoi_cells()
g <- make_full_graph(5) %du% make_full_graph(5) %du% make_full_graph(5) g <- add_edges(g, c(1, 6, 1, 11, 6, 11)) lec <- cluster_leading_eigen(g) lec cluster_leading_eigen(g, start = membership(lec))
g <- make_full_graph(5) %du% make_full_graph(5) %du% make_full_graph(5) g <- add_edges(g, c(1, 6, 1, 11, 6, 11)) lec <- cluster_leading_eigen(g) lec cluster_leading_eigen(g, start = membership(lec))
The Leiden algorithm is similar to the Louvain algorithm,
cluster_louvain()
, but it is faster and yields higher quality
solutions. It can optimize both modularity and the Constant Potts Model,
which does not suffer from the resolution-limit (see preprint
http://arxiv.org/abs/1104.3083).
cluster_leiden( graph, objective_function = c("CPM", "modularity"), ..., weights = NULL, resolution = 1, resolution_parameter = deprecated(), beta = 0.01, initial_membership = NULL, n_iterations = 2, vertex_weights = NULL )
cluster_leiden( graph, objective_function = c("CPM", "modularity"), ..., weights = NULL, resolution = 1, resolution_parameter = deprecated(), beta = 0.01, initial_membership = NULL, n_iterations = 2, vertex_weights = NULL )
graph |
The input graph. It must be undirected. |
objective_function |
Whether to use the Constant Potts Model (CPM) or
modularity. Must be either |
... |
These dots are for future extensions and must be empty. |
weights |
The weights of the edges. It must be a positive numeric vector,
|
resolution |
The resolution parameter to use. Higher resolutions lead to more smaller communities, while lower resolutions lead to fewer larger communities. |
resolution_parameter |
|
beta |
Parameter affecting the randomness in the Leiden algorithm. This affects only the refinement step of the algorithm. |
initial_membership |
If 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_iterations |
the number of iterations to iterate the Leiden algorithm. Each iteration may improve the partition further. |
vertex_weights |
the vertex weights used in the Leiden algorithm.
If this is not provided, it will be automatically determined on the basis
of the |
The Leiden algorithm consists of three phases: (1) local moving of nodes, (2) refinement of the partition and (3) aggregation of the network based on the refined partition, using the non-refined partition to create an initial partition for the aggregate network. In the local move procedure in the Leiden algorithm, only nodes whose neighborhood has changed are visited. The refinement is done by restarting from a singleton partition within each cluster and gradually merging the subclusters. When aggregating, a single cluster may then be represented by several nodes (which are the subclusters identified in the refinement).
The Leiden algorithm provides several guarantees. The Leiden algorithm is typically iterated: the output of one iteration is used as the input for the next iteration. At each iteration all clusters are guaranteed to be connected and well-separated. After an iteration in which nothing has changed, all nodes and some parts are guaranteed to be locally optimally assigned. Finally, asymptotically, all subsets of all clusters are guaranteed to be locally optimally assigned. For more details, please see Traag, Waltman & van Eck (2019).
The objective function being optimized is
where is the total edge weight,
is the weight
of edge
,
is the so-called resolution
parameter,
is the node weight of node
,
is the cluster of node
and
if and
only if
and
otherwise. By setting
, the
degree of node
, and dividing
by
, you
effectively obtain an expression for modularity.
Hence, the standard modularity will be optimized when you supply the degrees
as vertex_weights
and by supplying as a resolution parameter
, with
the number of edges. If you do not
specify any
vertex_weights
, the correct vertex weights and scaling of
is determined automatically by the
objective_function
argument.
cluster_leiden()
returns a communities()
object, please see the communities()
manual page for details.
Vincent Traag
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, arXiv:1810.08473v3 [cs.SI]
See communities()
for extracting the membership,
modularity scores, etc. from the results.
Other community detection algorithms: cluster_walktrap()
,
cluster_spinglass()
,
cluster_leading_eigen()
,
cluster_edge_betweenness()
,
cluster_fast_greedy()
,
cluster_label_prop()
cluster_louvain()
cluster_fluid_communities()
cluster_infomap()
cluster_optimal()
cluster_walktrap()
Community detection
as_membership()
,
cluster_edge_betweenness()
,
cluster_fast_greedy()
,
cluster_fluid_communities()
,
cluster_infomap()
,
cluster_label_prop()
,
cluster_leading_eigen()
,
cluster_louvain()
,
cluster_optimal()
,
cluster_spinglass()
,
cluster_walktrap()
,
compare()
,
groups()
,
make_clusters()
,
membership()
,
modularity.igraph()
,
plot_dendrogram()
,
split_join_distance()
,
voronoi_cells()
g <- make_graph("Zachary") # By default CPM is used r <- quantile(strength(g))[2] / (gorder(g) - 1) # Set seed for sake of reproducibility set.seed(1) ldc <- cluster_leiden(g, resolution = r) print(ldc) plot(ldc, g)
g <- make_graph("Zachary") # By default CPM is used r <- quantile(strength(g))[2] / (gorder(g) - 1) # Set seed for sake of reproducibility set.seed(1) ldc <- cluster_leiden(g, resolution = r) print(ldc) plot(ldc, g)
This function implements the multi-level modularity optimization algorithm for finding community structure, see references below. It is based on the modularity measure and a hierarchical approach.
cluster_louvain(graph, weights = NULL, resolution = 1)
cluster_louvain(graph, weights = NULL, resolution = 1)
graph |
The input graph. It must be undirected. |
weights |
The weights of the edges. It must be a positive numeric vector,
|
resolution |
Optional resolution parameter that allows the user to adjust the resolution parameter of the modularity function that the algorithm uses internally. Lower values typically yield fewer, larger clusters. The original definition of modularity is recovered when the resolution parameter is set to 1. |
This function implements the multi-level modularity optimization algorithm for finding community structure, see VD Blondel, J-L Guillaume, R Lambiotte and E Lefebvre: Fast unfolding of community hierarchies in large networks, https://arxiv.org/abs/0803.0476 for the details.
It is based on the modularity measure and a hierarchical approach. Initially, each vertex is assigned to a community on its own. In every step, vertices are re-assigned to communities in a local, greedy way: each vertex is moved to the community with which it achieves the highest contribution to modularity. When no vertices can be reassigned, each community is considered a vertex on its own, and the process starts again with the merged communities. The process stops when there is only a single vertex left or when the modularity cannot be increased any more in a step. Since igraph 1.3, vertices are processed in a random order.
This function was contributed by Tom Gregorovic.
cluster_louvain()
returns a communities()
object, please see the communities()
manual page for details.
Tom Gregorovic, Tamas Nepusz [email protected]
Vincent D. Blondel, Jean-Loup Guillaume, Renaud Lambiotte, Etienne Lefebvre: Fast unfolding of communities in large networks. J. Stat. Mech. (2008) P10008
See communities()
for extracting the membership,
modularity scores, etc. from the results.
Other community detection algorithms: cluster_walktrap()
,
cluster_spinglass()
,
cluster_leading_eigen()
,
cluster_edge_betweenness()
,
cluster_fast_greedy()
,
cluster_label_prop()
cluster_leiden()
Community detection
as_membership()
,
cluster_edge_betweenness()
,
cluster_fast_greedy()
,
cluster_fluid_communities()
,
cluster_infomap()
,
cluster_label_prop()
,
cluster_leading_eigen()
,
cluster_leiden()
,
cluster_optimal()
,
cluster_spinglass()
,
cluster_walktrap()
,
compare()
,
groups()
,
make_clusters()
,
membership()
,
modularity.igraph()
,
plot_dendrogram()
,
split_join_distance()
,
voronoi_cells()
# This is so simple that we will have only one level g <- make_full_graph(5) %du% make_full_graph(5) %du% make_full_graph(5) g <- add_edges(g, c(1, 6, 1, 11, 6, 11)) cluster_louvain(g)
# This is so simple that we will have only one level g <- make_full_graph(5) %du% make_full_graph(5) %du% make_full_graph(5) g <- add_edges(g, c(1, 6, 1, 11, 6, 11)) cluster_louvain(g)
This function calculates the optimal community structure of a graph, by maximizing the modularity measure over all possible partitions.
cluster_optimal(graph, weights = NULL)
cluster_optimal(graph, weights = NULL)
graph |
The input graph. It may be undirected or directed. |
weights |
The weights of the edges. It must be a positive numeric
vector, |
This function calculates the optimal community structure for a graph, in terms of maximal modularity score.
The calculation is done by transforming the modularity maximization into an integer programming problem, and then calling the GLPK library to solve that. Please the reference below for details.
Note that modularity optimization is an NP-complete problem, and all known algorithms for it have exponential time complexity. This means that you probably don't want to run this function on larger graphs. Graphs with up to fifty vertices should be fine, graphs with a couple of hundred vertices might be possible.
cluster_optimal()
returns a communities()
object,
please see the communities()
manual page for details.
## Zachary's karate club g <- make_graph("Zachary") ## We put everything into a big 'try' block, in case ## igraph was compiled without GLPK support ## The calculation only takes a couple of seconds oc <- cluster_optimal(g) ## Double check the result print(modularity(oc)) print(modularity(g, membership(oc))) ## Compare to the greedy optimizer fc <- cluster_fast_greedy(g) print(modularity(fc))
Gabor Csardi [email protected]
Ulrik Brandes, Daniel Delling, Marco Gaertler, Robert Gorke, Martin Hoefer, Zoran Nikoloski, Dorothea Wagner: On Modularity Clustering, IEEE Transactions on Knowledge and Data Engineering 20(2):172-188, 2008.
communities()
for the documentation of the result,
modularity()
. See also cluster_fast_greedy()
for a
fast greedy optimizer.
Community detection
as_membership()
,
cluster_edge_betweenness()
,
cluster_fast_greedy()
,
cluster_fluid_communities()
,
cluster_infomap()
,
cluster_label_prop()
,
cluster_leading_eigen()
,
cluster_leiden()
,
cluster_louvain()
,
cluster_spinglass()
,
cluster_walktrap()
,
compare()
,
groups()
,
make_clusters()
,
membership()
,
modularity.igraph()
,
plot_dendrogram()
,
split_join_distance()
,
voronoi_cells()
This function tries to find communities in graphs via a spin-glass model and simulated annealing.
cluster_spinglass( graph, weights = NULL, vertex = NULL, spins = 25, parupdate = FALSE, start.temp = 1, stop.temp = 0.01, cool.fact = 0.99, update.rule = c("config", "random", "simple"), gamma = 1, implementation = c("orig", "neg"), gamma.minus = 1 )
cluster_spinglass( graph, weights = NULL, vertex = NULL, spins = 25, parupdate = FALSE, start.temp = 1, stop.temp = 0.01, cool.fact = 0.99, update.rule = c("config", "random", "simple"), gamma = 1, implementation = c("orig", "neg"), gamma.minus = 1 )
graph |
The input graph. Edge directions are ignored in directed graphs. |
weights |
The weights of the edges. It must be a positive numeric vector,
|
vertex |
This parameter can be used to calculate the community of a given vertex without calculating all communities. Note that if this argument is present then some other arguments are ignored. |
spins |
Integer constant, 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. |
parupdate |
Logical constant, whether to update the spins of the
vertices in parallel (synchronously) or not. This argument is ignored if the
second form of the function is used (i.e. the ‘ |
start.temp |
Real constant, the start temperature. This argument is
ignored if the second form of the function is used (i.e. the
‘ |
stop.temp |
Real constant, the stop temperature. The simulation
terminates if the temperature lowers below this level. This argument is
ignored if the second form of the function is used (i.e. the
‘ |
cool.fact |
Cooling factor for the simulated annealing. This argument
is ignored if the second form of the function is used (i.e. the
‘ |
update.rule |
Character constant giving the ‘null-model’ of the simulation. Possible values: “simple” and “config”. “simple” uses a random graph with the same number of edges as the baseline probability and “config” uses a random graph with the same vertex degrees as the input graph. |
gamma |
Real constant, the gamma argument of the algorithm. This specifies the balance between the importance of present and non-present edges in a community. Roughly, a comunity is a set of vertices having many edges inside the community and few edges outside the community. The default 1.0 value makes existing and non-existing links equally important. Smaller values make the existing links, greater values the missing links more important. |
implementation |
Character scalar. Currently igraph contains two implementations for the Spin-glass community finding algorithm. The faster original implementation is the default. The other implementation, that takes into account negative weights, can be chosen by supplying ‘neg’ here. |
gamma.minus |
Real constant, the gamma.minus parameter of the algorithm. This specifies the balance between the importance of present and non-present negative weighted edges in a community. Smaller values of gamma.minus, leads to communities with lesser negative intra-connectivity. If this argument is set to zero, the algorithm reduces to a graph coloring algorithm, using the number of spins as the number of colors. This argument is ignored if the ‘orig’ implementation is chosen. |
This function tries to find communities in a graph. A community is a set of nodes with many edges inside the community and few edges between outside it (i.e. between the community itself and the rest of the graph.)
This idea is reversed for edges having a negative weight, i.e. few negative edges inside a community and many negative edges between communities. Note that only the ‘neg’ implementation supports negative edge weights.
The spinglass.cummunity
function can solve two problems related to
community detection. If the vertex
argument is not given (or it is
NULL
), then the regular community detection problem is solved
(approximately), i.e. partitioning the vertices into communities, by
optimizing the an energy function.
If the vertex
argument is given and it is not NULL
, then it
must be a vertex id, and the same energy function is used to find the
community of the the given vertex. See also the examples below.
If the vertex
argument is not given, i.e. the first form is
used then a cluster_spinglass()
returns a
communities()
object.
If the vertex
argument is present, i.e. the second form is used then a
named list is returned with the following components:
community |
Numeric vector giving the ids of the vertices in the same
community as |
cohesion |
The cohesion score of the result, see references. |
adhesion |
The adhesion score of the result, see references. |
inner.links |
The number of edges within the community
of |
outer.links |
The number of edges between the
community of |
Jorg Reichardt for the original code and Gabor Csardi [email protected] for the igraph glue code.
Changes to the original function for including the possibility of negative ties were implemented by Vincent Traag (https://www.traag.net/).
J. Reichardt and S. Bornholdt: Statistical Mechanics of Community Detection, Phys. Rev. E, 74, 016110 (2006), https://arxiv.org/abs/cond-mat/0603718
M. E. J. Newman and M. Girvan: Finding and evaluating community structure in networks, Phys. Rev. E 69, 026113 (2004)
V.A. Traag and Jeroen Bruggeman: Community detection in networks with positive and negative links, https://arxiv.org/abs/0811.2329 (2008).
Community detection
as_membership()
,
cluster_edge_betweenness()
,
cluster_fast_greedy()
,
cluster_fluid_communities()
,
cluster_infomap()
,
cluster_label_prop()
,
cluster_leading_eigen()
,
cluster_leiden()
,
cluster_louvain()
,
cluster_optimal()
,
cluster_walktrap()
,
compare()
,
groups()
,
make_clusters()
,
membership()
,
modularity.igraph()
,
plot_dendrogram()
,
split_join_distance()
,
voronoi_cells()
g <- sample_gnp(10, 5 / 10) %du% sample_gnp(9, 5 / 9) g <- add_edges(g, c(1, 12)) g <- induced_subgraph(g, subcomponent(g, 1)) cluster_spinglass(g, spins = 2) cluster_spinglass(g, vertex = 1)
g <- sample_gnp(10, 5 / 10) %du% sample_gnp(9, 5 / 9) g <- add_edges(g, c(1, 12)) g <- induced_subgraph(g, subcomponent(g, 1)) cluster_spinglass(g, spins = 2) cluster_spinglass(g, vertex = 1)
This function tries to find densely connected subgraphs, also called communities in a graph via random walks. The idea is that short random walks tend to stay in the same community.
cluster_walktrap( graph, weights = NULL, steps = 4, merges = TRUE, modularity = TRUE, membership = TRUE )
cluster_walktrap( graph, weights = NULL, steps = 4, merges = TRUE, modularity = TRUE, membership = TRUE )
graph |
The input graph. Edge directions are ignored in directed graphs. |
weights |
The weights of the edges. It must be a positive numeric vector,
|
steps |
The length of the random walks to perform. |
merges |
Logical scalar, whether to include the merge matrix in the result. |
modularity |
Logical scalar, whether to include the vector of the
modularity scores in the result. If the |
membership |
Logical scalar, whether to calculate the membership vector for the split corresponding to the highest modularity value. |
This function is the implementation of the Walktrap community finding algorithm, see Pascal Pons, Matthieu Latapy: Computing communities in large networks using random walks, https://arxiv.org/abs/physics/0512106
cluster_walktrap()
returns a communities()
object, please see the communities()
manual page for details.
Pascal Pons (http://psl.pons.free.fr/) and Gabor Csardi [email protected] for the R and igraph interface
Pascal Pons, Matthieu Latapy: Computing communities in large networks using random walks, https://arxiv.org/abs/physics/0512106
See communities()
on getting the actual membership
vector, merge matrix, modularity score, etc.
modularity()
and cluster_fast_greedy()
,
cluster_spinglass()
,
cluster_leading_eigen()
,
cluster_edge_betweenness()
, cluster_louvain()
,
and cluster_leiden()
for other community detection
methods.
Community detection
as_membership()
,
cluster_edge_betweenness()
,
cluster_fast_greedy()
,
cluster_fluid_communities()
,
cluster_infomap()
,
cluster_label_prop()
,
cluster_leading_eigen()
,
cluster_leiden()
,
cluster_louvain()
,
cluster_optimal()
,
cluster_spinglass()
,
compare()
,
groups()
,
make_clusters()
,
membership()
,
modularity.igraph()
,
plot_dendrogram()
,
split_join_distance()
,
voronoi_cells()
g <- make_full_graph(5) %du% make_full_graph(5) %du% make_full_graph(5) g <- add_edges(g, c(1, 6, 1, 11, 6, 11)) cluster_walktrap(g)
g <- make_full_graph(5) %du% make_full_graph(5) %du% make_full_graph(5) g <- add_edges(g, c(1, 6, 1, 11, 6, 11)) cluster_walktrap(g)
Two vertices are cocited if there is another vertex citing both of them.
cocitation()
simply counts how many types two vertices are cocited. The
bibliographic coupling of two vertices is the number of other vertices they
both cite, bibcoupling()
calculates this.
cocitation(graph, v = V(graph)) bibcoupling(graph, v = V(graph))
cocitation(graph, v = V(graph)) bibcoupling(graph, v = V(graph))
graph |
The graph object to analyze |
v |
Vertex sequence or numeric vector, the vertex ids for which the cocitation or bibliographic coupling values we want to calculate. The default is all vertices. |
cocitation()
calculates the cocitation counts for the vertices in the
v
argument and all vertices in the graph.
bibcoupling()
calculates the bibliographic coupling for vertices in
v
and all vertices in the graph.
Calculating the cocitation or bibliographic coupling for only one vertex costs the same amount of computation as for all vertices. This might change in the future.
A numeric matrix with length(v)
lines and
vcount(graph)
columns. Element (i,j)
contains the cocitation
or bibliographic coupling for vertices v[i]
and j
.
Gabor Csardi [email protected]
Other cocitation:
similarity()
g <- make_kautz_graph(2, 3) cocitation(g) bibcoupling(g)
g <- make_kautz_graph(2, 3) cocitation(g) bibcoupling(g)
Calculates cohesive blocks for objects of class igraph
.
cohesive_blocks(graph, labels = TRUE) ## S3 method for class 'cohesiveBlocks' length(x) blocks(blocks) graphs_from_cohesive_blocks(blocks, graph) ## S3 method for class 'cohesiveBlocks' cohesion(x, ...) hierarchy(blocks) parent(blocks) ## S3 method for class 'cohesiveBlocks' print(x, ...) ## S3 method for class 'cohesiveBlocks' summary(object, ...) ## S3 method for class 'cohesiveBlocks' plot( x, y, colbar = rainbow(max(cohesion(x)) + 1), col = colbar[max_cohesion(x) + 1], mark.groups = blocks(x)[-1], ... ) plot_hierarchy( blocks, layout = layout_as_tree(hierarchy(blocks), root = 1), ... ) export_pajek(blocks, graph, file, project.file = TRUE) max_cohesion(blocks)
cohesive_blocks(graph, labels = TRUE) ## S3 method for class 'cohesiveBlocks' length(x) blocks(blocks) graphs_from_cohesive_blocks(blocks, graph) ## S3 method for class 'cohesiveBlocks' cohesion(x, ...) hierarchy(blocks) parent(blocks) ## S3 method for class 'cohesiveBlocks' print(x, ...) ## S3 method for class 'cohesiveBlocks' summary(object, ...) ## S3 method for class 'cohesiveBlocks' plot( x, y, colbar = rainbow(max(cohesion(x)) + 1), col = colbar[max_cohesion(x) + 1], mark.groups = blocks(x)[-1], ... ) plot_hierarchy( blocks, layout = layout_as_tree(hierarchy(blocks), root = 1), ... ) export_pajek(blocks, graph, file, project.file = TRUE) max_cohesion(blocks)
graph |
For For |
labels |
Logical scalar, whether to add the vertex labels to the result object. These labels can be then used when reporting and plotting the cohesive blocks. |
blocks , x , object
|
A |
... |
Additional arguments. |
y |
The graph whose cohesive blocks are supplied in the |
colbar |
Color bar for the vertex colors. Its length should be at least
|
col |
A vector of vertex colors, in any of the usual formats. (Symbolic
color names (e.g. ‘red’, ‘blue’, etc.) , RGB colors (e.g.
‘#FF9900FF’), integer numbers referring to the current palette. By
default the given |
mark.groups |
A list of vertex sets to mark on the plot by circling them. By default all cohesive blocks are marked, except the one corresponding to the all vertices. |
layout |
The layout of a plot, it is simply passed on to
|
file |
Defines the file (or connection) the Pajek file is written to. If the If the See also details below. |
project.file |
Logical scalar, whether to create a single Pajek project file containing all the data, or to create separated files for each item. See details below. |
Cohesive blocking is a method of determining hierarchical subsets of graph
vertices based on their structural cohesion (or vertex connectivity). For a
given graph , a subset of its vertices
is said
to be maximally
-cohesive if there is no superset of
with
vertex connectivity greater than or equal to
. Cohesive blocking is a
process through which, given a
-cohesive set of vertices, maximally
-cohesive subsets are recursively identified with
. Thus a
hierarchy of vertex subsets is found, with the entire graph
at its
root.
The function cohesive_blocks()
implements cohesive blocking. It
returns a cohesiveBlocks
object. cohesiveBlocks
should be
handled as an opaque class, i.e. its internal structure should not be
accessed directly, but through the functions listed here.
The function length
can be used on cohesiveBlocks
objects and
it gives the number of blocks.
The function blocks()
returns the actual blocks stored in the
cohesiveBlocks
object. They are returned in a list of numeric
vectors, each containing vertex ids.
The function graphs_from_cohesive_blocks()
is similar, but returns the blocks as
(induced) subgraphs of the input graph. The various (graph, vertex and edge)
attributes are kept in the subgraph.
The function cohesion()
returns a numeric vector, the cohesion of the
different blocks. The order of the blocks is the same as for the
blocks()
and graphs_from_cohesive_blocks()
functions.
The block hierarchy can be queried using the hierarchy()
function. It
returns an igraph graph, its vertex ids are ordered according the order of
the blocks in the blocks()
and graphs_from_cohesive_blocks()
, cohesion()
,
etc. functions.
parent()
gives the parent vertex of each block, in the block hierarchy,
for the root vertex it gives 0.
plot_hierarchy()
plots the hierarchy tree of the cohesive blocks on the
active graphics device, by calling igraph.plot
.
The export_pajek()
function can be used to export the graph and its
cohesive blocks in Pajek format. It can either export a single Pajek project
file with all the information, or a set of files, depending on its
project.file
argument. If project.file
is TRUE
, then
the following information is written to the file (or connection) given in
the file
argument: (1) the input graph, together with its attributes,
see write_graph()
for details; (2) the hierarchy graph; and (3)
one binary partition for each cohesive block. If project.file
is
FALSE
, then the file
argument must be a character scalar and
it is used as the base name for the generated files. If file
is
‘basename’, then the following files are created: (1)
‘basename.net’ for the original graph; (2)
‘basename_hierarchy.net’ for the hierarchy graph; (3)
‘basename_block_x.net’ for each cohesive block, where ‘x’ is
the number of the block, starting with one.
max_cohesion()
returns the maximal cohesion of each vertex, i.e. the
cohesion of the most cohesive block of the vertex.
The generic function summary()
works on cohesiveBlocks
objects
and it prints a one line summary to the terminal.
The generic function print()
is also defined on cohesiveBlocks
objects and it is invoked automatically if the name of the
cohesiveBlocks
object is typed in. It produces an output like this:
Cohesive block structure: B-1 c 1, n 23 '- B-2 c 2, n 14 oooooooo.. .o......oo ooo '- B-4 c 5, n 7 ooooooo... .......... ... '- B-3 c 2, n 10 ......o.oo o.oooooo.. ... '- B-5 c 3, n 4 ......o.oo o......... ...
The left part shows the block structure, in this case for five blocks. The first block always corresponds to the whole graph, even if its cohesion is zero. Then cohesion of the block and the number of vertices in the block are shown. The last part is only printed if the display is wide enough and shows the vertices in the blocks, ordered by vertex ids. ‘o’ means that the vertex is included, a dot means that it is not, and the vertices are shown in groups of ten.
The generic function plot()
plots the graph, showing one or more
cohesive blocks in it.
cohesive_blocks()
returns a cohesiveBlocks
object.
blocks()
returns a list of numeric vectors, containing vertex ids.
graphs_from_cohesive_blocks()
returns a list of igraph graphs, corresponding to the
cohesive blocks.
cohesion()
returns a numeric vector, the cohesion of each block.
hierarchy()
returns an igraph graph, the representation of the cohesive
block hierarchy.
parent()
returns a numeric vector giving the parent block of each
cohesive block, in the block hierarchy. The block at the root of the
hierarchy has no parent and 0
is returned for it.
plot_hierarchy()
, plot()
and export_pajek()
return NULL
,
invisibly.
max_cohesion()
returns a numeric vector with one entry for each vertex,
giving the cohesion of its most cohesive block.
print()
and summary()
return the cohesiveBlocks
object
itself, invisibly.
length
returns a numeric scalar, the number of blocks.
Gabor Csardi [email protected] for the current implementation, Peter McMahan (https://socialsciences.uchicago.edu/news/alumni-profile-peter-mcmahan-phd17-sociology) wrote the first version in R.
J. Moody and D. R. White. Structural cohesion and embeddedness: A hierarchical concept of social groups. American Sociological Review, 68(1):103–127, Feb 2003, doi:10.2307/3088904.
## The graph from the Moody-White paper mw <- graph_from_literal( 1 - 2:3:4:5:6, 2 - 3:4:5:7, 3 - 4:6:7, 4 - 5:6:7, 5 - 6:7:21, 6 - 7, 7 - 8:11:14:19, 8 - 9:11:14, 9 - 10, 10 - 12:13, 11 - 12:14, 12 - 16, 13 - 16, 14 - 15, 15 - 16, 17 - 18:19:20, 18 - 20:21, 19 - 20:22:23, 20 - 21, 21 - 22:23, 22 - 23 ) mwBlocks <- cohesive_blocks(mw) # Inspect block membership and cohesion mwBlocks blocks(mwBlocks) cohesion(mwBlocks) # Save results in a Pajek file file <- tempfile(fileext = ".paj") export_pajek(mwBlocks, mw, file = file) if (!interactive()) { unlink(file) } # Plot the results plot(mwBlocks, mw) ## The science camp network camp <- graph_from_literal( Harry:Steve:Don:Bert - Harry:Steve:Don:Bert, Pam:Brazey:Carol:Pat - Pam:Brazey:Carol:Pat, Holly - Carol:Pat:Pam:Jennie:Bill, Bill - Pauline:Michael:Lee:Holly, Pauline - Bill:Jennie:Ann, Jennie - Holly:Michael:Lee:Ann:Pauline, Michael - Bill:Jennie:Ann:Lee:John, Ann - Michael:Jennie:Pauline, Lee - Michael:Bill:Jennie, Gery - Pat:Steve:Russ:John, Russ - Steve:Bert:Gery:John, John - Gery:Russ:Michael ) campBlocks <- cohesive_blocks(camp) campBlocks plot(campBlocks, camp, vertex.label = V(camp)$name, margin = -0.2, vertex.shape = "rectangle", vertex.size = 24, vertex.size2 = 8, mark.border = 1, colbar = c(NA, NA, "cyan", "orange") )
## The graph from the Moody-White paper mw <- graph_from_literal( 1 - 2:3:4:5:6, 2 - 3:4:5:7, 3 - 4:6:7, 4 - 5:6:7, 5 - 6:7:21, 6 - 7, 7 - 8:11:14:19, 8 - 9:11:14, 9 - 10, 10 - 12:13, 11 - 12:14, 12 - 16, 13 - 16, 14 - 15, 15 - 16, 17 - 18:19:20, 18 - 20:21, 19 - 20:22:23, 20 - 21, 21 - 22:23, 22 - 23 ) mwBlocks <- cohesive_blocks(mw) # Inspect block membership and cohesion mwBlocks blocks(mwBlocks) cohesion(mwBlocks) # Save results in a Pajek file file <- tempfile(fileext = ".paj") export_pajek(mwBlocks, mw, file = file) if (!interactive()) { unlink(file) } # Plot the results plot(mwBlocks, mw) ## The science camp network camp <- graph_from_literal( Harry:Steve:Don:Bert - Harry:Steve:Don:Bert, Pam:Brazey:Carol:Pat - Pam:Brazey:Carol:Pat, Holly - Carol:Pat:Pam:Jennie:Bill, Bill - Pauline:Michael:Lee:Holly, Pauline - Bill:Jennie:Ann, Jennie - Holly:Michael:Lee:Ann:Pauline, Michael - Bill:Jennie:Ann:Lee:John, Ann - Michael:Jennie:Pauline, Lee - Michael:Bill:Jennie, Gery - Pat:Steve:Russ:John, Russ - Steve:Bert:Gery:John, John - Gery:Russ:Michael ) campBlocks <- cohesive_blocks(camp) campBlocks plot(campBlocks, camp, vertex.label = V(camp)$name, margin = -0.2, vertex.shape = "rectangle", vertex.size = 24, vertex.size2 = 8, mark.border = 1, colbar = c(NA, NA, "cyan", "orange") )
This function assesses the distance between two community structures.
compare( comm1, comm2, method = c("vi", "nmi", "split.join", "rand", "adjusted.rand") )
compare( comm1, comm2, method = c("vi", "nmi", "split.join", "rand", "adjusted.rand") )
comm1 |
A |
comm2 |
A |
method |
Character scalar, the comparison method to use. Possible values: ‘vi’ is the variation of information (VI) metric of Meila (2003), ‘nmi’ is the normalized mutual information measure proposed by Danon et al. (2005), ‘split.join’ is the split-join distance of can Dongen (2000), ‘rand’ is the Rand index of Rand (1971), ‘adjusted.rand’ is the adjusted Rand index by Hubert and Arabie (1985). |
A real number.
Tamas Nepusz [email protected]
Meila M: Comparing clusterings by the variation of information. In: Scholkopf B, Warmuth MK (eds.). Learning Theory and Kernel Machines: 16th Annual Conference on Computational Learning Theory and 7th Kernel Workshop, COLT/Kernel 2003, Washington, DC, USA. Lecture Notes in Computer Science, vol. 2777, Springer, 2003. ISBN: 978-3-540-40720-1.
Danon L, Diaz-Guilera A, Duch J, Arenas A: Comparing community structure identification. J Stat Mech P09008, 2005.
van Dongen S: Performance criteria for graph clustering and Markov cluster experiments. Technical Report INS-R0012, National Research Institute for Mathematics and Computer Science in the Netherlands, Amsterdam, May 2000.
Rand WM: Objective criteria for the evaluation of clustering methods. J Am Stat Assoc 66(336):846-850, 1971.
Hubert L and Arabie P: Comparing partitions. Journal of Classification 2:193-218, 1985.
Community detection
as_membership()
,
cluster_edge_betweenness()
,
cluster_fast_greedy()
,
cluster_fluid_communities()
,
cluster_infomap()
,
cluster_label_prop()
,
cluster_leading_eigen()
,
cluster_leiden()
,
cluster_louvain()
,
cluster_optimal()
,
cluster_spinglass()
,
cluster_walktrap()
,
groups()
,
make_clusters()
,
membership()
,
modularity.igraph()
,
plot_dendrogram()
,
split_join_distance()
,
voronoi_cells()
g <- make_graph("Zachary") sg <- cluster_spinglass(g) le <- cluster_leading_eigen(g) compare(sg, le, method = "rand") compare(membership(sg), membership(le))
g <- make_graph("Zachary") sg <- cluster_spinglass(g) le <- cluster_leading_eigen(g) compare(sg, le, method = "rand") compare(membership(sg), membership(le))
A complementer graph contains all edges that were not present in the input graph.
complementer(graph, loops = FALSE)
complementer(graph, loops = FALSE)
graph |
The input graph, can be directed or undirected. |
loops |
Logical constant, whether to generate loop edges. |
complementer()
creates the complementer of a graph. Only edges
which are not present in the original graph will be included in the
new graph.
complementer()
keeps graph and vertex attriubutes, edge
attributes are lost.
A new graph object.
Gabor Csardi [email protected]
Other functions for manipulating graph structure:
+.igraph()
,
add_edges()
,
add_vertices()
,
compose()
,
connect()
,
contract()
,
delete_edges()
,
delete_vertices()
,
difference()
,
difference.igraph()
,
disjoint_union()
,
edge()
,
igraph-minus
,
intersection()
,
intersection.igraph()
,
path()
,
permute()
,
rep.igraph()
,
reverse_edges()
,
simplify()
,
union()
,
union.igraph()
,
vertex()
## Complementer of a ring g <- make_ring(10) complementer(g) ## A graph and its complementer give together the full graph g <- make_ring(10) gc <- complementer(g) gu <- union(g, gc) gu graph.isomorphic(gu, make_full_graph(vcount(g)))
## Complementer of a ring g <- make_ring(10) complementer(g) ## A graph and its complementer give together the full graph g <- make_ring(10) gc <- complementer(g) gu <- union(g, gc) gu graph.isomorphic(gu, make_full_graph(vcount(g)))
Calculate the maximal (weakly or strongly) connected components of a graph
component_distribution(graph, cumulative = FALSE, mul.size = FALSE, ...) largest_component(graph, mode = c("weak", "strong")) components(graph, mode = c("weak", "strong")) is_connected(graph, mode = c("weak", "strong")) count_components(graph, mode = c("weak", "strong"))
component_distribution(graph, cumulative = FALSE, mul.size = FALSE, ...) largest_component(graph, mode = c("weak", "strong")) components(graph, mode = c("weak", "strong")) is_connected(graph, mode = c("weak", "strong")) count_components(graph, mode = c("weak", "strong"))
graph |
The graph to analyze. |
cumulative |
Logical, if TRUE the cumulative distirubution (relative frequency) is calculated. |
mul.size |
Logical. If TRUE the relative frequencies will be multiplied by the cluster sizes. |
... |
Additional attributes to pass to |
mode |
Character string, either “weak” or “strong”. For directed graphs “weak” implies weakly, “strong” strongly connected components to search. It is ignored for undirected graphs. |
is_connected()
decides whether the graph is weakly or strongly
connected. The null graph is considered disconnected.
components()
finds the maximal (weakly or strongly) connected components
of a graph.
count_components()
does almost the same as components()
but returns only
the number of clusters found instead of returning the actual clusters.
component_distribution()
creates a histogram for the maximal connected
component sizes.
largest_component()
returns the largest connected component of a graph. For
directed graphs, optionally the largest weakly or strongly connected component.
In case of a tie, the first component by vertex ID order is returned. Vertex
IDs from the original graph are not retained in the returned graph.
The weakly connected components are found by a simple breadth-first search. The strongly connected components are implemented by two consecutive depth-first searches.
For is_connected()
a logical constant.
For components()
a named list with three components:
membership |
numeric vector giving the cluster id to which each vertex belongs. |
csize |
numeric vector giving the sizes of the clusters. |
no |
numeric constant, the number of clusters. |
For count_components()
an integer constant is returned.
For component_distribution()
a numeric vector with the relative
frequencies. The length of the vector is the size of the largest component
plus one. Note that (for currently unknown reasons) the first element of the
vector is the number of clusters of size zero, so this is always zero.
For largest_component()
the largest connected component of the graph.
Gabor Csardi [email protected]
decompose()
, subcomponent()
, groups()
Connected components
articulation_points()
,
biconnected_components()
,
decompose()
,
is_biconnected()
Other structural.properties:
bfs()
,
connect()
,
constraint()
,
coreness()
,
degree()
,
dfs()
,
distance_table()
,
edge_density()
,
feedback_arc_set()
,
girth()
,
is_acyclic()
,
is_dag()
,
is_matching()
,
k_shortest_paths()
,
knn()
,
reciprocity()
,
subcomponent()
,
subgraph()
,
topo_sort()
,
transitivity()
,
unfold_tree()
,
which_multiple()
,
which_mutual()
g <- sample_gnp(20, 1 / 20) clu <- components(g) groups(clu) largest_component(g)
g <- sample_gnp(20, 1 / 20) clu <- components(g) groups(clu) largest_component(g)
This is a layout modifier function, and it can be used to calculate the layout separately for each component of the graph.
component_wise(merge_method = "dla")
component_wise(merge_method = "dla")
merge_method |
Merging algorithm, the |
Other layout modifiers:
normalize()
Other graph layouts:
add_layout_()
,
layout_()
,
layout_as_bipartite()
,
layout_as_star()
,
layout_as_tree()
,
layout_in_circle()
,
layout_nicely()
,
layout_on_grid()
,
layout_on_sphere()
,
layout_randomly()
,
layout_with_dh()
,
layout_with_fr()
,
layout_with_gem()
,
layout_with_graphopt()
,
layout_with_kk()
,
layout_with_lgl()
,
layout_with_mds()
,
layout_with_sugiyama()
,
merge_coords()
,
norm_coords()
,
normalize()
g <- make_ring(10) + make_ring(10) g %>% add_layout_(in_circle(), component_wise()) %>% plot()
g <- make_ring(10) + make_ring(10) g %>% add_layout_(in_circle(), component_wise()) %>% plot()
Relational composition of two graph.
compose(g1, g2, byname = "auto")
compose(g1, g2, byname = "auto")
g1 |
The first input graph. |
g2 |
The second input graph. |
byname |
A logical scalar, or the character scalar |
compose()
creates the relational composition of two graphs. The
new graph will contain an (a,b) edge only if there is a vertex c, such that
edge (a,c) is included in the first graph and (c,b) is included in the
second graph. The corresponding operator is %c%
.
The function gives an error if one of the input graphs is directed and the other is undirected.
If the byname
argument is TRUE
(or auto
and the graphs
are all named), then the operation is performed based on symbolic vertex
names. Otherwise numeric vertex ids are used.
compose()
keeps the attributes of both graphs. All graph, vertex
and edge attributes are copied to the result. If an attribute is present in
multiple graphs and would result a name clash, then this attribute is
renamed by adding suffixes: _1, _2, etc.
The name
vertex attribute is treated specially if the operation is
performed based on symbolic vertex names. In this case name
must be
present in both graphs, and it is not renamed in the result graph.
Note that an edge in the result graph corresponds to two edges in the input, one in the first graph, one in the second. This mapping is not injective and several edges in the result might correspond to the same edge in the first (and/or the second) graph. The edge attributes in the result graph are updated accordingly.
Also note that the function may generate multigraphs, if there are more than
one way to find edges (a,b) in g1 and (b,c) in g2 for an edge (a,c) in the
result. See simplify()
if you want to get rid of the multiple
edges.
The function may create loop edges, if edges (a,b) and (b,a) are present in
g1 and g2, respectively, then (a,a) is included in the result. See
simplify()
if you want to get rid of the self-loops.
A new graph object.
Gabor Csardi [email protected]
Other functions for manipulating graph structure:
+.igraph()
,
add_edges()
,
add_vertices()
,
complementer()
,
connect()
,
contract()
,
delete_edges()
,
delete_vertices()
,
difference()
,
difference.igraph()
,
disjoint_union()
,
edge()
,
igraph-minus
,
intersection()
,
intersection.igraph()
,
path()
,
permute()
,
rep.igraph()
,
reverse_edges()
,
simplify()
,
union()
,
union.igraph()
,
vertex()
g1 <- make_ring(10) g2 <- make_star(10, mode = "undirected") gc <- compose(g1, g2) print_all(gc) print_all(simplify(gc))
g1 <- make_ring(10) g2 <- make_star(10, mode = "undirected") gc <- compose(g1, g2) print_all(gc) print_all(simplify(gc))
These functions find the vertices not farther than a given limit from
another fixed vertex, these are called the neighborhood of the vertex.
Note that ego()
and neighborhood()
,
ego_size()
and neighborhood_size()
,
make_ego_graph()
and make_neighborhood()_graph()
,
are synonyms (aliases).
connect(graph, order, mode = c("all", "out", "in", "total")) ego_size( graph, order = 1, nodes = V(graph), mode = c("all", "out", "in"), mindist = 0 ) neighborhood_size( graph, order = 1, nodes = V(graph), mode = c("all", "out", "in"), mindist = 0 ) ego( graph, order = 1, nodes = V(graph), mode = c("all", "out", "in"), mindist = 0 ) neighborhood( graph, order = 1, nodes = V(graph), mode = c("all", "out", "in"), mindist = 0 ) make_ego_graph( graph, order = 1, nodes = V(graph), mode = c("all", "out", "in"), mindist = 0 ) make_neighborhood_graph( graph, order = 1, nodes = V(graph), mode = c("all", "out", "in"), mindist = 0 )
connect(graph, order, mode = c("all", "out", "in", "total")) ego_size( graph, order = 1, nodes = V(graph), mode = c("all", "out", "in"), mindist = 0 ) neighborhood_size( graph, order = 1, nodes = V(graph), mode = c("all", "out", "in"), mindist = 0 ) ego( graph, order = 1, nodes = V(graph), mode = c("all", "out", "in"), mindist = 0 ) neighborhood( graph, order = 1, nodes = V(graph), mode = c("all", "out", "in"), mindist = 0 ) make_ego_graph( graph, order = 1, nodes = V(graph), mode = c("all", "out", "in"), mindist = 0 ) make_neighborhood_graph( graph, order = 1, nodes = V(graph), mode = c("all", "out", "in"), mindist = 0 )
graph |
The input graph. |
order |
Integer giving the order of the neighborhood. |
mode |
Character constant, it specifies how to use the direction of
the edges if a directed graph is analyzed. For ‘out’ only the
outgoing edges are followed, so all vertices reachable from the source
vertex in at most |
nodes |
The vertices for which the calculation is performed. |
mindist |
The minimum distance to include the vertex in the result. |
The neighborhood of a given order r
of a vertex v
includes all
vertices which are closer to v
than the order. I.e. order 0 is always
v
itself, order 1 is v
plus its immediate neighbors, order 2
is order 1 plus the immediate neighbors of the vertices in order 1, etc.
ego_size()
/neighborhood_size()
(synonyms) returns the size of the neighborhoods of the given order,
for each given vertex.
ego()
/neighborhood()
(synonyms) returns the vertices belonging to the neighborhoods of the given
order, for each given vertex.
make_ego_graph()
/make_neighborhood()_graph()
(synonyms) is creates (sub)graphs from all neighborhoods of
the given vertices with the given order parameter. This function preserves
the vertex, edge and graph attributes.
connect()
creates a new graph by connecting each vertex to
all other vertices in its neighborhood.
ego_size()
/neighborhood_size()
returns with an integer vector.
ego()
/neighborhood()
(synonyms) returns A list of igraph.vs
or a list of numeric
vectors depending on the value of igraph_opt("return.vs.es")
,
see details for performance characteristics.
make_ego_graph()
/make_neighborhood_graph()
returns with a list of graphs.
connect()
returns with a new graph object.
Gabor Csardi [email protected], the first version was done by Vincent Matossian
Other functions for manipulating graph structure:
+.igraph()
,
add_edges()
,
add_vertices()
,
complementer()
,
compose()
,
contract()
,
delete_edges()
,
delete_vertices()
,
difference()
,
difference.igraph()
,
disjoint_union()
,
edge()
,
igraph-minus
,
intersection()
,
intersection.igraph()
,
path()
,
permute()
,
rep.igraph()
,
reverse_edges()
,
simplify()
,
union()
,
union.igraph()
,
vertex()
Other structural.properties:
bfs()
,
component_distribution()
,
constraint()
,
coreness()
,
degree()
,
dfs()
,
distance_table()
,
edge_density()
,
feedback_arc_set()
,
girth()
,
is_acyclic()
,
is_dag()
,
is_matching()
,
k_shortest_paths()
,
knn()
,
reciprocity()
,
subcomponent()
,
subgraph()
,
topo_sort()
,
transitivity()
,
unfold_tree()
,
which_multiple()
,
which_mutual()
g <- make_ring(10) ego_size(g, order = 0, 1:3) ego_size(g, order = 1, 1:3) ego_size(g, order = 2, 1:3) # neighborhood_size() is an alias of ego_size() neighborhood_size(g, order = 0, 1:3) neighborhood_size(g, order = 1, 1:3) neighborhood_size(g, order = 2, 1:3) ego(g, order = 0, 1:3) ego(g, order = 1, 1:3) ego(g, order = 2, 1:3) # neighborhood() is an alias of ego() neighborhood(g, order = 0, 1:3) neighborhood(g, order = 1, 1:3) neighborhood(g, order = 2, 1:3) # attributes are preserved V(g)$name <- c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j") make_ego_graph(g, order = 2, 1:3) # make_neighborhood_graph() is an alias of make_ego_graph() make_neighborhood_graph(g, order = 2, 1:3) # connecting to the neighborhood g <- make_ring(10) g <- connect(g, 2)
g <- make_ring(10) ego_size(g, order = 0, 1:3) ego_size(g, order = 1, 1:3) ego_size(g, order = 2, 1:3) # neighborhood_size() is an alias of ego_size() neighborhood_size(g, order = 0, 1:3) neighborhood_size(g, order = 1, 1:3) neighborhood_size(g, order = 2, 1:3) ego(g, order = 0, 1:3) ego(g, order = 1, 1:3) ego(g, order = 2, 1:3) # neighborhood() is an alias of ego() neighborhood(g, order = 0, 1:3) neighborhood(g, order = 1, 1:3) neighborhood(g, order = 2, 1:3) # attributes are preserved V(g)$name <- c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j") make_ego_graph(g, order = 2, 1:3) # make_neighborhood_graph() is an alias of make_ego_graph() make_neighborhood_graph(g, order = 2, 1:3) # connecting to the neighborhood g <- make_ring(10) g <- connect(g, 2)
consensus_tree()
creates a consensus tree from several fitted
hierarchical random graph models, using phylogeny methods. If the hrg()
argument is given and start
is set to TRUE
, then it starts
sampling from the given HRG. Otherwise it optimizes the HRG log-likelihood
first, and then samples starting from the optimum.
consensus_tree(graph, hrg = NULL, start = FALSE, num.samples = 10000)
consensus_tree(graph, hrg = NULL, start = FALSE, num.samples = 10000)
graph |
The graph the models were fitted to. |
hrg |
A hierarchical random graph model, in the form of an
|
start |
Logical, whether to start the fitting/sampling from the
supplied |
num.samples |
Number of samples to use for consensus generation or missing edge prediction. |
consensus_tree()
returns a list of two objects. The first
is an igraphHRGConsensus
object, the second is an
igraphHRG
object. The igraphHRGConsensus
object has the
following members:
parents |
For each vertex, the id of its parent vertex is stored, or zero, if the vertex is the root vertex in the tree. The first n vertex ids (from 0) refer to the original vertices of the graph, the other ids refer to vertex groups. |
weights |
Numeric vector, counts the number of times a given tree
split occurred in the generated network samples, for each internal
vertices. The order is the same as in the |
Other hierarchical random graph functions:
fit_hrg()
,
hrg()
,
hrg-methods
,
hrg_tree()
,
predict_edges()
,
print.igraphHRG()
,
print.igraphHRGConsensus()
,
sample_hrg()
The igraph console is a GUI window that shows what the currently running igraph function is doing.
console()
console()
The console can be started by calling the console()
function.
Then it stays open, until the user closes it.
Another way to start it to set the verbose
igraph option to
“tkconsole” via igraph_options()
. Then the console (re)opens
each time an igraph function supporting it starts; to close it, set the
verbose
option to another value.
The console is written in Tcl/Tk and required the tcltk
package.
NULL
, invisibly.
Gabor Csardi [email protected]
igraph_options()
and the verbose
option.
Given a graph, constraint()
calculates Burt's constraint for each
vertex.
constraint(graph, nodes = V(graph), weights = NULL)
constraint(graph, nodes = V(graph), weights = NULL)
graph |
A graph object, the input graph. |
nodes |
The vertices for which the constraint will be calculated. Defaults to all vertices. |
weights |
The weights of the edges. If this is |
Burt's constraint is higher if ego has less, or mutually
stronger related (i.e. more redundant) contacts. Burt's measure of
constraint, , of vertex
's ego network
, is defined for directed and valued graphs,
for a graph of order (i.e. number of vertices) , where
proportional tie strengths are defined as
are elements of
and the latter being the
graph adjacency matrix. For isolated vertices, constraint is undefined.
A numeric vector of constraint scores
Jeroen Bruggeman (https://sites.google.com/site/jebrug/jeroen-bruggeman-social-science) and Gabor Csardi [email protected]
Burt, R.S. (2004). Structural holes and good ideas. American Journal of Sociology 110, 349-399.
Other structural.properties:
bfs()
,
component_distribution()
,
connect()
,
coreness()
,
degree()
,
dfs()
,
distance_table()
,
edge_density()
,
feedback_arc_set()
,
girth()
,
is_acyclic()
,
is_dag()
,
is_matching()
,
k_shortest_paths()
,
knn()
,
reciprocity()
,
subcomponent()
,
subgraph()
,
topo_sort()
,
transitivity()
,
unfold_tree()
,
which_multiple()
,
which_mutual()
g <- sample_gnp(20, 5 / 20) constraint(g)
g <- sample_gnp(20, 5 / 20) constraint(g)
This function creates a new graph, by merging several vertices into one. The vertices in the new graph correspond to sets of vertices in the input graph.
contract(graph, mapping, vertex.attr.comb = igraph_opt("vertex.attr.comb"))
contract(graph, mapping, vertex.attr.comb = igraph_opt("vertex.attr.comb"))
graph |
The input graph, it can be directed or undirected. |
mapping |
A numeric vector that specifies the mapping. Its elements correspond to the vertices, and for each element the id in the new graph is given. |
vertex.attr.comb |
Specifies how to combine the vertex attributes in
the new graph. Please see |
The attributes of the graph are kept. Graph and edge attributes are
unchanged, vertex attributes are combined, according to the
vertex.attr.comb
parameter.
A new graph object.
Gabor Csardi [email protected]
Other functions for manipulating graph structure:
+.igraph()
,
add_edges()
,
add_vertices()
,
complementer()
,
compose()
,
connect()
,
delete_edges()
,
delete_vertices()
,
difference()
,
difference.igraph()
,
disjoint_union()
,
edge()
,
igraph-minus
,
intersection()
,
intersection.igraph()
,
path()
,
permute()
,
rep.igraph()
,
reverse_edges()
,
simplify()
,
union()
,
union.igraph()
,
vertex()
g <- make_ring(10) g$name <- "Ring" V(g)$name <- letters[1:vcount(g)] E(g)$weight <- runif(ecount(g)) g2 <- contract(g, rep(1:5, each = 2), vertex.attr.comb = toString ) ## graph and edge attributes are kept, vertex attributes are ## combined using the 'toString' function. print(g2, g = TRUE, v = TRUE, e = TRUE)
g <- make_ring(10) g$name <- "Ring" V(g)$name <- letters[1:vcount(g)] E(g)$weight <- runif(ecount(g)) g2 <- contract(g, rep(1:5, each = 2), vertex.attr.comb = toString ) ## graph and edge attributes are kept, vertex attributes are ## combined using the 'toString' function. print(g2, g = TRUE, v = TRUE, e = TRUE)
Calculate the convex hull of a set of points, i.e. the covering polygon that has the smallest area.
convex_hull(data)
convex_hull(data)
data |
The data points, a numeric matrix with two columns. |
A named list with components:
resverts |
The indices of the input vertices that constritute the convex hull. |
rescoords |
The coordinates of the corners of the convex hull. |
Tamas Nepusz [email protected]
Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. Introduction to Algorithms, Second Edition. MIT Press and McGraw-Hill, 2001. ISBN 0262032937. Pages 949-955 of section 33.3: Finding the convex hull.
Other other:
running_mean()
,
sample_seq()
M <- cbind(runif(100), runif(100)) convex_hull(M)
M <- cbind(runif(100), runif(100)) convex_hull(M)
The k-core of graph is a maximal subgraph in which each vertex has at least degree k. The coreness of a vertex is k if it belongs to the k-core but not to the (k+1)-core.
coreness(graph, mode = c("all", "out", "in"))
coreness(graph, mode = c("all", "out", "in"))
graph |
The input graph, it can be directed or undirected |
mode |
The type of the core in directed graphs. Character constant,
possible values: |
The k-core of a graph is the maximal subgraph in which every vertex has at least degree k. The cores of a graph form layers: the (k+1)-core is always a subgraph of the k-core.
This function calculates the coreness for each vertex.
Numeric vector of integer numbers giving the coreness of each vertex.
Gabor Csardi [email protected]
Vladimir Batagelj, Matjaz Zaversnik: An O(m) Algorithm for Cores Decomposition of Networks, 2002
Seidman S. B. (1983) Network structure and minimum degree, Social Networks, 5, 269–287.
Other structural.properties:
bfs()
,
component_distribution()
,
connect()
,
constraint()
,
degree()
,
dfs()
,
distance_table()
,
edge_density()
,
feedback_arc_set()
,
girth()
,
is_acyclic()
,
is_dag()
,
is_matching()
,
k_shortest_paths()
,
knn()
,
reciprocity()
,
subcomponent()
,
subgraph()
,
topo_sort()
,
transitivity()
,
unfold_tree()
,
which_multiple()
,
which_mutual()
g <- make_ring(10) g <- add_edges(g, c(1, 2, 2, 3, 1, 3)) coreness(g) # small core triangle in a ring
g <- make_ring(10) g <- add_edges(g, c(1, 2, 2, 3, 1, 3)) coreness(g) # small core triangle in a ring
Calculate the number of automorphisms of a graph, i.e. the number of isomorphisms to itself.
count_automorphisms( graph, colors = NULL, sh = c("fm", "f", "fs", "fl", "flm", "fsm") )
count_automorphisms( graph, colors = NULL, sh = c("fm", "f", "fs", "fl", "flm", "fsm") )
graph |
The input graph, it is treated as undirected. |
colors |
The colors of the individual vertices of the graph; only
vertices having the same color are allowed to match each other in an
automorphism. When omitted, igraph uses the |
sh |
The splitting heuristics for the BLISS algorithm. Possible values
are: ‘ |
An automorphism of a graph is a permutation of its vertices which brings the graph into itself.
This function calculates the number of automorphism of a graph using the
BLISS algorithm. See also the BLISS homepage at
http://www.tcs.hut.fi/Software/bliss/index.html. If you need the
automorphisms themselves, use automorphism_group()
to obtain
a compact representation of the automorphism group.
A named list with the following members:
group_size |
The size of the automorphism group of the input graph, as a string. This number is exact if igraph was compiled with the GMP library, and approximate otherwise. |
nof_nodes |
The number of nodes in the search tree. |
nof_leaf_nodes |
The number of leaf nodes in the search tree. |
nof_bad_nodes |
Number of bad nodes. |
nof_canupdates |
Number of canrep updates. |
max_level |
Maximum level. |
Tommi Junttila (http://users.ics.aalto.fi/tjunttil/) for BLISS and Gabor Csardi [email protected] for the igraph glue code and this manual page.
Tommi Junttila and Petteri Kaski: Engineering an Efficient Canonical Labeling Tool for Large and Sparse Graphs, Proceedings of the Ninth Workshop on Algorithm Engineering and Experiments and the Fourth Workshop on Analytic Algorithms and Combinatorics. 2007.
canonical_permutation()
, permute()
,
and automorphism_group()
for a compact representation of all
automorphisms
Other graph automorphism:
automorphism_group()
## A ring has n*2 automorphisms, you can "turn" it by 0-9 vertices ## and each of these graphs can be "flipped" g <- make_ring(10) count_automorphisms(g) ## A full graph has n! automorphisms; however, we restrict the vertex ## matching by colors, leading to only 4 automorphisms g <- make_full_graph(4) count_automorphisms(g, colors = c(1, 2, 1, 2))
## A ring has n*2 automorphisms, you can "turn" it by 0-9 vertices ## and each of these graphs can be "flipped" g <- make_ring(10) count_automorphisms(g) ## A full graph has n! automorphisms; however, we restrict the vertex ## matching by colors, leading to only 4 automorphisms g <- make_full_graph(4) count_automorphisms(g, colors = c(1, 2, 1, 2))
Count the number of isomorphic mappings between two graphs
count_isomorphisms(graph1, graph2, method = "vf2", ...)
count_isomorphisms(graph1, graph2, method = "vf2", ...)
graph1 |
The first graph. |
graph2 |
The second graph. |
method |
Currently only ‘vf2’ is supported, see
|
... |
Passed to the individual methods. |
Number of isomorphic mappings between the two graphs.
LP Cordella, P Foggia, C Sansone, and M Vento: An improved algorithm for matching large graphs, Proc. of the 3rd IAPR TC-15 Workshop on Graphbased Representations in Pattern Recognition, 149–159, 2001.
Other graph isomorphism:
canonical_permutation()
,
count_subgraph_isomorphisms()
,
graph_from_isomorphism_class()
,
isomorphic()
,
isomorphism_class()
,
isomorphisms()
,
subgraph_isomorphic()
,
subgraph_isomorphisms()
# colored graph isomorphism g1 <- make_ring(10) g2 <- make_ring(10) isomorphic(g1, g2) V(g1)$color <- rep(1:2, length = vcount(g1)) V(g2)$color <- rep(2:1, length = vcount(g2)) # consider colors by default count_isomorphisms(g1, g2) # ignore colors count_isomorphisms(g1, g2, vertex.color1 = NULL, vertex.color2 = NULL )
# colored graph isomorphism g1 <- make_ring(10) g2 <- make_ring(10) isomorphic(g1, g2) V(g1)$color <- rep(1:2, length = vcount(g1)) V(g2)$color <- rep(2:1, length = vcount(g2)) # consider colors by default count_isomorphisms(g1, g2) # ignore colors count_isomorphisms(g1, g2, vertex.color1 = NULL, vertex.color2 = NULL )
Graph motifs are small connected induced subgraphs with a well-defined structure. These functions search a graph for various motifs.
count_motifs(graph, size = 3, cut.prob = rep(0, size))
count_motifs(graph, size = 3, cut.prob = rep(0, size))
graph |
Graph object, the input graph. |
size |
The size of the motif. |
cut.prob |
Numeric vector giving the probabilities that the search
graph is cut at a certain level. Its length should be the same as the size
of the motif (the |
count_motifs()
calculates the total number of motifs of a given
size in graph.
count_motifs()
returns a numeric scalar.
Other graph motifs:
dyad_census()
,
motifs()
,
sample_motifs()
g <- sample_pa(100) motifs(g, 3) count_motifs(g, 3) sample_motifs(g, 3)
g <- sample_pa(100) motifs(g, 3) count_motifs(g, 3) sample_motifs(g, 3)
Count the isomorphic mappings between a graph and the subgraphs of another graph
count_subgraph_isomorphisms(pattern, target, method = c("lad", "vf2"), ...)
count_subgraph_isomorphisms(pattern, target, method = c("lad", "vf2"), ...)
pattern |
The smaller graph, it might be directed or undirected. Undirected graphs are treated as directed graphs with mutual edges. |
target |
The bigger graph, it might be directed or undirected. Undirected graphs are treated as directed graphs with mutual edges. |
method |
The method to use. Possible values: ‘lad’, ‘vf2’. See their details below. |
... |
Additional arguments, passed to the various methods. |
Logical scalar, TRUE
if the pattern
is
isomorphic to a (possibly induced) subgraph of target
.
This is the LAD algorithm by Solnon, see the reference below. It has the following extra arguments:
If not NULL
, then it specifies matching
restrictions. It must be a list of target
vertex sets, given
as numeric vertex ids or symbolic vertex names. The length of the
list must be vcount(pattern)
and for each vertex in
pattern
it gives the allowed matching vertices in
target
. Defaults to NULL
.
Logical scalar, whether to search for an induced
subgraph. It is FALSE
by default.
The processor time limit for the computation, in
seconds. It defaults to Inf
, which means no limit.
This method uses the VF2 algorithm by Cordella, Foggia et al., see references below. It supports vertex and edge colors and have the following extra arguments:
Optional integer vectors giving the
colors of the vertices for colored graph isomorphism. If they
are not given, but the graph has a “color” vertex attribute,
then it will be used. If you want to ignore these attributes, then
supply NULL
for both of these arguments. See also examples
below.
Optional integer vectors giving the
colors of the edges for edge-colored (sub)graph isomorphism. If they
are not given, but the graph has a “color” edge attribute,
then it will be used. If you want to ignore these attributes, then
supply NULL
for both of these arguments.
LP Cordella, P Foggia, C Sansone, and M Vento: An improved algorithm for matching large graphs, Proc. of the 3rd IAPR TC-15 Workshop on Graphbased Representations in Pattern Recognition, 149–159, 2001.
C. Solnon: AllDifferent-based Filtering for Subgraph Isomorphism, Artificial Intelligence 174(12-13):850–864, 2010.
Other graph isomorphism:
canonical_permutation()
,
count_isomorphisms()
,
graph_from_isomorphism_class()
,
isomorphic()
,
isomorphism_class()
,
isomorphisms()
,
subgraph_isomorphic()
,
subgraph_isomorphisms()
If graphs have multiple edges, then drawing them as straight lines does not show them when plotting the graphs; they will be on top of each other. One solution is to bend the edges, with diffenent curvature, so that all of them are visible.
curve_multiple(graph, start = 0.5)
curve_multiple(graph, start = 0.5)
graph |
The input graph. |
start |
The curvature at the two extreme edges. All edges will have a
curvature between |
curve_multiple()
calculates the optimal edge.curved
vector for
plotting a graph with multiple edges, so that all edges are visible.
A numeric vector, its length is the number of edges in the graph.
Gabor Csardi [email protected]
igraph.plotting for all plotting parameters,
plot.igraph()
, tkplot()
and rglplot()
for plotting functions.
g <- make_graph(c( 0, 1, 1, 0, 1, 2, 1, 3, 1, 3, 1, 3, 2, 3, 2, 3, 2, 3, 2, 3, 0, 1 ) + 1) curve_multiple(g) set.seed(42) plot(g)
g <- make_graph(c( 0, 1, 1, 0, 1, 2, 1, 3, 1, 3, 1, 3, 2, 3, 2, 3, 2, 3, 2, 3, 0, 1 ) + 1) curve_multiple(g) set.seed(42) plot(g)
Creates a separate graph for each connected component of a graph.
decompose(graph, mode = c("weak", "strong"), max.comps = NA, min.vertices = 0)
decompose(graph, mode = c("weak", "strong"), max.comps = NA, min.vertices = 0)
graph |
The original graph. |
mode |
Character constant giving the type of the components, wither
|
max.comps |
The maximum number of components to return. The first
|
min.vertices |
The minimum number of vertices a component should contain in order to place it in the result list. E.g. supply 2 here to ignore isolate vertices. |
A list of graph objects.
Gabor Csardi [email protected]
is_connected()
to decide whether a graph is connected,
components()
to calculate the connected components of a graph.
Connected components
articulation_points()
,
biconnected_components()
,
component_distribution()
,
is_biconnected()
# the diameter of each component in a random graph g <- sample_gnp(1000, 1 / 1000) components <- decompose(g, min.vertices = 2) sapply(components, diameter)
# the diameter of each component in a random graph g <- sample_gnp(1000, 1 / 1000) components <- decompose(g, min.vertices = 2) sapply(components, diameter)
The degree of a vertex is its most basic structural property, the number of its adjacent edges.
degree( graph, v = V(graph), mode = c("all", "out", "in", "total"), loops = TRUE, normalized = FALSE ) max_degree( graph, ..., v = V(graph), mode = c("all", "out", "in", "total"), loops = TRUE ) degree_distribution(graph, cumulative = FALSE, ...)
degree( graph, v = V(graph), mode = c("all", "out", "in", "total"), loops = TRUE, normalized = FALSE ) max_degree( graph, ..., v = V(graph), mode = c("all", "out", "in", "total"), loops = TRUE ) degree_distribution(graph, cumulative = FALSE, ...)
graph |
The graph to analyze. |
v |
The ids of vertices of which the degree will be calculated. |
mode |
Character string, “out” for out-degree, “in” for in-degree or “total” for the sum of the two. For undirected graphs this argument is ignored. “all” is a synonym of “total”. |
loops |
Logical; whether the loop edges are also counted. |
normalized |
Logical scalar, whether to normalize the degree. If
|
... |
These dots are for future extensions and must be empty. |
cumulative |
Logical; whether the cumulative degree distribution is to be calculated. |
For degree()
a numeric vector of the same length as argument
v
.
For degree_distribution()
a numeric vector of the same length as the
maximum degree plus one. The first element is the relative frequency zero
degree vertices, the second vertices with degree one, etc.
For max_degree()
, the largest degree in the graph. When no vertices are
selected, or when the input is the null graph, zero is returned as this
is the smallest possible degree.
Gabor Csardi [email protected]
Other structural.properties:
bfs()
,
component_distribution()
,
connect()
,
constraint()
,
coreness()
,
dfs()
,
distance_table()
,
edge_density()
,
feedback_arc_set()
,
girth()
,
is_acyclic()
,
is_dag()
,
is_matching()
,
k_shortest_paths()
,
knn()
,
reciprocity()
,
subcomponent()
,
subgraph()
,
topo_sort()
,
transitivity()
,
unfold_tree()
,
which_multiple()
,
which_mutual()
g <- make_ring(10) degree(g) g2 <- sample_gnp(1000, 10 / 1000) max_degree(g2) degree_distribution(g2)
g <- make_ring(10) degree(g) g2 <- sample_gnp(1000, 10 / 1000) max_degree(g2) degree_distribution(g2)
Delete an edge attribute
delete_edge_attr(graph, name)
delete_edge_attr(graph, name)
graph |
The graph |
name |
The name of the edge attribute to delete. |
The graph, with the specified edge attribute removed.
Vertex, edge and graph attributes
delete_graph_attr()
,
delete_vertex_attr()
,
edge_attr()
,
edge_attr<-()
,
edge_attr_names()
,
graph_attr()
,
graph_attr<-()
,
graph_attr_names()
,
igraph-attribute-combination
,
igraph-dollar
,
igraph-vs-attributes
,
set_edge_attr()
,
set_graph_attr()
,
set_vertex_attr()
,
vertex_attr()
,
vertex_attr<-()
,
vertex_attr_names()
g <- make_ring(10) %>% set_edge_attr("name", value = LETTERS[1:10]) edge_attr_names(g) g2 <- delete_edge_attr(g, "name") edge_attr_names(g2)
g <- make_ring(10) %>% set_edge_attr("name", value = LETTERS[1:10]) edge_attr_names(g) g2 <- delete_edge_attr(g, "name") edge_attr_names(g2)
Delete edges from a graph
delete_edges(graph, edges)
delete_edges(graph, edges)
graph |
The input graph. |
edges |
The edges to remove, specified as an edge sequence. Typically
this is either a numeric vector containing edge IDs, or a character vector
containing the IDs or names of the source and target vertices, separated by
|
The graph, with the edges removed.
Other functions for manipulating graph structure:
+.igraph()
,
add_edges()
,
add_vertices()
,
complementer()
,
compose()
,
connect()
,
contract()
,
delete_vertices()
,
difference()
,
difference.igraph()
,
disjoint_union()
,
edge()
,
igraph-minus
,
intersection()
,
intersection.igraph()
,
path()
,
permute()
,
rep.igraph()
,
reverse_edges()
,
simplify()
,
union()
,
union.igraph()
,
vertex()
g <- make_ring(10) %>% delete_edges(seq(1, 9, by = 2)) g g <- make_ring(10) %>% delete_edges("10|1") g g <- make_ring(5) g <- delete_edges(g, get_edge_ids(g, c(1, 5, 4, 5))) g
g <- make_ring(10) %>% delete_edges(seq(1, 9, by = 2)) g g <- make_ring(10) %>% delete_edges("10|1") g g <- make_ring(5) g <- delete_edges(g, get_edge_ids(g, c(1, 5, 4, 5))) g
Delete a graph attribute
delete_graph_attr(graph, name)
delete_graph_attr(graph, name)
graph |
The graph. |
name |
Name of the attribute to delete. |
The graph, with the specified attribute removed.
Vertex, edge and graph attributes
delete_edge_attr()
,
delete_vertex_attr()
,
edge_attr()
,
edge_attr<-()
,
edge_attr_names()
,
graph_attr()
,
graph_attr<-()
,
graph_attr_names()
,
igraph-attribute-combination
,
igraph-dollar
,
igraph-vs-attributes
,
set_edge_attr()
,
set_graph_attr()
,
set_vertex_attr()
,
vertex_attr()
,
vertex_attr<-()
,
vertex_attr_names()
g <- make_ring(10) graph_attr_names(g) g2 <- delete_graph_attr(g, "name") graph_attr_names(g2)
g <- make_ring(10) graph_attr_names(g) g2 <- delete_graph_attr(g, "name") graph_attr_names(g2)
Delete a vertex attribute
delete_vertex_attr(graph, name)
delete_vertex_attr(graph, name)
graph |
The graph |
name |
The name of the vertex attribute to delete. |
The graph, with the specified vertex attribute removed.
Vertex, edge and graph attributes
delete_edge_attr()
,
delete_graph_attr()
,
edge_attr()
,
edge_attr<-()
,
edge_attr_names()
,
graph_attr()
,
graph_attr<-()
,
graph_attr_names()
,
igraph-attribute-combination
,
igraph-dollar
,
igraph-vs-attributes
,
set_edge_attr()
,
set_graph_attr()
,
set_vertex_attr()
,
vertex_attr()
,
vertex_attr<-()
,
vertex_attr_names()
g <- make_ring(10) %>% set_vertex_attr("name", value = LETTERS[1:10]) vertex_attr_names(g) g2 <- delete_vertex_attr(g, "name") vertex_attr_names(g2)
g <- make_ring(10) %>% set_vertex_attr("name", value = LETTERS[1:10]) vertex_attr_names(g) g2 <- delete_vertex_attr(g, "name") vertex_attr_names(g2)
Delete vertices from a graph
delete_vertices(graph, v)
delete_vertices(graph, v)
graph |
The input graph. |
v |
The vertices to remove, a vertex sequence. |
The graph, with the vertices removed.
Other functions for manipulating graph structure:
+.igraph()
,
add_edges()
,
add_vertices()
,
complementer()
,
compose()
,
connect()
,
contract()
,
delete_edges()
,
difference()
,
difference.igraph()
,
disjoint_union()
,
edge()
,
igraph-minus
,
intersection()
,
intersection.igraph()
,
path()
,
permute()
,
rep.igraph()
,
reverse_edges()
,
simplify()
,
union()
,
union.igraph()
,
vertex()
g <- make_ring(10) %>% set_vertex_attr("name", value = LETTERS[1:10]) g V(g) g2 <- delete_vertices(g, c(1, 5)) %>% delete_vertices("B") g2 V(g2)
g <- make_ring(10) %>% set_vertex_attr("name", value = LETTERS[1:10]) g V(g) g2 <- delete_vertices(g, c(1, 5)) %>% delete_vertices("B") g2 V(g2)
Depth-first search is an algorithm to traverse a graph. It starts from a root vertex and tries to go quickly as far from as possible.
dfs( graph, root, mode = c("out", "in", "all", "total"), unreachable = TRUE, order = TRUE, order.out = FALSE, father = FALSE, dist = FALSE, in.callback = NULL, out.callback = NULL, extra = NULL, rho = parent.frame(), neimode = deprecated() )
dfs( graph, root, mode = c("out", "in", "all", "total"), unreachable = TRUE, order = TRUE, order.out = FALSE, father = FALSE, dist = FALSE, in.callback = NULL, out.callback = NULL, extra = NULL, rho = parent.frame(), neimode = deprecated() )
The callback functions must have the following arguments:
The input graph is passed to the callback function here.
A named numeric vector, with the following entries: ‘vid’, the vertex that was just visited and ‘dist’, its distance from the root of the search tree.
The extra argument.
The callback must return FALSE to continue the search or TRUE to terminate it. See examples below on how to use the callback functions.
A named list with the following entries:
root |
Numeric scalar. The root vertex that was used as the starting point of the search. |
neimode |
Character scalar. The |
order |
Numeric vector. The vertex ids, in the order in which they were visited by the search. |
order.out |
Numeric vector, the vertex ids, in the order of the completion of their subtree. |
father |
Numeric vector. The father of each vertex, i.e. the vertex it was discovered from. |
dist |
Numeric vector, for each vertex its distance from the root of the search tree. |
Note that order
, order.out
, father
, and dist
might be NULL
if their corresponding argument is FALSE
, i.e.
if their calculation is not requested.
Gabor Csardi [email protected]
bfs()
for breadth-first search.
Other structural.properties:
bfs()
,
component_distribution()
,
connect()
,
constraint()
,
coreness()
,
degree()
,
distance_table()
,
edge_density()
,
feedback_arc_set()
,
girth()
,
is_acyclic()
,
is_dag()
,
is_matching()
,
k_shortest_paths()
,
knn()
,
reciprocity()
,
subcomponent()
,
subgraph()
,
topo_sort()
,
transitivity()
,
unfold_tree()
,
which_multiple()
,
which_mutual()
## A graph with two separate trees dfs(make_tree(10) %du% make_tree(10), root = 1, "out", TRUE, TRUE, TRUE, TRUE ) ## How to use a callback f.in <- function(graph, data, extra) { cat("in:", paste(collapse = ", ", data), "\n") FALSE } f.out <- function(graph, data, extra) { cat("out:", paste(collapse = ", ", data), "\n") FALSE } tmp <- dfs(make_tree(10), root = 1, "out", in.callback = f.in, out.callback = f.out ) ## Terminate after the first component, using a callback f.out <- function(graph, data, extra) { data["vid"] == 1 } tmp <- dfs(make_tree(10) %du% make_tree(10), root = 1, out.callback = f.out )
## A graph with two separate trees dfs(make_tree(10) %du% make_tree(10), root = 1, "out", TRUE, TRUE, TRUE, TRUE ) ## How to use a callback f.in <- function(graph, data, extra) { cat("in:", paste(collapse = ", ", data), "\n") FALSE } f.out <- function(graph, data, extra) { cat("out:", paste(collapse = ", ", data), "\n") FALSE } tmp <- dfs(make_tree(10), root = 1, "out", in.callback = f.in, out.callback = f.out ) ## Terminate after the first component, using a callback f.out <- function(graph, data, extra) { data["vid"] == 1 } tmp <- dfs(make_tree(10) %du% make_tree(10), root = 1, out.callback = f.out )
The diameter of a graph is the length of the longest geodesic.
diameter(graph, directed = TRUE, unconnected = TRUE, weights = NULL) get_diameter(graph, directed = TRUE, unconnected = TRUE, weights = NULL) farthest_vertices(graph, directed = TRUE, unconnected = TRUE, weights = NULL)
diameter(graph, directed = TRUE, unconnected = TRUE, weights = NULL) get_diameter(graph, directed = TRUE, unconnected = TRUE, weights = NULL) farthest_vertices(graph, directed = TRUE, unconnected = TRUE, weights = NULL)
graph |
The graph to analyze. |
directed |
Logical, whether directed or undirected paths are to be considered. This is ignored for undirected graphs. |
unconnected |
Logical, what to do if the graph is unconnected. If FALSE, the function will return a number that is one larger the largest possible diameter, which is always the number of vertices. If TRUE, the diameters of the connected components will be calculated and the largest one will be returned. |
weights |
Optional positive weight vector for calculating weighted
distances. If the graph has a |
The diameter is calculated by using a breadth-first search like method.
get_diameter()
returns a path with the actual diameter. If there are
many shortest paths of the length of the diameter, then it returns the first
one found.
farthest_vertices()
returns two vertex ids, the vertices which are
connected by the diameter path.
A numeric constant for diameter()
, a numeric vector for
get_diameter()
. farthest_vertices()
returns a list with two
entries:
vertices
The two vertices that are the farthest.
distance
Their distance.
Gabor Csardi [email protected]
Other paths:
all_simple_paths()
,
distance_table()
,
eccentricity()
,
graph_center()
,
radius()
g <- make_ring(10) g2 <- delete_edges(g, c(1, 2, 1, 10)) diameter(g2, unconnected = TRUE) diameter(g2, unconnected = FALSE) ## Weighted diameter set.seed(1) g <- make_ring(10) E(g)$weight <- sample(seq_len(ecount(g))) diameter(g) get_diameter(g) diameter(g, weights = NA) get_diameter(g, weights = NA)
g <- make_ring(10) g2 <- delete_edges(g, c(1, 2, 1, 10)) diameter(g2, unconnected = TRUE) diameter(g2, unconnected = FALSE) ## Weighted diameter set.seed(1) g <- make_ring(10) E(g)$weight <- sample(seq_len(ecount(g))) diameter(g) get_diameter(g) diameter(g, weights = NA) get_diameter(g, weights = NA)
This is an S3 generic function. See methods("difference")
for the actual implementations for various S3 classes. Initially
it is implemented for igraph graphs (difference of edges in two graphs),
and igraph vertex and edge sequences. See
difference.igraph()
, and
difference.igraph.vs()
.
difference(...)
difference(...)
... |
Arguments, their number and interpretation depends on
the function that implements |
Depends on the function that implements this method.
Other functions for manipulating graph structure:
+.igraph()
,
add_edges()
,
add_vertices()
,
complementer()
,
compose()
,
connect()
,
contract()
,
delete_edges()
,
delete_vertices()
,
difference.igraph()
,
disjoint_union()
,
edge()
,
igraph-minus
,
intersection()
,
intersection.igraph()
,
path()
,
permute()
,
rep.igraph()
,
reverse_edges()
,
simplify()
,
union()
,
union.igraph()
,
vertex()
The difference of two graphs are created.
## S3 method for class 'igraph' difference(big, small, byname = "auto", ...)
## S3 method for class 'igraph' difference(big, small, byname = "auto", ...)
big |
The left hand side argument of the minus operator. A directed or undirected graph. |
small |
The right hand side argument of the minus operator. A directed ot undirected graph. |
byname |
A logical scalar, or the character scalar |
... |
Ignored, included for S3 compatibility. |
difference()
creates the difference of two graphs. Only edges
present in the first graph but not in the second will be be included in the
new graph. The corresponding operator is %m%
.
If the byname
argument is TRUE
(or auto
and the graphs
are all named), then the operation is performed based on symbolic vertex
names. Otherwise numeric vertex ids are used.
difference()
keeps all attributes (graph, vertex and edge) of the
first graph.
Note that big
and small
must both be directed or both be
undirected, otherwise an error message is given.
A new graph object.
Gabor Csardi [email protected]
Other functions for manipulating graph structure:
+.igraph()
,
add_edges()
,
add_vertices()
,
complementer()
,
compose()
,
connect()
,
contract()
,
delete_edges()
,
delete_vertices()
,
difference()
,
disjoint_union()
,
edge()
,
igraph-minus
,
intersection()
,
intersection.igraph()
,
path()
,
permute()
,
rep.igraph()
,
reverse_edges()
,
simplify()
,
union()
,
union.igraph()
,
vertex()
## Create a wheel graph wheel <- union( make_ring(10), make_star(11, center = 11, mode = "undirected") ) V(wheel)$name <- letters[seq_len(vcount(wheel))] ## Subtract a star graph from it sstar <- make_star(6, center = 6, mode = "undirected") V(sstar)$name <- letters[c(1, 3, 5, 7, 9, 11)] G <- wheel %m% sstar print_all(G) plot(G, layout = layout_nicely(wheel))
## Create a wheel graph wheel <- union( make_ring(10), make_star(11, center = 11, mode = "undirected") ) V(wheel)$name <- letters[seq_len(vcount(wheel))] ## Subtract a star graph from it sstar <- make_star(6, center = 6, mode = "undirected") V(sstar)$name <- letters[c(1, 3, 5, 7, 9, 11)] G <- wheel %m% sstar print_all(G) plot(G, layout = layout_nicely(wheel))
Difference of edge sequences
## S3 method for class 'igraph.es' difference(big, small, ...)
## S3 method for class 'igraph.es' difference(big, small, ...)
big |
The ‘big’ edge sequence. |
small |
The ‘small’ edge sequence. |
... |
Ignored, included for S3 signature compatibility. |
They must belong to the same graph. Note that this function has ‘set’ semantics and the multiplicity of edges is lost in the result.
An edge sequence that contains only edges that are part of
big
, but not part of small
.
Other vertex and edge sequence operations:
c.igraph.es()
,
c.igraph.vs()
,
difference.igraph.vs()
,
igraph-es-indexing
,
igraph-es-indexing2
,
igraph-vs-indexing
,
igraph-vs-indexing2
,
intersection.igraph.es()
,
intersection.igraph.vs()
,
rev.igraph.es()
,
rev.igraph.vs()
,
union.igraph.es()
,
union.igraph.vs()
,
unique.igraph.es()
,
unique.igraph.vs()
g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) difference(V(g), V(g)[6:10])
g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) difference(V(g), V(g)[6:10])
Difference of vertex sequences
## S3 method for class 'igraph.vs' difference(big, small, ...)
## S3 method for class 'igraph.vs' difference(big, small, ...)
big |
The ‘big’ vertex sequence. |
small |
The ‘small’ vertex sequence. |
... |
Ignored, included for S3 signature compatibility. |
They must belong to the same graph. Note that this function has ‘set’ semantics and the multiplicity of vertices is lost in the result.
A vertex sequence that contains only vertices that are part of
big
, but not part of small
.
Other vertex and edge sequence operations:
c.igraph.es()
,
c.igraph.vs()
,
difference.igraph.es()
,
igraph-es-indexing
,
igraph-es-indexing2
,
igraph-vs-indexing
,
igraph-vs-indexing2
,
intersection.igraph.es()
,
intersection.igraph.vs()
,
rev.igraph.es()
,
rev.igraph.vs()
,
union.igraph.es()
,
union.igraph.vs()
,
unique.igraph.es()
,
unique.igraph.vs()
g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) difference(V(g), V(g)[6:10])
g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) difference(V(g), V(g)[6:10])
Select the number of significant singular values, by finding the ‘elbow’ of the scree plot, in a principled way.
dim_select(sv)
dim_select(sv)
sv |
A numeric vector, the ordered singular values. |
The input of the function is a numeric vector which contains the measure of ‘importance’ for each dimension.
For spectral embedding, these are the singular values of the adjacency
matrix. The singular values are assumed to be generated from a Gaussian
mixture distribution with two components that have different means and same
variance. The dimensionality is chosen to maximize the likelihood
when the
largest singular values are assigned to one component of
the mixture and the rest of the singular values assigned to the other
component.
This function can also be used for the general separation problem, where we assume that the left and the right of the vector are coming from two Normal distributions, with different means, and we want to know their border. See examples below.
A numeric scalar, the estimate of .
Gabor Csardi [email protected]
M. Zhu, and A. Ghodsi (2006). Automatic dimensionality selection from the scree plot via the use of profile likelihood. Computational Statistics and Data Analysis, Vol. 51, 918–930.
Other embedding:
embed_adjacency_matrix()
,
embed_laplacian_matrix()
# Generate the two groups of singular values with # Gaussian mixture of two components that have different means sing.vals <- c(rnorm(10, mean = 1, sd = 1), rnorm(10, mean = 3, sd = 1)) dim.chosen <- dim_select(sing.vals) dim.chosen # Sample random vectors with multivariate normal distribution # and normalize to unit length lpvs <- matrix(rnorm(200), 10, 20) lpvs <- apply(lpvs, 2, function(x) { (abs(x) / sqrt(sum(x^2))) }) RDP.graph <- sample_dot_product(lpvs) dim_select(embed_adjacency_matrix(RDP.graph, 10)$D) # Sample random vectors with the Dirichlet distribution lpvs.dir <- sample_dirichlet(n = 20, rep(1, 10)) RDP.graph.2 <- sample_dot_product(lpvs.dir) dim_select(embed_adjacency_matrix(RDP.graph.2, 10)$D) # Sample random vectors from hypersphere with radius 1. lpvs.sph <- sample_sphere_surface(dim = 10, n = 20, radius = 1) RDP.graph.3 <- sample_dot_product(lpvs.sph) dim_select(embed_adjacency_matrix(RDP.graph.3, 10)$D)
# Generate the two groups of singular values with # Gaussian mixture of two components that have different means sing.vals <- c(rnorm(10, mean = 1, sd = 1), rnorm(10, mean = 3, sd = 1)) dim.chosen <- dim_select(sing.vals) dim.chosen # Sample random vectors with multivariate normal distribution # and normalize to unit length lpvs <- matrix(rnorm(200), 10, 20) lpvs <- apply(lpvs, 2, function(x) { (abs(x) / sqrt(sum(x^2))) }) RDP.graph <- sample_dot_product(lpvs) dim_select(embed_adjacency_matrix(RDP.graph, 10)$D) # Sample random vectors with the Dirichlet distribution lpvs.dir <- sample_dirichlet(n = 20, rep(1, 10)) RDP.graph.2 <- sample_dot_product(lpvs.dir) dim_select(embed_adjacency_matrix(RDP.graph.2, 10)$D) # Sample random vectors from hypersphere with radius 1. lpvs.sph <- sample_sphere_surface(dim = 10, n = 20, radius = 1) RDP.graph.3 <- sample_dot_product(lpvs.sph) dim_select(embed_adjacency_matrix(RDP.graph.3, 10)$D)
The union of two or more graphs are created. The graphs are assumed to have disjoint vertex sets.
disjoint_union(...) x %du% y
disjoint_union(...) x %du% y
... |
Graph objects or lists of graph objects. |
x , y
|
Graph objects. |
disjoint_union()
creates a union of two or more disjoint graphs.
Thus first the vertices in the second, third, etc. graphs are relabeled to
have completely disjoint graphs. Then a simple union is created. This
function can also be used via the %du%
operator.
graph.disjont.union
handles graph, vertex and edge attributes. In
particular, it merges vertex and edge attributes using the basic c()
function. For graphs that lack some vertex/edge attribute, the corresponding
values in the new graph are set to NA
. Graph attributes are simply
copied to the result. If this would result a name clash, then they are
renamed by adding suffixes: _1, _2, etc.
Note that if both graphs have vertex names (i.e. a name
vertex
attribute), then the concatenated vertex names might be non-unique in the
result. A warning is given if this happens.
An error is generated if some input graphs are directed and others are undirected.
A new graph object.
Gabor Csardi [email protected]
Other functions for manipulating graph structure:
+.igraph()
,
add_edges()
,
add_vertices()
,
complementer()
,
compose()
,
connect()
,
contract()
,
delete_edges()
,
delete_vertices()
,
difference()
,
difference.igraph()
,
edge()
,
igraph-minus
,
intersection()
,
intersection.igraph()
,
path()
,
permute()
,
rep.igraph()
,
reverse_edges()
,
simplify()
,
union()
,
union.igraph()
,
vertex()
## A star and a ring g1 <- make_star(10, mode = "undirected") V(g1)$name <- letters[1:10] g2 <- make_ring(10) V(g2)$name <- letters[11:20] print_all(g1 %du% g2)
## A star and a ring g1 <- make_star(10, mode = "undirected") V(g1)$name <- letters[1:10] g2 <- make_ring(10) V(g2)$name <- letters[11:20] print_all(g1 %du% g2)
distances()
calculates the length of all the shortest paths from
or to the vertices in the network. shortest_paths()
calculates one
shortest path (the path itself, and not just its length) from or to the
given vertex.
distance_table(graph, directed = TRUE) mean_distance( graph, weights = NULL, directed = TRUE, unconnected = TRUE, details = FALSE ) distances( graph, v = V(graph), to = V(graph), mode = c("all", "out", "in"), weights = NULL, algorithm = c("automatic", "unweighted", "dijkstra", "bellman-ford", "johnson", "floyd-warshall") ) shortest_paths( graph, from, to = V(graph), mode = c("out", "all", "in"), weights = NULL, output = c("vpath", "epath", "both"), predecessors = FALSE, inbound.edges = FALSE, algorithm = c("automatic", "unweighted", "dijkstra", "bellman-ford") ) all_shortest_paths( graph, from, to = V(graph), mode = c("out", "all", "in"), weights = NULL )
distance_table(graph, directed = TRUE) mean_distance( graph, weights = NULL, directed = TRUE, unconnected = TRUE, details = FALSE ) distances( graph, v = V(graph), to = V(graph), mode = c("all", "out", "in"), weights = NULL, algorithm = c("automatic", "unweighted", "dijkstra", "bellman-ford", "johnson", "floyd-warshall") ) shortest_paths( graph, from, to = V(graph), mode = c("out", "all", "in"), weights = NULL, output = c("vpath", "epath", "both"), predecessors = FALSE, inbound.edges = FALSE, algorithm = c("automatic", "unweighted", "dijkstra", "bellman-ford") ) all_shortest_paths( graph, from, to = V(graph), mode = c("out", "all", "in"), weights = NULL )
graph |
The graph to work on. |
directed |
Whether to consider directed paths in directed graphs, this argument is ignored for undirected graphs. |
weights |
Possibly a numeric vector giving edge weights. If this is
|
unconnected |
What to do if the graph is unconnected (not strongly connected if directed paths are considered). If TRUE, only the lengths of the existing paths are considered and averaged; if FALSE, the length of the missing paths are considered as having infinite length, making the mean distance infinite as well. |
details |
Whether to provide additional details in the result.
Functions accepting this argument (like |
v |
Numeric vector, the vertices from which the shortest paths will be calculated. |
to |
Numeric vector, the vertices to which the shortest paths will be
calculated. By default it includes all vertices. Note that for
|
mode |
Character constant, gives whether the shortest paths to or from
the given vertices should be calculated for directed graphs. If |
algorithm |
Which algorithm to use for the calculation. By default igraph tries to select the fastest suitable algorithm. If there are no weights, then an unweighted breadth-first search is used, otherwise if all weights are positive, then Dijkstra's algorithm is used. If there are negative weights and we do the calculation for more than 100 sources, then Johnson's algorithm is used. Otherwise the Bellman-Ford algorithm is used. You can override igraph's choice by explicitly giving this parameter. Note that the igraph C core might still override your choice in obvious cases, i.e. if there are no edge weights, then the unweighted algorithm will be used, regardless of this argument. |
from |
Numeric constant, the vertex from or to the shortest paths will be calculated. Note that right now this is not a vector of vertex ids, but only a single vertex. |
output |
Character scalar, defines how to report the shortest paths. “vpath” means that the vertices along the paths are reported, this form was used prior to igraph version 0.6. “epath” means that the edges along the paths are reported. “both” means that both forms are returned, in a named list with components “vpath” and “epath”. |
predecessors |
Logical scalar, whether to return the predecessor vertex
for each vertex. The predecessor of vertex |
inbound.edges |
Logical scalar, whether to return the inbound edge for
each vertex. The inbound edge of vertex |
The shortest path, or geodesic between two pair of vertices is a path with the minimal number of vertices. The functions documented in this manual page all calculate shortest paths between vertex pairs.
distances()
calculates the lengths of pairwise shortest paths from
a set of vertices (from
) to another set of vertices (to
). It
uses different algorithms, depending on the algorithm
argument and
the weight
edge attribute of the graph. The implemented algorithms
are breadth-first search (‘unweighted
’), this only works for
unweighted graphs; the Dijkstra algorithm (‘dijkstra
’), this
works for graphs with non-negative edge weights; the Bellman-Ford algorithm
(‘bellman-ford
’); Johnson's algorithm
(‘johnson
’); and a faster version of the Floyd-Warshall algorithm
with expected quadratic running time (‘floyd-warshall
’). The latter
three algorithms work with arbitrary
edge weights, but (naturally) only for graphs that don't have a negative
cycle. Note that a negative-weight edge in an undirected graph implies
such a cycle. Johnson's algorithm performs better than the Bellman-Ford
one when many source (and target) vertices are given, with all-pairs
shortest path length calculations being the typical use case.
igraph can choose automatically between algorithms, and chooses the most
efficient one that is appropriate for the supplied weights (if any). For
automatic algorithm selection, supply ‘automatic
’ as the
algorithm
argument. (This is also the default.)
shortest_paths()
calculates a single shortest path (i.e. the path
itself, not just its length) between the source vertex given in from
,
to the target vertices given in to
. shortest_paths()
uses
breadth-first search for unweighted graphs and Dijkstra's algorithm for
weighted graphs. The latter only works if the edge weights are non-negative.
all_shortest_paths()
calculates all shortest paths between
pairs of vertices, including several shortest paths of the same length.
More precisely, it computerd all shortest path starting at from
, and
ending at any vertex given in to
. It uses a breadth-first search for
unweighted graphs and Dijkstra's algorithm for weighted ones. The latter
only supports non-negative edge weights. Caution: in multigraphs, the
result size is exponentially large in the number of vertex pairs with
multiple edges between them.
mean_distance()
calculates the average path length in a graph, by
calculating the shortest paths between all pairs of vertices (both ways for
directed graphs). It uses a breadth-first search for unweighted graphs and
Dijkstra's algorithm for weighted ones. The latter only supports non-negative
edge weights.
distance_table()
calculates a histogram, by calculating the shortest
path length between each pair of vertices. For directed graphs both
directions are considered, so every pair of vertices appears twice in the
histogram.
For distances()
a numeric matrix with length(to)
columns and length(v)
rows. The shortest path length from a vertex to
itself is always zero. For unreachable vertices Inf
is included.
For shortest_paths()
a named list with four entries is returned:
vpath |
This itself is a list, of length |
epath |
This is a list similar to |
predecessors |
Numeric vector, the
predecessor of each vertex in the |
inbound_edges |
Numeric vector, the inbound edge
for each vertex, or |
For all_shortest_paths()
a list is returned, each list element
contains a shortest path from from
to a vertex in to
. The
shortest paths to the same vertex are collected into consecutive elements
of the list.
For mean_distance()
a single number is returned if details=FALSE
,
or a named list with two entries: res
is the mean distance as a numeric
scalar and unconnected
is the number of unconnected vertex pairs,
also as a numeric scalar.
distance_table()
returns a named list with two entries: res
is
a numeric vector, the histogram of distances, unconnected
is a
numeric scalar, the number of pairs for which the first vertex is not
reachable from the second. In undirected and directed graphs, unorderde
and ordered pairs are considered, respectively. Therefore the sum of the
two entries is always for directed graphs and
for undirected graphs.
igraph_path_length_hist()
, igraph_average_path_length_dijkstra()
.
Gabor Csardi [email protected]
West, D.B. (1996). Introduction to Graph Theory. Upper Saddle River, N.J.: Prentice Hall.
Other structural.properties:
bfs()
,
component_distribution()
,
connect()
,
constraint()
,
coreness()
,
degree()
,
dfs()
,
edge_density()
,
feedback_arc_set()
,
girth()
,
is_acyclic()
,
is_dag()
,
is_matching()
,
k_shortest_paths()
,
knn()
,
reciprocity()
,
subcomponent()
,
subgraph()
,
topo_sort()
,
transitivity()
,
unfold_tree()
,
which_multiple()
,
which_mutual()
Other paths:
all_simple_paths()
,
diameter()
,
eccentricity()
,
graph_center()
,
radius()
g <- make_ring(10) distances(g) shortest_paths(g, 5) all_shortest_paths(g, 1, 6:8) mean_distance(g) ## Weighted shortest paths el <- matrix( ncol = 3, byrow = TRUE, c( 1, 2, 0, 1, 3, 2, 1, 4, 1, 2, 3, 0, 2, 5, 5, 2, 6, 2, 3, 2, 1, 3, 4, 1, 3, 7, 1, 4, 3, 0, 4, 7, 2, 5, 6, 2, 5, 8, 8, 6, 3, 2, 6, 7, 1, 6, 9, 1, 6, 10, 3, 8, 6, 1, 8, 9, 1, 9, 10, 4 ) ) g2 <- add_edges(make_empty_graph(10), t(el[, 1:2]), weight = el[, 3]) distances(g2, mode = "out")
g <- make_ring(10) distances(g) shortest_paths(g, 5) all_shortest_paths(g, 1, 6:8) mean_distance(g) ## Weighted shortest paths el <- matrix( ncol = 3, byrow = TRUE, c( 1, 2, 0, 1, 3, 2, 1, 4, 1, 2, 3, 0, 2, 5, 5, 2, 6, 2, 3, 2, 1, 3, 4, 1, 3, 7, 1, 4, 3, 0, 4, 7, 2, 5, 6, 2, 5, 8, 8, 6, 3, 2, 6, 7, 1, 6, 9, 1, 6, 10, 3, 8, 6, 1, 8, 9, 1, 9, 10, 4 ) ) g2 <- add_edges(make_empty_graph(10), t(el[, 1:2]), weight = el[, 3]) distances(g2, mode = "out")
This is the ‘PuOr’ palette from https://colorbrewer2.org/. It has at most eleven colors.
diverging_pal(n)
diverging_pal(n)
n |
The number of colors in the palette. The maximum is eleven currently. |
This is similar to sequential_pal()
, but it also puts
emphasis on the mid-range values, plus the the two extreme ends.
Use this palette, if you have such a quantity to mark with vertex
colors.
A character vector of RGB color codes.
Other palettes:
categorical_pal()
,
r_pal()
,
sequential_pal()
library(igraphdata) data(foodwebs) fw <- foodwebs[[1]] %>% induced_subgraph(V(.)[ECO == 1]) %>% add_layout_(with_fr()) %>% set_vertex_attr("label", value = seq_len(gorder(.))) %>% set_vertex_attr("size", value = 10) %>% set_edge_attr("arrow.size", value = 0.3) V(fw)$color <- scales::dscale(V(fw)$Biomass %>% cut(10), diverging_pal) plot(fw) data(karate) karate <- karate %>% add_layout_(with_kk()) %>% set_vertex_attr("size", value = 10) V(karate)$color <- scales::dscale(degree(karate) %>% cut(5), diverging_pal) plot(karate)
library(igraphdata) data(foodwebs) fw <- foodwebs[[1]] %>% induced_subgraph(V(.)[ECO == 1]) %>% add_layout_(with_fr()) %>% set_vertex_attr("label", value = seq_len(gorder(.))) %>% set_vertex_attr("size", value = 10) %>% set_edge_attr("arrow.size", value = 0.3) V(fw)$color <- scales::dscale(V(fw)$Biomass %>% cut(10), diverging_pal) plot(fw) data(karate) karate <- karate %>% add_layout_(with_kk()) %>% set_vertex_attr("size", value = 10) V(karate)$color <- scales::dscale(degree(karate) %>% cut(5), diverging_pal) plot(karate)
Calculates a measure of diversity for all vertices.
diversity(graph, weights = NULL, vids = V(graph))
diversity(graph, weights = NULL, vids = V(graph))
graph |
The input graph. Edge directions are ignored. |
weights |
|
vids |
The vertex ids for which to calculate the measure. |
The diversity of a vertex is defined as the (scaled) Shannon entropy of the weights of its incident edges:
and
where
and is the (total) degree of vertex
,
is the weight of the edge(s) between vertices
and
.
For vertices with degree less than two the function returns NaN
.
A numeric vector, its length is the number of vertices.
Gabor Csardi [email protected]
Nathan Eagle, Michael Macy and Rob Claxton: Network Diversity and Economic Development, Science 328, 1029–1031, 2010.
Centrality measures
alpha_centrality()
,
authority_score()
,
betweenness()
,
closeness()
,
eigen_centrality()
,
harmonic_centrality()
,
hits_scores()
,
page_rank()
,
power_centrality()
,
spectrum()
,
strength()
,
subgraph_centrality()
g1 <- sample_gnp(20, 2 / 20) g2 <- sample_gnp(20, 2 / 20) g3 <- sample_gnp(20, 5 / 20) E(g1)$weight <- 1 E(g2)$weight <- runif(ecount(g2)) E(g3)$weight <- runif(ecount(g3)) diversity(g1) diversity(g2) diversity(g3)
g1 <- sample_gnp(20, 2 / 20) g2 <- sample_gnp(20, 2 / 20) g3 <- sample_gnp(20, 5 / 20) E(g1)$weight <- 1 E(g2)$weight <- runif(ecount(g2)) E(g3)$weight <- runif(ecount(g3)) diversity(g1) diversity(g2) diversity(g3)
Dominator tree of a directed graph.
dominator_tree(graph, root, mode = c("out", "in", "all", "total"))
dominator_tree(graph, root, mode = c("out", "in", "all", "total"))
graph |
A directed graph. If it is not a flowgraph, and it contains some vertices not reachable from the root vertex, then these vertices will be collected and returned as part of the result. |
root |
The id of the root (or source) vertex, this will be the root of the tree. |
mode |
Constant, must be ‘ |
A flowgraph is a directed graph with a distinguished start (or root) vertex
, such that for any vertex
, there is a path from
to
. A vertex
dominates another vertex
(not equal to
), if every path from
to
contains
. Vertex
is the immediate dominator or
,
, if
dominates
and every
other dominator of
dominates
. The edges
form a
directed tree, rooted at
, called the dominator tree of the graph.
Vertex
dominates vertex
if and only if
is an
ancestor of
in the dominator tree.
This function implements the Lengauer-Tarjan algorithm to construct the dominator tree of a directed graph. For details see the reference below.
A list with components:
dom |
A numeric vector giving the
immediate dominators for each vertex. For vertices that are unreachable from
the root, it contains |
domtree |
A graph object, the dominator tree. Its vertex ids are the as the vertex ids of the input graph. Isolate vertices are the ones that are unreachable from the root. |
leftout |
A numeric vector containing the vertex ids that are unreachable from the root. |
Gabor Csardi [email protected]
Thomas Lengauer, Robert Endre Tarjan: A fast algorithm for finding dominators in a flowgraph, ACM Transactions on Programming Languages and Systems (TOPLAS) I/1, 121–141, 1979.
Other flow:
edge_connectivity()
,
is_min_separator()
,
is_separator()
,
max_flow()
,
min_cut()
,
min_separators()
,
min_st_separators()
,
st_cuts()
,
st_min_cuts()
,
vertex_connectivity()
## The example from the paper g <- graph_from_literal( R -+ A:B:C, A -+ D, B -+ A:D:E, C -+ F:G, D -+ L, E -+ H, F -+ I, G -+ I:J, H -+ E:K, I -+ K, J -+ I, K -+ I:R, L -+ H ) dtree <- dominator_tree(g, root = "R") layout <- layout_as_tree(dtree$domtree, root = "R") layout[, 2] <- -layout[, 2] plot(dtree$domtree, layout = layout, vertex.label = V(dtree$domtree)$name)
## The example from the paper g <- graph_from_literal( R -+ A:B:C, A -+ D, B -+ A:D:E, C -+ F:G, D -+ L, E -+ H, F -+ I, G -+ I:J, H -+ E:K, I -+ K, J -+ I, K -+ I:R, L -+ H ) dtree <- dominator_tree(g, root = "R") layout <- layout_as_tree(dtree$domtree, root = "R") layout[, 2] <- -layout[, 2] plot(dtree$domtree, layout = layout, vertex.label = V(dtree$domtree)$name)
.data
and .env
pronounsThe .data
and .env
pronouns make it explicit where to look up attribute
names when indexing V(g)
or E(g)
, i.e. the vertex or edge sequence of a
graph. These pronouns are inspired by .data
and .env
in rlang
- thanks
to Michał Bojanowski for bringing these to our attention.
The rules are simple:
.data
retrieves attributes from the graph whose vertex or edge sequence
is being evaluated.
.env
retrieves variables from the calling environment.
Note that .data
and .env
are injected dynamically into the environment
where the indexing expressions are evaluated; you cannot get access to these
objects outside the context of an indexing expression. To avoid warnings
printed by R CMD check
when code containing .data
and .env
is checked,
you can import .data
and .env
from igraph
if needed. Alternatively,
you can declare them explicitly with utils::globalVariables()
to silence
the warnings.
The common bits of the three plotting functions
plot.igraph
, tkplot
and rglplot
are discussed in
this manual page
There are currently three different functions in the igraph package which can draw graph in various ways:
plot.igraph
does simple non-interactive 2D plotting to R devices.
Actually it is an implementation of the plot
generic function,
so you can write plot(graph)
instead of
plot.igraph(graph)
. As it used the standard R devices it
supports every output format for which R has an output device. The
list is quite impressing: PostScript, PDF files, XFig files, SVG
files, JPG, PNG and of course you can plot to the screen as well using
the default devices, or the good-looking anti-aliased Cairo device.
See plot.igraph
for some more information.
tkplot
does interactive 2D plotting using the tcltk
package. It can only handle graphs of moderate size, a thousand
vertices is probably already too many. Some parameters of the plotted
graph can be changed interactively after issuing the tkplot
command: the position, color and size of the vertices and the color
and width of the edges. See tkplot
for details.
rglplot
is an experimental function to draw graphs in 3D
using OpenGL. See rglplot
for some more information.
Please also check the examples below.
There are three ways to give values to the parameters described below, in section 'Parameters'. We give these three ways here in the order of their precedence.
The first method is to supply named arguments to the plotting commands:
plot.igraph
, tkplot
or
rglplot
. Parameters for vertices start with prefix
‘vertex.
’, parameters for edges have prefix
‘edge.
’, and global parameters have no prefix. Eg. the
color of the vertices can be given via argument vertex.color
,
whereas edge.color
sets the color of the edges. layout
gives the layout of the graphs.
The second way is to assign vertex, edge and graph attributes to the
graph. These attributes have no prefix, ie. the color of the vertices
is taken from the color
vertex attribute and the color of the
edges from the color
edge attribute. The layout of the graph is
given by the layout
graph attribute. (Always assuming that the
corresponding command argument is not present.) Setting vertex and
edge attributes are handy if you want to assign a given ‘look’
to a graph, attributes are saved with the graph is you save it with
save
or in GraphML format with
write_graph
, so the graph will have the same look after
loading it again.
If a parameter is not given in the command line, and the corresponding
vertex/edge/graph attribute is also missing then the general igraph
parameters handled by igraph_options
are also
checked. Vertex parameters have prefix ‘vertex.
’, edge
parameters are prefixed with ‘edge.
’, general parameters
like layout
are prefixed with ‘plot
’.
These parameters are useful if you want
all or most of your graphs to have the same look, vertex size, vertex
color, etc. Then you don't need to set these at every plotting, and
you also don't need to assign vertex/edge attributes to every graph.
If the value of a parameter is not specified by any of the three ways described here, its default valued is used, as given in the source code.
Different parameters can have different type, eg. vertex colors can be given as a character vector with color names, or as an integer vector with the color numbers from the current palette. Different types are valid for different parameters, this is discussed in detail in the next section. It is however always true that the parameter can always be a function object in which it will be called with the graph as its single argument to get the “proper” value of the parameter. (If the function returns another function object that will not be called again...)
Vertex parameters first, note that the ‘vertex.
’ prefix
needs to be added if they are used as an argument or when setting via
igraph_options
. The value of the parameter may be scalar
valid for every vertex or a vector with a separate value for each
vertex. (Shorter vectors are recycled.)
The size of the vertex, a numeric scalar or vector, in the latter case each vertex sizes may differ. This vertex sizes are scaled in order have about the same size of vertices for a given value for all three plotting commands. It does not need to be an integer number.
The default value is 15. This is big enough to place short labels on vertices.
The “other” size of the vertex, for some vertex
shapes. For the various rectangle shapes this gives the height of
the vertices, whereas size
gives the width. It is ignored
by shapes for which the size can be specified with a single
number.
The default is 15.
The fill color of the vertex. If it is numeric then
the current palette is used, see
palette
. If it is a character vector then
it may either contain integer values, named colors or RGB
specified colors with three or four bytes. All strings starting
with ‘#
’ are assumed to be RGB color
specifications. It is possible to mix named color and RGB
colors. Note that tkplot
ignores the fourth byte
(alpha channel) in the RGB color specification.
For plot.igraph
and integer values, the default igraph
palette is used (see the ‘palette’ parameter below. Note
that this is different from the R palette.
If you don't want (some) vertices to have any color, supply
NA
as the color name.
The default value is “SkyBlue2
”.
The color of the frame of the vertices, the same formats are allowed as for the fill color.
If you don't want vertices to have a frame, supply NA
as
the color name.
By default it is “black”.
The width of the frame of the vertices.
The default value is 1.
The shape of the vertex, currently
“circle
”, “square
”,
“csquare
”, “rectangle
”,
“crectangle
”, “vrectangle
”,
“pie
” (see vertex.shape.pie),
‘sphere
’, and “none
” are supported,
and only by the plot.igraph
command. “none
” does not draw the vertices at all,
although vertex label are plotted (if given). See
shapes
for details about vertex
shapes and vertex.shape.pie
for using pie charts as
vertices.
The “sphere
” vertex shape plots vertices as 3D
ray-traced spheres, in the given color and size. This produces a
raster image and it is only supported with some graphics
devices. On some devices raster transparency is not supported and
the spheres do not have a transparent background. See
dev.capabilities
and the ‘rasterImage
’
capability to check that your device is supported.
By default vertices are drawn as circles.
The vertex labels. They will be converted to
character. Specify NA
to omit vertex labels.
The default vertex labels are the vertex ids.
The font family to be used for vertex labels.
As different plotting commands can used different fonts, they
interpret this parameter different ways. The basic notation is,
however, understood by both plot.igraph
and
tkplot
. rglplot
does not support fonts
at all right now, it ignores this parameter completely.
For plot.igraph
this parameter is simply passed to
text
as argument family
.
For tkplot
some
conversion is performed. If this parameter is the name of an
existing Tk font, then that font is used and the label.font
and label.cex
parameters are ignored completely. If it is
one of the base families (serif, sans, mono) then Times,
Helvetica or Courier fonts are used, there are guaranteed to exist
on all systems. For the ‘symbol’ base family we used the
symbol font is available, otherwise the first font which has
‘symbol’ in its name. If the parameter is not a name of the
base families and it is also not a named Tk font then we pass it
to tkfont.create
and hope the user knows what
she is doing. The label.font
and label.cex
parameters are also passed to tkfont.create
in this case.
The default value is ‘serif’.
The font within the font family to use for the
vertex labels. It is interpreted the same way as the the
font
graphical parameter: 1 is plain text, 2 is bold face,
3 is italic, 4 is bold and italic and 5 specifies the symbol
font.
For plot.igraph
this parameter is simply passed to
text
.
For tkplot
, if the label.family
parameter is
not the name of a Tk font then this parameter is used to set
whether the newly created font should be italic and/or
boldface. Otherwise it is ignored.
For rglplot
it is ignored.
The default value is 1.
The font size for vertex labels. It is interpreted as a multiplication factor of some device-dependent base font size.
For plot.igraph
it is simply passed to
text
as argument cex
.
For tkplot
it is multiplied by 12 and then used as
the size
argument for tkfont.create
.
The base font is thus 12 for tkplot.
For rglplot
it is ignored.
The default value is 1.
The distance of the label from the center of the vertex. If it is 0 then the label is centered on the vertex. If it is 1 then the label is displayed beside the vertex.
The default value is 0.
It defines the position of the vertex labels, relative to the
center of the vertices. It is interpreted as an angle in radians,
zero means ‘to the right’, and ‘pi
’ means to
the left, up is -pi/2
and down is pi/2
.
The default value is -pi/4
.
The color of the labels, see the color
vertex parameter discussed earlier for the possible values.
The default value is black
.
Edge parameters require to add the ‘edge.
’ prefix when
used as arguments or set by igraph_options
. The edge
parameters:
The color of the edges, see the color
vertex
parameter for the possible values.
By default this parameter is darkgrey
.
The width of the edges.
The default value is 1.
The size of the arrows. Currently this is a constant, so it is the same for every edge. If a vector is submitted then only the first element is used, ie. if this is taken from an edge attribute then only the attribute of the first edge is used for all arrows. This will likely change in the future.
The default value is 1.
The width of the arrows. Currently this is a constant, so it is the same for every edge. If a vector is submitted then only the first element is used, ie. if this is taken from an edge attribute then only the attribute of the first edge is used for all arrows. This will likely change in the future.
This argument is currently only used by plot.igraph
.
The default value is 1, which gives the same width as before this option appeared in igraph.
The line type for the edges. Almost the same format is
accepted as for the standard graphics par
,
0 and “blank” mean no edges, 1 and “solid” are for
solid lines, the other possible values are: 2 (“dashed”),
3 (“dotted”), 4 (“dotdash”), 5 (“longdash”),
6 (“twodash”).
tkplot
also accepts standard Tk line type strings,
it does not however support “blank” lines, instead of type
‘0’ type ‘1’, ie. solid lines will be drawn.
This argument is ignored for rglplot
.
The default value is type 1, a solid line.
The edge labels. They will be converted to
character. Specify NA
to omit edge labels.
Edge labels are omitted by default.
Font family of the edge labels. See the vertex parameter with the same name for the details.
The font for the edge labels. See the corresponding vertex parameter discussed earlier for details.
The font size for the edge labels, see the corresponding vertex parameter for details.
The color of the edge labels, see the
color
vertex parameters on how to specify colors.
The horizontal coordinates of the edge labels might
be given here, explicitly. The NA
elements will be
replaced by automatically calculated coordinates. If NULL
,
then all edge horizontal coordinates are calculated
automatically. This parameter is only supported by
plot.igraph
.
The same as label.x
, but for vertical
coordinates.
Specifies whether to draw curved edges, or not. This can be a logical or a numeric vector or scalar.
First the vector is replicated to have the same length as the
number of edges in the graph. Then it is interpreted for each edge
separately. A numeric value specifies the curvature of the edge;
zero curvature means straight edges, negative values means the
edge bends clockwise, positive values the opposite. TRUE
means curvature 0.5, FALSE
means curvature zero.
By default the vector specifying the curvature is calculated via a
call to the curve_multiple
function. This function makes
sure that multiple edges are curved and are all visible. This
parameter is ignored for loop edges.
The default value is FALSE
.
This parameter is currently ignored by rglplot
.
This parameter can be used to specify for which edges should arrows be drawn. If this parameter is given by the user (in either of the three ways) then it specifies which edges will have forward, backward arrows, or both, or no arrows at all. As usual, this parameter can be a vector or a scalar value. It can be an integer or character type. If it is integer then 0 means no arrows, 1 means backward arrows, 2 is for forward arrows and 3 for both. If it is a character vector then “<” and “<-” specify backward, “>” and “->” forward arrows and “<>” and “<->” stands for both arrows. All other values mean no arrows, perhaps you should use “-” or “–” to specify no arrows.
Hint: this parameter can be used as a ‘cheap’ solution for drawing “mixed” graphs: graphs in which some edges are directed some are not. If you want do this, then please create a directed graph, because as of version 0.4 the vertex pairs in the edge lists can be swapped in undirected graphs.
By default, no arrows will be drawn for undirected graphs, and for directed graphs, an arrow will be drawn for each edge, according to its direction. This is not very surprising, it is the expected behavior.
Gives the angle in radians for plotting loop
edges. See the label.dist
vertex parameter to see how this
is interpreted.
The default value is 0.
Gives the second angle in radians for plotting
loop edges. This is only used in 3D, loop.angle
is enough
in 2D.
The default value is 0.
Other parameters:
Either a function or a numeric matrix. It specifies how the vertices will be placed on the plot.
If it is a numeric matrix, then the matrix has to have one line for
each vertex, specifying its coordinates. The matrix should have at
least two columns, for the x
and y
coordinates, and
it can also have third column, this will be the z
coordinate for 3D plots and it is ignored for 2D plots.
If a two column matrix is given for the 3D plotting function
rglplot
then the third column is assumed to be 1 for
each vertex.
If layout
is a function, this function will be called with the
graph
as the single parameter to determine the
actual coordinates. The function should return a matrix with two
or three columns. For the 2D plots the third column is ignored.
The default value is layout_nicely
, a smart function that
chooses a layout based on the graph.
The amount of empty space below, over, at the left and right of the plot, it is a numeric vector of length four. Usually values between 0 and 0.5 are meaningful, but negative values are also possible, that will make the plot zoom in to a part of the graph. If it is shorter than four then it is recycled.
rglplot
does not support this parameter, as it can
zoom in and out the graph in a more flexible way.
Its default value is 0.
The color palette to use for vertex color.
The default is categorical_pal
, which is a
color-blind friendly categorical palette. See its manual page
for details and other palettes. This parameters is only supported
by plot
, and not by tkplot
and rglplot
.
Logical constant, whether to rescale the coordinates
to the [-1,1]x[-1,1](x[-1,1]) interval. This parameter is not
implemented for tkplot
.
Defaults to TRUE
, the layout will be rescaled.
A numeric constant, it gives the asp
parameter
for plot
, the aspect ratio. Supply 0 here if you
don't want to give an aspect ratio. It is ignored by tkplot
and rglplot
.
Defaults to 1.
Boolean, whether to plot a frame around the graph. It
is ignored by tkplot
and rglplot
.
Defaults to FALSE
.
Overall title for the main plot. The default is empty if
the annotate.plot
igraph option is FALSE
, and the
graph's name
attribute otherwise. See the same argument of
the base plot
function. Only supported by plot
.
Subtitle of the main plot, the default is empty. Only
supported by plot
.
Title for the x axis, the default is empty if the
annotate.plot
igraph option is FALSE
, and the number
of vertices and edges, if it is TRUE
. Only supported by
plot
.
Title for the y axis, the default is empty. Only
supported by plot
.
Gabor Csardi [email protected]
plot.igraph
, tkplot
,
rglplot
, igraph_options
## Not run: # plotting a simple ring graph, all default parameters, except the layout g <- make_ring(10) g$layout <- layout_in_circle plot(g) tkplot(g) rglplot(g) # plotting a random graph, set the parameters in the command arguments g <- barabasi.game(100) plot(g, layout=layout_with_fr, vertex.size=4, vertex.label.dist=0.5, vertex.color="red", edge.arrow.size=0.5) # plot a random graph, different color for each component g <- sample_gnp(100, 1/100) comps <- components(g)$membership colbar <- rainbow(max(comps)+1) V(g)$color <- colbar[comps+1] plot(g, layout=layout_with_fr, vertex.size=5, vertex.label=NA) # plot communities in a graph g <- make_full_graph(5) %du% make_full_graph(5) %du% make_full_graph(5) g <- add_edges(g, c(1,6, 1,11, 6,11)) com <- cluster_spinglass(g, spins=5) V(g)$color <- com$membership+1 g <- set_graph_attr(g, "layout", layout_with_kk(g)) plot(g, vertex.label.dist=1.5) # draw a bunch of trees, fix layout igraph_options(plot.layout=layout_as_tree) plot(make_tree(20, 2)) plot(make_tree(50, 3), vertex.size=3, vertex.label=NA) tkplot(make_tree(50, 2, mode="undirected"), vertex.size=10, vertex.color="green") ## End(Not run)
## Not run: # plotting a simple ring graph, all default parameters, except the layout g <- make_ring(10) g$layout <- layout_in_circle plot(g) tkplot(g) rglplot(g) # plotting a random graph, set the parameters in the command arguments g <- barabasi.game(100) plot(g, layout=layout_with_fr, vertex.size=4, vertex.label.dist=0.5, vertex.color="red", edge.arrow.size=0.5) # plot a random graph, different color for each component g <- sample_gnp(100, 1/100) comps <- components(g)$membership colbar <- rainbow(max(comps)+1) V(g)$color <- colbar[comps+1] plot(g, layout=layout_with_fr, vertex.size=5, vertex.label=NA) # plot communities in a graph g <- make_full_graph(5) %du% make_full_graph(5) %du% make_full_graph(5) g <- add_edges(g, c(1,6, 1,11, 6,11)) com <- cluster_spinglass(g, spins=5) V(g)$color <- com$membership+1 g <- set_graph_attr(g, "layout", layout_with_kk(g)) plot(g, vertex.label.dist=1.5) # draw a bunch of trees, fix layout igraph_options(plot.layout=layout_as_tree) plot(make_tree(20, 2)) plot(make_tree(50, 3), vertex.size=3, vertex.label=NA) tkplot(make_tree(50, 2, mode="undirected"), vertex.size=10, vertex.color="green") ## End(Not run)
Classify dyads in a directed graphs. The relationship between each pair of vertices is measured. It can be in three states: mutual, asymmetric or non-existent.
dyad_census(graph)
dyad_census(graph)
graph |
The input graph. A warning is given if it is not directed. |
A named numeric vector with three elements:
mut |
The number of pairs with mutual connections. |
asym |
The number of pairs with non-mutual connections. |
null |
The number of pairs with no connection between them. |
Gabor Csardi [email protected]
Holland, P.W. and Leinhardt, S. A Method for Detecting Structure in Sociometric Data. American Journal of Sociology, 76, 492–513. 1970.
Wasserman, S., and Faust, K. Social Network Analysis: Methods and Applications. Cambridge: Cambridge University Press. 1994.
triad_census()
for the same classification, but with
triples.
Other graph motifs:
count_motifs()
,
motifs()
,
sample_motifs()
g <- sample_pa(100) dyad_census(g)
g <- sample_pa(100) dyad_census(g)
An edge sequence is a vector containing numeric edge ids, with a special class attribute that allows custom operations: selecting subsets of edges based on attributes, or graph structure, creating the intersection, union of edges, etc.
E(graph, P = NULL, path = NULL, directed = TRUE)
E(graph, P = NULL, path = NULL, directed = TRUE)
graph |
The graph. |
P |
A list of vertices to select edges via pairs of vertices. The first and second vertices select the first edge, the third and fourth the second, etc. |
path |
A list of vertices, to select edges along a path. Note that this only works reliable for simple graphs. If the graph has multiple edges, one of them will be chosen arbitrarily to be included in the edge sequence. |
directed |
Whether to consider edge directions in the |
Edge sequences are usually used as igraph function arguments that refer to edges of a graph.
An edge sequence is tied to the graph it refers to: it really denoted the specific edges of that graph, and cannot be used together with another graph.
An edge sequence is most often created by the E()
function. The
result includes edges in increasing edge id order by default (if. none
of the P
and path
arguments are used). An edge
sequence can be indexed by a numeric vector, just like a regular R
vector. See links to other edge sequence operations below.
An edge sequence of the graph.
Edge sequences mostly behave like regular vectors, but there are some
additional indexing operations that are specific for them;
e.g. selecting edges based on graph structure, or based on edge
attributes. See [.igraph.es
for details.
Edge sequences can be used to query or set attributes for the
edges in the sequence. See $.igraph.es()
for details.
Other vertex and edge sequences:
V()
,
as_ids()
,
igraph-es-attributes
,
igraph-es-indexing
,
igraph-es-indexing2
,
igraph-vs-attributes
,
igraph-vs-indexing
,
igraph-vs-indexing2
,
print.igraph.es()
,
print.igraph.vs()
# Edges of an unnamed graph g <- make_ring(10) E(g) # Edges of a named graph g2 <- make_ring(10) %>% set_vertex_attr("name", value = letters[1:10]) E(g2)
# Edges of an unnamed graph g <- make_ring(10) E(g) # Edges of a named graph g2 <- make_ring(10) %>% set_vertex_attr("name", value = letters[1:10]) E(g2)
This function can be used together with rewire()
.
This method rewires the endpoints of the edges with a constant probability
uniformly randomly to a new vertex in a graph.
each_edge( prob, loops = FALSE, multiple = FALSE, mode = c("all", "out", "in", "total") )
each_edge( prob, loops = FALSE, multiple = FALSE, mode = c("all", "out", "in", "total") )
prob |
The rewiring probability, a real number between zero and one. |
loops |
Logical scalar, whether loop edges are allowed in the rewired graph. |
multiple |
Logical scalar, whether multiple edges are allowed in the generated graph. |
mode |
Character string, specifies which endpoint of the edges to rewire in directed graphs. ‘all’ rewires both endpoints, ‘in’ rewires the start (tail) of each directed edge, ‘out’ rewires the end (head) of each directed edge. Ignored for undirected graphs. |
Note that this method might create graphs with multiple and/or loop edges.
Gabor Csardi [email protected]
Other rewiring functions:
keeping_degseq()
,
rewire()
# Some random shortcuts shorten the distances on a lattice g <- make_lattice(length = 100, dim = 1, nei = 5) mean_distance(g) g <- rewire(g, each_edge(prob = 0.05)) mean_distance(g) # Rewiring the start of each directed edge preserves the in-degree distribution # but not the out-degree distribution g <- sample_pa(1000) g2 <- g %>% rewire(each_edge(mode = "in", multiple = TRUE, prob = 0.2)) degree(g, mode = "in") == degree(g2, mode = "in")
# Some random shortcuts shorten the distances on a lattice g <- make_lattice(length = 100, dim = 1, nei = 5) mean_distance(g) g <- rewire(g, each_edge(prob = 0.05)) mean_distance(g) # Rewiring the start of each directed edge preserves the in-degree distribution # but not the out-degree distribution g <- sample_pa(1000) g2 <- g %>% rewire(each_edge(mode = "in", multiple = TRUE, prob = 0.2)) degree(g, mode = "in") == degree(g2, mode = "in")
The eccentricity of a vertex is its shortest path distance from the farthest other node in the graph.
eccentricity( graph, vids = V(graph), ..., weights = NULL, mode = c("all", "out", "in", "total") )
eccentricity( graph, vids = V(graph), ..., weights = NULL, mode = c("all", "out", "in", "total") )
graph |
The input graph, it can be directed or undirected. |
vids |
The vertices for which the eccentricity is calculated. |
... |
These dots are for future extensions and must be empty. |
weights |
Possibly a numeric vector giving edge weights. If this is
|
mode |
Character constant, gives whether the shortest paths to or from
the given vertices should be calculated for directed graphs. If |
The eccentricity of a vertex is calculated by measuring the shortest distance from (or to) the vertex, to (or from) all vertices in the graph, and taking the maximum.
This implementation ignores vertex pairs that are in different components. Isolate vertices have eccentricity zero.
eccentricity()
returns a numeric vector, containing the
eccentricity score of each given vertex.
igraph_eccentricity_dijkstra()
.
Harary, F. Graph Theory. Reading, MA: Addison-Wesley, p. 35, 1994.
radius()
for a related concept,
distances()
for general shortest path calculations.
Other paths:
all_simple_paths()
,
diameter()
,
distance_table()
,
graph_center()
,
radius()
g <- make_star(10, mode = "undirected") eccentricity(g)
g <- make_star(10, mode = "undirected") eccentricity(g)
This is a helper function that simplifies adding and deleting edges to/from graphs.
edge(...) edges(...)
edge(...) edges(...)
... |
See details below. |
edges()
is an alias for edge()
.
When adding edges via +
, all unnamed arguments of
edge()
(or edges()
) are concatenated, and then passed to
add_edges()
. They are interpreted as pairs of vertex ids,
and an edge will added between each pair. Named arguments will be
used as edge attributes for the new edges.
When deleting edges via -
, all arguments of edge()
(or
edges()
) are concatenated via c()
and passed to
delete_edges()
.
A special object that can be used with together with igraph graphs and the plus and minus operators.
Other functions for manipulating graph structure:
+.igraph()
,
add_edges()
,
add_vertices()
,
complementer()
,
compose()
,
connect()
,
contract()
,
delete_edges()
,
delete_vertices()
,
difference()
,
difference.igraph()
,
disjoint_union()
,
igraph-minus
,
intersection()
,
intersection.igraph()
,
path()
,
permute()
,
rep.igraph()
,
reverse_edges()
,
simplify()
,
union()
,
union.igraph()
,
vertex()
g <- make_ring(10) %>% set_edge_attr("color", value = "red") g <- g + edge(1, 5, color = "green") + edge(2, 6, color = "blue") - edge("8|9") E(g)[[]] g %>% add_layout_(in_circle()) %>% plot() g <- make_ring(10) + edges(1:10) plot(g)
g <- make_ring(10) %>% set_edge_attr("color", value = "red") g <- g + edge(1, 5, color = "green") + edge(2, 6, color = "blue") - edge("8|9") E(g)[[]] g %>% add_layout_(in_circle()) %>% plot() g <- make_ring(10) + edges(1:10) plot(g)
Query edge attributes of a graph
edge_attr(graph, name, index = E(graph))
edge_attr(graph, name, index = E(graph))
graph |
The graph |
name |
The name of the attribute to query. If missing, then all edge attributes are returned in a list. |
index |
An optional edge sequence to query edge attributes for a subset of edges. |
The value of the edge attribute, or the list of all
edge attributes if name
is missing.
Vertex, edge and graph attributes
delete_edge_attr()
,
delete_graph_attr()
,
delete_vertex_attr()
,
edge_attr<-()
,
edge_attr_names()
,
graph_attr()
,
graph_attr<-()
,
graph_attr_names()
,
igraph-attribute-combination
,
igraph-dollar
,
igraph-vs-attributes
,
set_edge_attr()
,
set_graph_attr()
,
set_vertex_attr()
,
vertex_attr()
,
vertex_attr<-()
,
vertex_attr_names()
g <- make_ring(10) %>% set_edge_attr("weight", value = 1:10) %>% set_edge_attr("color", value = "red") g plot(g, edge.width = E(g)$weight)
g <- make_ring(10) %>% set_edge_attr("weight", value = 1:10) %>% set_edge_attr("color", value = "red") g plot(g, edge.width = E(g)$weight)
List names of edge attributes
edge_attr_names(graph)
edge_attr_names(graph)
graph |
The graph. |
Character vector, the names of the edge attributes.
Vertex, edge and graph attributes
delete_edge_attr()
,
delete_graph_attr()
,
delete_vertex_attr()
,
edge_attr()
,
edge_attr<-()
,
graph_attr()
,
graph_attr<-()
,
graph_attr_names()
,
igraph-attribute-combination
,
igraph-dollar
,
igraph-vs-attributes
,
set_edge_attr()
,
set_graph_attr()
,
set_vertex_attr()
,
vertex_attr()
,
vertex_attr<-()
,
vertex_attr_names()
g <- make_ring(10) %>% set_edge_attr("label", value = letters[1:10]) edge_attr_names(g) plot(g)
g <- make_ring(10) %>% set_edge_attr("label", value = letters[1:10]) edge_attr_names(g) plot(g)
Set one or more edge attributes
edge_attr(graph, name, index = E(graph)) <- value
edge_attr(graph, name, index = E(graph)) <- value
graph |
The graph. |
name |
The name of the edge attribute to set. If missing,
then |
index |
An optional edge sequence to set the attributes of a subset of edges. |
value |
The new value of the attribute(s) for all
(or |
The graph, with the edge attribute(s) added or set.
Vertex, edge and graph attributes
delete_edge_attr()
,
delete_graph_attr()
,
delete_vertex_attr()
,
edge_attr()
,
edge_attr_names()
,
graph_attr()
,
graph_attr<-()
,
graph_attr_names()
,
igraph-attribute-combination
,
igraph-dollar
,
igraph-vs-attributes
,
set_edge_attr()
,
set_graph_attr()
,
set_vertex_attr()
,
vertex_attr()
,
vertex_attr<-()
,
vertex_attr_names()
g <- make_ring(10) edge_attr(g) <- list( name = LETTERS[1:10], color = rep("green", gsize(g)) ) edge_attr(g, "label") <- E(g)$name g plot(g)
g <- make_ring(10) edge_attr(g) <- list( name = LETTERS[1:10], color = rep("green", gsize(g)) ) edge_attr(g, "label") <- E(g)$name g plot(g)
The edge connectivity of a graph or two vertices, this is recently also called group adhesion.
edge_connectivity(graph, source = NULL, target = NULL, checks = TRUE) edge_disjoint_paths(graph, source, target) adhesion(graph, checks = TRUE)
edge_connectivity(graph, source = NULL, target = NULL, checks = TRUE) edge_disjoint_paths(graph, source, target) adhesion(graph, checks = TRUE)
graph |
The input graph. |
source |
The id of the source vertex, for |
target |
The id of the target vertex, for |
checks |
Logical constant. Whether to check that the graph is connected and also the degree of the vertices. If the graph is not (strongly) connected then the connectivity is obviously zero. Otherwise if the minimum degree is one then the edge connectivity is also one. It is a good idea to perform these checks, as they can be done quickly compared to the connectivity calculation itself. They were suggested by Peter McMahan, thanks Peter. |
A scalar real value.
edge_connectivity()
Edge connectivityThe edge connectivity of a pair of vertices (source
and
target
) is the minimum number of edges needed to remove to eliminate
all (directed) paths from source
to target
.
edge_connectivity()
calculates this quantity if both the source
and target
arguments are given (and not NULL
).
The edge connectivity of a graph is the minimum of the edge connectivity of
every (ordered) pair of vertices in the graph. edge_connectivity()
calculates this quantity if neither the source
nor the target
arguments are given (i.e. they are both NULL
).
edge_disjoint_paths()
The maximum number of edge-disjoint paths between two verticesA set of paths between two vertices is called edge-disjoint if they do not share any edges. The maximum number of edge-disjoint paths are calculated by this function using maximum flow techniques. Directed paths are considered in directed graphs.
A set of edge disjoint paths between two vertices is a set of paths between them containing no common edges. The maximum number of edge disjoint paths between two vertices is the same as their edge connectivity.
When there are no direct edges between the source and the target, the number of vertex-disjoint paths is the same as the vertex connectivity of the two vertices. When some edges are present, each one of them contributes one extra path.
adhesion()
Adhesion of a graphThe adhesion of a graph is the minimum number of edges needed to remove to obtain a graph which is not strongly connected. This is the same as the edge connectivity of the graph.
The three functions documented on this page calculate similar properties,
more precisely the most general is edge_connectivity()
, the others are
included only for having more descriptive function names.
Gabor Csardi [email protected]
Douglas R. White and Frank Harary (2001): The cohesiveness of blocks in social networks: node connectivity and conditional density, Sociological Methodology, vol. 31, 2001, pp. 305–59.
Other flow:
dominator_tree()
,
is_min_separator()
,
is_separator()
,
max_flow()
,
min_cut()
,
min_separators()
,
min_st_separators()
,
st_cuts()
,
st_min_cuts()
,
vertex_connectivity()
g <- sample_pa(100, m = 1) g2 <- sample_pa(100, m = 5) edge_connectivity(g, 100, 1) edge_connectivity(g2, 100, 1) edge_disjoint_paths(g2, 100, 1) g <- sample_gnp(50, 5 / 50) g <- as_directed(g) g <- induced_subgraph(g, subcomponent(g, 1)) adhesion(g)
g <- sample_pa(100, m = 1) g2 <- sample_pa(100, m = 5) edge_connectivity(g, 100, 1) edge_connectivity(g2, 100, 1) edge_disjoint_paths(g2, 100, 1) g <- sample_gnp(50, 5 / 50) g <- as_directed(g) g <- induced_subgraph(g, subcomponent(g, 1)) adhesion(g)
The density of a graph is the ratio of the actual number of edges and the largest possible number of edges in the graph, assuming that no multi-edges are present.
edge_density(graph, loops = FALSE)
edge_density(graph, loops = FALSE)
graph |
The input graph. |
loops |
Logical constant, whether loop edges may exist in the graph. This affects the calculation of the largest possible number of edges in the graph. If this parameter is set to FALSE yet the graph contains self-loops, the result will not be meaningful. |
The concept of density is ill-defined for multigraphs. Note that this function does not check whether the graph has multi-edges and will return meaningless results for such graphs.
A real constant. This function returns NaN
(=0.0/0.0) for an
empty graph with zero vertices.
Gabor Csardi [email protected]
Wasserman, S., and Faust, K. (1994). Social Network Analysis: Methods and Applications. Cambridge: Cambridge University Press.
vcount()
, ecount()
, simplify()
to get rid of the multiple and/or loop edges.
Other structural.properties:
bfs()
,
component_distribution()
,
connect()
,
constraint()
,
coreness()
,
degree()
,
dfs()
,
distance_table()
,
feedback_arc_set()
,
girth()
,
is_acyclic()
,
is_dag()
,
is_matching()
,
k_shortest_paths()
,
knn()
,
reciprocity()
,
subcomponent()
,
subgraph()
,
topo_sort()
,
transitivity()
,
unfold_tree()
,
which_multiple()
,
which_mutual()
edge_density(make_empty_graph(n = 10)) # empty graphs have density 0 edge_density(make_full_graph(n = 10)) # complete graphs have density 1 edge_density(sample_gnp(n = 100, p = 0.4)) # density will be close to p # loop edges g <- make_graph(c(1, 2, 2, 2, 2, 3)) # graph with a self-loop edge_density(g, loops = FALSE) # this is wrong!!! edge_density(g, loops = TRUE) # this is right!!! edge_density(simplify(g), loops = FALSE) # this is also right, but different
edge_density(make_empty_graph(n = 10)) # empty graphs have density 0 edge_density(make_full_graph(n = 10)) # complete graphs have density 1 edge_density(sample_gnp(n = 100, p = 0.4)) # density will be close to p # loop edges g <- make_graph(c(1, 2, 2, 2, 2, 3)) # graph with a self-loop edge_density(g, loops = FALSE) # this is wrong!!! edge_density(g, loops = TRUE) # this is right!!! edge_density(simplify(g), loops = FALSE) # this is also right, but different
eigen_centrality()
takes a graph (graph
) and returns the
eigenvector centralities of the vertices v
within it.
eigen_centrality( graph, directed = FALSE, scale = deprecated(), weights = NULL, options = arpack_defaults() )
eigen_centrality( graph, directed = FALSE, scale = deprecated(), weights = NULL, options = arpack_defaults() )
graph |
Graph to be analyzed. |
directed |
Logical scalar, whether to consider direction of the edges in directed graphs. It is ignored for undirected graphs. |
scale |
|
weights |
A numerical vector or |
options |
A named list, to override some ARPACK options. See
|
Eigenvector centrality scores correspond to the values of the principal
eigenvector of the graph's adjacency matrix; these scores may, in turn, be
interpreted as arising from a reciprocal process in which the centrality of
each actor is proportional to the sum of the centralities of those actors to
whom he or she is connected. In general, vertices with high eigenvector
centralities are those which are connected to many other vertices which are,
in turn, connected to many others (and so on). The perceptive may realize
that this implies that the largest values will be obtained by individuals in
large cliques (or high-density substructures). This is also intelligible
from an algebraic point of view, with the first eigenvector being closely
related to the best rank-1 approximation of the adjacency matrix (a
relationship which is easy to see in the special case of a diagonalizable
symmetric real matrix via the
decomposition).
The adjacency matrix used in the eigenvector centrality calculation assumes that loop edges are counted twice in undirected graphs; this is because each loop edge has two endpoints that are both connected to the same vertex, and you could traverse the loop edge via either endpoint.
In the directed case, the left eigenvector of the adjacency matrix is calculated. In other words, the centrality of a vertex is proportional to the sum of centralities of vertices pointing to it.
Eigenvector centrality is meaningful only for (strongly) connected graphs. Undirected graphs that are not connected should be decomposed into connected components, and the eigenvector centrality calculated for each separately. This function does not verify that the graph is connected. If it is not, in the undirected case the scores of all but one component will be zeros.
Also note that the adjacency matrix of a directed acyclic graph or the adjacency matrix of an empty graph does not possess positive eigenvalues, therefore the eigenvector centrality is not defined for these graphs. igraph will return an eigenvalue of zero in such cases. The eigenvector centralities will all be equal for an empty graph and will all be zeros for a directed acyclic graph. Such pathological cases can be detected by checking whether the eigenvalue is very close to zero.
From igraph version 0.5 this function uses ARPACK for the underlying
computation, see arpack()
for more about ARPACK in igraph.
A named list with components:
vector |
A vector containing the centrality scores. |
value |
The eigenvalue corresponding to the calculated eigenvector, i.e. the centrality scores. |
options |
A named
list, information about the underlying ARPACK computation. See
|
igraph_eigenvector_centrality()
.
Gabor Csardi [email protected] and Carter T. Butts (http://www.faculty.uci.edu/profile.cfm?faculty_id=5057) for the manual page.
Bonacich, P. (1987). Power and Centrality: A Family of Measures. American Journal of Sociology, 92, 1170-1182.
Centrality measures
alpha_centrality()
,
authority_score()
,
betweenness()
,
closeness()
,
diversity()
,
harmonic_centrality()
,
hits_scores()
,
page_rank()
,
power_centrality()
,
spectrum()
,
strength()
,
subgraph_centrality()
# Generate some test data g <- make_ring(10, directed = FALSE) # Compute eigenvector centrality scores eigen_centrality(g)
# Generate some test data g <- make_ring(10, directed = FALSE) # Compute eigenvector centrality scores eigen_centrality(g)
Spectral decomposition of the adjacency matrices of graphs.
embed_adjacency_matrix( graph, no, weights = NULL, which = c("lm", "la", "sa"), scaled = TRUE, cvec = strength(graph, weights = weights)/(vcount(graph) - 1), options = arpack_defaults() )
embed_adjacency_matrix( graph, no, weights = NULL, which = c("lm", "la", "sa"), scaled = TRUE, cvec = strength(graph, weights = weights)/(vcount(graph) - 1), options = arpack_defaults() )
graph |
The input graph, directed or undirected. |
no |
An integer scalar. This value is the embedding dimension of the
spectral embedding. Should be smaller than the number of vertices. The
largest |
weights |
Optional positive weight vector for calculating a weighted
embedding. If the graph has a |
which |
Which eigenvalues (or singular values, for directed graphs) to use. ‘lm’ means the ones with the largest magnitude, ‘la’ is the ones (algebraic) largest, and ‘sa’ is the (algebraic) smallest eigenvalues. The default is ‘lm’. Note that for directed graphs ‘la’ and ‘lm’ are the equivalent, because the singular values are used for the ordering. |
scaled |
Logical scalar, if |
cvec |
A numeric vector, its length is the number vertices in the graph. This vector is added to the diagonal of the adjacency matrix. |
options |
A named list containing the parameters for the SVD
computation algorithm in ARPACK. By default, the list of values is assigned
the values given by |
This function computes a no
-dimensional Euclidean representation of
the graph based on its adjacency matrix, . This representation is
computed via the singular value decomposition of the adjacency matrix,
.In the case, where the graph is a random dot product graph
generated using latent position vectors in
for each vertex, the
embedding will provide an estimate of these latent vectors.
For undirected graphs the latent positions are calculated as
, where
equals
to the first
no
columns of , and
is
a diagonal matrix containing the top
no
singular values on the
diagonal.
For directed graphs the embedding is defined as the pair
and
. (For undirected graphs
, so it is enough to keep one
of them.)
A list containing with entries:
X |
Estimated latent positions,
an |
Y |
|
D |
The eigenvalues (for undirected graphs) or the singular values (for directed graphs) calculated by the algorithm. |
options |
A named list, information about the underlying ARPACK
computation. See |
igraph_adjacency_spectral_embedding()
.
Sussman, D.L., Tang, M., Fishkind, D.E., Priebe, C.E. A Consistent Adjacency Spectral Embedding for Stochastic Blockmodel Graphs, Journal of the American Statistical Association, Vol. 107(499), 2012
Other embedding:
dim_select()
,
embed_laplacian_matrix()
## A small graph lpvs <- matrix(rnorm(200), 20, 10) lpvs <- apply(lpvs, 2, function(x) { return(abs(x) / sqrt(sum(x^2))) }) RDP <- sample_dot_product(lpvs) embed <- embed_adjacency_matrix(RDP, 5)
## A small graph lpvs <- matrix(rnorm(200), 20, 10) lpvs <- apply(lpvs, 2, function(x) { return(abs(x) / sqrt(sum(x^2))) }) RDP <- sample_dot_product(lpvs) embed <- embed_adjacency_matrix(RDP, 5)
Spectral decomposition of Laplacian matrices of graphs.
embed_laplacian_matrix( graph, no, weights = NULL, which = c("lm", "la", "sa"), type = c("default", "D-A", "DAD", "I-DAD", "OAP"), scaled = TRUE, options = arpack_defaults() )
embed_laplacian_matrix( graph, no, weights = NULL, which = c("lm", "la", "sa"), type = c("default", "D-A", "DAD", "I-DAD", "OAP"), scaled = TRUE, options = arpack_defaults() )
graph |
The input graph, directed or undirected. |
no |
An integer scalar. This value is the embedding dimension of the
spectral embedding. Should be smaller than the number of vertices. The
largest |
weights |
Optional positive weight vector for calculating a weighted
embedding. If the graph has a |
which |
Which eigenvalues (or singular values, for directed graphs) to use. ‘lm’ means the ones with the largest magnitude, ‘la’ is the ones (algebraic) largest, and ‘sa’ is the (algebraic) smallest eigenvalues. The default is ‘lm’. Note that for directed graphs ‘la’ and ‘lm’ are the equivalent, because the singular values are used for the ordering. |
type |
The type of the Laplacian to use. Various definitions exist for the Laplacian of a graph, and one can choose between them with this argument. Possible values:
The default (i.e. type |
scaled |
Logical scalar, if |
options |
A named list containing the parameters for the SVD
computation algorithm in ARPACK. By default, the list of values is assigned
the values given by |
This function computes a no
-dimensional Euclidean representation of
the graph based on its Laplacian matrix, . This representation is
computed via the singular value decomposition of the Laplacian matrix.
They are essentially doing the same as embed_adjacency_matrix()
,
but work on the Laplacian matrix, instead of the adjacency matrix.
A list containing with entries:
X |
Estimated latent positions,
an |
Y |
|
D |
The eigenvalues (for undirected graphs) or the singular values (for directed graphs) calculated by the algorithm. |
options |
A named list, information about the underlying ARPACK
computation. See |
igraph_laplacian_spectral_embedding()
.
Gabor Csardi [email protected]
Sussman, D.L., Tang, M., Fishkind, D.E., Priebe, C.E. A Consistent Adjacency Spectral Embedding for Stochastic Blockmodel Graphs, Journal of the American Statistical Association, Vol. 107(499), 2012
embed_adjacency_matrix()
,
sample_dot_product()
Other embedding:
dim_select()
,
embed_adjacency_matrix()
## A small graph lpvs <- matrix(rnorm(200), 20, 10) lpvs <- apply(lpvs, 2, function(x) { return(abs(x) / sqrt(sum(x^2))) }) RDP <- sample_dot_product(lpvs) embed <- embed_laplacian_matrix(RDP, 5)
## A small graph lpvs <- matrix(rnorm(200), 20, 10) lpvs <- apply(lpvs, 2, function(x) { return(abs(x) / sqrt(sum(x^2))) }) RDP <- sample_dot_product(lpvs) embed <- embed_laplacian_matrix(RDP, 5)
Incident vertices of some graph edges
ends(graph, es, names = TRUE)
ends(graph, es, names = TRUE)
graph |
The input graph |
es |
The sequence of edges to query |
names |
Whether to return vertex names or numeric vertex ids. By default vertex names are used. |
A two column matrix of vertex names or vertex ids.
Other structural queries:
[.igraph()
,
[[.igraph()
,
adjacent_vertices()
,
are_adjacent()
,
get_edge_ids()
,
gorder()
,
gsize()
,
head_of()
,
incident()
,
incident_edges()
,
is_directed()
,
neighbors()
,
tail_of()
g <- make_ring(5) ends(g, E(g))
g <- make_ring(5) ends(g, E(g))
A feedback arc set of a graph is a subset of edges whose removal breaks all cycles in the graph.
feedback_arc_set(graph, weights = NULL, algo = c("approx_eades", "exact_ip"))
feedback_arc_set(graph, weights = NULL, algo = c("approx_eades", "exact_ip"))
graph |
The input graph |
weights |
Potential edge weights. If the graph has an edge
attribute called ‘ |
algo |
Specifies the algorithm to use. “ |
Feedback arc sets are typically used in directed graphs. The removal of a feedback arc set of a directed graph ensures that the remaining graph is a directed acyclic graph (DAG). For undirected graphs, the removal of a feedback arc set ensures that the remaining graph is a forest (i.e. every connected component is a tree).
An edge sequence (by default, but see the return.vs.es
option
of igraph_options()
) containing the feedback arc set.
Peter Eades, Xuemin Lin and W.F.Smyth: A fast and effective heuristic for the feedback arc set problem. Information Processing Letters 47:6, pp. 319-323, 1993
Other structural.properties:
bfs()
,
component_distribution()
,
connect()
,
constraint()
,
coreness()
,
degree()
,
dfs()
,
distance_table()
,
edge_density()
,
girth()
,
is_acyclic()
,
is_dag()
,
is_matching()
,
k_shortest_paths()
,
knn()
,
reciprocity()
,
subcomponent()
,
subgraph()
,
topo_sort()
,
transitivity()
,
unfold_tree()
,
which_multiple()
,
which_mutual()
Graph cycles
girth()
,
has_eulerian_path()
,
is_acyclic()
,
is_dag()
g <- sample_gnm(20, 40, directed = TRUE) feedback_arc_set(g) feedback_arc_set(g, algo = "approx_eades")
g <- sample_gnm(20, 40, directed = TRUE) feedback_arc_set(g) feedback_arc_set(g, algo = "approx_eades")
fit_hrg()
fits a HRG to a given graph. It takes the specified
steps
number of MCMC steps to perform the fitting, or a convergence
criteria if the specified number of steps is zero. fit_hrg()
can start
from a given HRG, if this is given in the hrg()
argument and the
start
argument is TRUE
. It can be converted to the hclust
class using
as.hclust()
provided in this package.
fit_hrg(graph, hrg = NULL, start = FALSE, steps = 0)
fit_hrg(graph, hrg = NULL, start = FALSE, steps = 0)
graph |
The graph to fit the model to. Edge directions are ignored in directed graphs. |
hrg |
A hierarchical random graph model, in the form of an
|
start |
Logical, whether to start the fitting/sampling from the
supplied |
steps |
The number of MCMC steps to make. If this is zero, then the MCMC procedure is performed until convergence. |
fit_hrg()
returns an igraphHRG
object. This is a list
with the following members:
left |
Vector that contains the left children of the internal tree vertices. The first vertex is always the root vertex, so the first element of the vector is the left child of the root vertex. Internal vertices are denoted with negative numbers, starting from -1 and going down, i.e. the root vertex is -1. Leaf vertices are denoted by non-negative number, starting from zero and up. |
right |
Vector that contains the right children of the vertices,
with the same encoding as the |
prob |
The connection probabilities attached to the internal vertices, the first number belongs to the root vertex (i.e. internal vertex -1), the second to internal vertex -2, etc. |
edges |
The number of edges in the subtree below the given internal vertex. |
vertices |
The number of vertices in the subtree below the given internal vertex, including itself. |
A. Clauset, C. Moore, and M.E.J. Newman. Hierarchical structure and the prediction of missing links in networks. Nature 453, 98–101 (2008);
A. Clauset, C. Moore, and M.E.J. Newman. Structural Inference of Hierarchies in Networks. In E. M. Airoldi et al. (Eds.): ICML 2006 Ws, Lecture Notes in Computer Science 4503, 1–13. Springer-Verlag, Berlin Heidelberg (2007).
Other hierarchical random graph functions:
consensus_tree()
,
hrg()
,
hrg-methods
,
hrg_tree()
,
predict_edges()
,
print.igraphHRG()
,
print.igraphHRGConsensus()
,
sample_hrg()
## A graph with two dense groups g <- sample_gnp(10, p = 1 / 2) + sample_gnp(10, p = 1 / 2) hrg <- fit_hrg(g) hrg summary(as.hclust(hrg)) ## The consensus tree for it consensus_tree(g, hrg = hrg, start = TRUE) ## Prediction of missing edges g2 <- make_full_graph(4) + (make_full_graph(4) - path(1, 2)) predict_edges(g2)
## A graph with two dense groups g <- sample_gnp(10, p = 1 / 2) + sample_gnp(10, p = 1 / 2) hrg <- fit_hrg(g) hrg summary(as.hclust(hrg)) ## The consensus tree for it consensus_tree(g, hrg = hrg, start = TRUE) ## Prediction of missing edges g2 <- make_full_graph(4) + (make_full_graph(4) - path(1, 2)) predict_edges(g2)
fit_power_law()
fits a power-law distribution to a data set.
fit_power_law( x, xmin = NULL, start = 2, force.continuous = FALSE, implementation = c("plfit", "R.mle"), p.value = FALSE, p.precision = NULL, ... )
fit_power_law( x, xmin = NULL, start = 2, force.continuous = FALSE, implementation = c("plfit", "R.mle"), p.value = FALSE, p.precision = NULL, ... )
x |
The data to fit, a numeric vector. For implementation
‘ |
xmin |
Numeric scalar, or |
start |
Numeric scalar. The initial value of the exponent for the
minimizing function, for the ‘ |
force.continuous |
Logical scalar. Whether to force a continuous
distribution for the ‘ |
implementation |
Character scalar. Which implementation to use. See details below. |
p.value |
Set to |
p.precision |
The desired precision of the p-value calculation. The precision ultimately depends on the number of resampling attempts. The number of resampling trials is determined by 0.25 divided by the square of the required precision. For instance, a required precision of 0.01 means that 2500 samples will be drawn. |
... |
Additional arguments, passed to the maximum likelihood
optimizing function, |
This function fits a power-law distribution to a vector containing samples
from a distribution (that is assumed to follow a power-law of course). In a
power-law distribution, it is generally assumed that is
proportional to
, where
is a positive
number and
is greater than 1. In many real-world cases,
the power-law behaviour kicks in only above a threshold value
. The goal of this function is to determine
if
is given, or to determine
and the corresponding value of
.
fit_power_law()
provides two maximum likelihood implementations. If
the implementation
argument is ‘R.mle
’, then the BFGS
optimization (see stats4::mle()
) algorithm is applied. The additional
arguments are passed to the mle function, so it is possible to change the
optimization method and/or its parameters. This implementation can
not to fit the argument, so use the
‘
plfit
’ implementation if you want to do that.
The ‘plfit
’ implementation also uses the maximum likelihood
principle to determine for a given
;
When
is not given in advance, the algorithm will attempt
to find its optimal value for which the
-value of a Kolmogorov-Smirnov
test between the fitted distribution and the original sample is the largest.
The function uses the method of Clauset, Shalizi and Newman to calculate the
parameters of the fitted distribution. See references below for the details.
Pass p.value = TRUE
to include the p-value in the output.
This is not returned by default because the computation may be slow.
Depends on the implementation
argument. If it is
‘R.mle
’, then an object with class ‘mle
’. It can
be used to calculate confidence intervals and log-likelihood. See
stats4::mle-class()
for details.
If implementation
is ‘plfit
’, then the result is a
named list with entries:
continuous |
Logical scalar, whether the fitted power-law distribution was continuous or discrete. |
alpha |
Numeric scalar, the exponent of the fitted power-law distribution. |
xmin |
Numeric scalar, the minimum value from which the
power-law distribution was fitted. In other words, only the values larger
than |
logLik |
Numeric scalar, the log-likelihood of the fitted parameters. |
KS.stat |
Numeric scalar, the test statistic of a Kolmogorov-Smirnov test that compares the fitted distribution with the input vector. Smaller scores denote better fit. |
KS.p |
Only for |
Tamas Nepusz [email protected] and Gabor Csardi [email protected]
Power laws, Pareto distributions and Zipf's law, M. E. J. Newman, Contemporary Physics, 46, 323-351, 2005.
Aaron Clauset, Cosma R .Shalizi and Mark E.J. Newman: Power-law distributions in empirical data. SIAM Review 51(4):661-703, 2009.
# This should approximately yield the correct exponent 3 g <- sample_pa(1000) # increase this number to have a better estimate d <- degree(g, mode = "in") fit1 <- fit_power_law(d + 1, 10) fit2 <- fit_power_law(d + 1, 10, implementation = "R.mle") fit1$alpha stats4::coef(fit2) fit1$logLik stats4::logLik(fit2)
# This should approximately yield the correct exponent 3 g <- sample_pa(1000) # increase this number to have a better estimate d <- degree(g, mode = "in") fit1 <- fit_power_law(d + 1, 10) fit2 <- fit_power_law(d + 1, 10, implementation = "R.mle") fit1$alpha stats4::coef(fit2) fit1$logLik stats4::logLik(fit2)
Find the edges in an igraph graph that have the specified end points. This function handles multi-graph (graphs with multiple edges) and can consider or ignore the edge directions in directed graphs.
get_edge_ids(graph, vp, directed = TRUE, error = FALSE)
get_edge_ids(graph, vp, directed = TRUE, error = FALSE)
graph |
The input graph. |
vp |
The incident vertices, given as vertex ids or symbolic vertex names. They are interpreted pairwise, i.e. the first and second are used for the first edge, the third and fourth for the second, etc. |
directed |
Logical scalar, whether to consider edge directions in directed graphs. This argument is ignored for undirected graphs. |
error |
Logical scalar, whether to report an error if an edge is not
found in the graph. If |
igraph vertex ids are natural numbers, starting from one, up to the number of vertices in the graph. Similarly, edges are also numbered from one, up to the number of edges.
This function allows finding the edges of the graph, via their incident vertices.
A numeric vector of edge ids, one for each pair of input vertices.
If there is no edge in the input graph for a given pair of vertices, then
zero is reported. (If the error
argument is FALSE
.)
Gabor Csardi [email protected]
Other structural queries:
[.igraph()
,
[[.igraph()
,
adjacent_vertices()
,
are_adjacent()
,
ends()
,
gorder()
,
gsize()
,
head_of()
,
incident()
,
incident_edges()
,
is_directed()
,
neighbors()
,
tail_of()
g <- make_ring(10) ei <- get_edge_ids(g, c(1, 2, 4, 5)) E(g)[ei] ## non-existant edge get_edge_ids(g, c(2, 1, 1, 4, 5, 4)) ## For multiple edges, a single edge id is returned, ## as many times as corresponding pairs in the vertex series. g <- make_graph(rep(c(1, 2), 5)) eis <- get_edge_ids(g, c(1, 2, 1, 2)) eis E(g)[eis]
g <- make_ring(10) ei <- get_edge_ids(g, c(1, 2, 4, 5)) E(g)[ei] ## non-existant edge get_edge_ids(g, c(2, 1, 1, 4, 5, 4)) ## For multiple edges, a single edge id is returned, ## as many times as corresponding pairs in the vertex series. g <- make_graph(rep(c(1, 2), 5)) eis <- get_edge_ids(g, c(1, 2, 1, 2)) eis E(g)[eis]
The girth of a graph is the length of the shortest circle in it.
girth(graph, circle = TRUE)
girth(graph, circle = TRUE)
graph |
The input graph. It may be directed, but the algorithm searches for undirected circles anyway. |
circle |
Logical scalar, whether to return the shortest circle itself. |
The current implementation works for undirected graphs only, directed graphs
are treated as undirected graphs. Loop edges and multiple edges are ignored.
If the graph is a forest (i.e. acyclic), then Inf
is returned.
This implementation is based on Alon Itai and Michael Rodeh: Finding a minimum circuit in a graph Proceedings of the ninth annual ACM symposium on Theory of computing, 1-10, 1977. The first implementation of this function was done by Keith Briggs, thanks Keith.
A named list with two components:
girth |
Integer constant, the girth of the graph, or 0 if the graph is acyclic. |
circle |
Numeric vector with the vertex ids in the shortest circle. |
Gabor Csardi [email protected]
Alon Itai and Michael Rodeh: Finding a minimum circuit in a graph Proceedings of the ninth annual ACM symposium on Theory of computing, 1-10, 1977
Other structural.properties:
bfs()
,
component_distribution()
,
connect()
,
constraint()
,
coreness()
,
degree()
,
dfs()
,
distance_table()
,
edge_density()
,
feedback_arc_set()
,
is_acyclic()
,
is_dag()
,
is_matching()
,
k_shortest_paths()
,
knn()
,
reciprocity()
,
subcomponent()
,
subgraph()
,
topo_sort()
,
transitivity()
,
unfold_tree()
,
which_multiple()
,
which_mutual()
Graph cycles
feedback_arc_set()
,
has_eulerian_path()
,
is_acyclic()
,
is_dag()
# No circle in a tree g <- make_tree(1000, 3) girth(g) # The worst case running time is for a ring g <- make_ring(100) girth(g) # What about a random graph? g <- sample_gnp(1000, 1 / 1000) girth(g)
# No circle in a tree g <- make_tree(1000, 3) girth(g) # The worst case running time is for a ring g <- make_ring(100) girth(g) # What about a random graph? g <- sample_gnp(1000, 1 / 1000) girth(g)
These functions calculate the global or average local efficiency of a network, or the local efficiency of every vertex in the network. See below for definitions.
global_efficiency(graph, weights = NULL, directed = TRUE) local_efficiency( graph, vids = V(graph), weights = NULL, directed = TRUE, mode = c("all", "out", "in", "total") ) average_local_efficiency( graph, weights = NULL, directed = TRUE, mode = c("all", "out", "in", "total") )
global_efficiency(graph, weights = NULL, directed = TRUE) local_efficiency( graph, vids = V(graph), weights = NULL, directed = TRUE, mode = c("all", "out", "in", "total") ) average_local_efficiency( graph, weights = NULL, directed = TRUE, mode = c("all", "out", "in", "total") )
graph |
The graph to analyze. |
weights |
The edge weights. All edge weights must be non-negative;
additionally, no edge weight may be NaN. If it is |
directed |
Logical scalar, whether to consider directed paths. Ignored for undirected graphs. |
vids |
The vertex ids of the vertices for which the calculation will be done. Applies to the local efficiency calculation only. |
mode |
Specifies how to define the local neighborhood of a vertex in directed graphs. “out” considers out-neighbors only, “in” considers in-neighbors only, “all” considers both. |
For global_efficiency()
, the global efficiency of the graph as a
single number. For average_local_efficiency()
, the average local
efficiency of the graph as a single number. For local_efficiency()
, the
local efficiency of each vertex in a vector.
The global efficiency of a network is defined as the average of inverse distances between all pairs of vertices.
More precisely:
where is the number of vertices.
The inverse distance between pairs that are not reachable from each other is considered to be zero. For graphs with fewer than 2 vertices, NaN is returned.
The local efficiency of a network around a vertex is defined as follows: We remove the vertex and compute the distances (shortest path lengths) between its neighbours through the rest of the network. The local efficiency around the removed vertex is the average of the inverse of these distances.
The inverse distance between two vertices which are not reachable from each other is considered to be zero. The local efficiency around a vertex with fewer than two neighbours is taken to be zero by convention.
The average local efficiency of a network is simply the arithmetic mean of the local efficiencies of all the vertices; see the definition for local efficiency above.
igraph_global_efficiency()
, igraph_local_efficiency()
, igraph_average_local_efficiency()
.
V. Latora and M. Marchiori: Efficient Behavior of Small-World Networks, Phys. Rev. Lett. 87, 198701 (2001).
I. Vragović, E. Louis, and A. Díaz-Guilera, Efficiency of informational transfer in regular and complex networks, Phys. Rev. E 71, 1 (2005).
g <- make_graph("zachary") global_efficiency(g) average_local_efficiency(g)
g <- make_graph("zachary") global_efficiency(g) average_local_efficiency(g)
vcount()
and gorder()
are aliases.
vcount(graph) gorder(graph)
vcount(graph) gorder(graph)
graph |
The graph |
Number of vertices, numeric scalar.
Other structural queries:
[.igraph()
,
[[.igraph()
,
adjacent_vertices()
,
are_adjacent()
,
ends()
,
get_edge_ids()
,
gsize()
,
head_of()
,
incident()
,
incident_edges()
,
is_directed()
,
neighbors()
,
tail_of()
g <- make_ring(10) gorder(g) vcount(g)
g <- make_ring(10) gorder(g) vcount(g)
This is a generic function to convert R objects to igraph graphs.
graph_(...)
graph_(...)
... |
Parameters, see details below. |
TODO
## These are equivalent graph_(cbind(1:5, 2:6), from_edgelist(directed = FALSE)) graph_(cbind(1:5, 2:6), from_edgelist(), directed = FALSE)
## These are equivalent graph_(cbind(1:5, 2:6), from_edgelist(directed = FALSE)) graph_(cbind(1:5, 2:6), from_edgelist(), directed = FALSE)
Graph attributes of a graph
graph_attr(graph, name)
graph_attr(graph, name)
graph |
Input graph. |
name |
The name of attribute to query. If missing, then all attributes are returned in a list. |
A list of graph attributes, or a single graph attribute.
Vertex, edge and graph attributes
delete_edge_attr()
,
delete_graph_attr()
,
delete_vertex_attr()
,
edge_attr()
,
edge_attr<-()
,
edge_attr_names()
,
graph_attr<-()
,
graph_attr_names()
,
igraph-attribute-combination
,
igraph-dollar
,
igraph-vs-attributes
,
set_edge_attr()
,
set_graph_attr()
,
set_vertex_attr()
,
vertex_attr()
,
vertex_attr<-()
,
vertex_attr_names()
g <- make_ring(10) graph_attr(g) graph_attr(g, "name")
g <- make_ring(10) graph_attr(g) graph_attr(g, "name")
List names of graph attributes
graph_attr_names(graph)
graph_attr_names(graph)
graph |
The graph. |
Character vector, the names of the graph attributes.
Vertex, edge and graph attributes
delete_edge_attr()
,
delete_graph_attr()
,
delete_vertex_attr()
,
edge_attr()
,
edge_attr<-()
,
edge_attr_names()
,
graph_attr()
,
graph_attr<-()
,
igraph-attribute-combination
,
igraph-dollar
,
igraph-vs-attributes
,
set_edge_attr()
,
set_graph_attr()
,
set_vertex_attr()
,
vertex_attr()
,
vertex_attr<-()
,
vertex_attr_names()
g <- make_ring(10) graph_attr_names(g)
g <- make_ring(10) graph_attr_names(g)
Set all or some graph attributes
graph_attr(graph, name) <- value
graph_attr(graph, name) <- value
graph |
The graph. |
name |
The name of the attribute to set. If missing, then
|
value |
The value of the attribute to set |
The graph, with the attribute(s) added.
Vertex, edge and graph attributes
delete_edge_attr()
,
delete_graph_attr()
,
delete_vertex_attr()
,
edge_attr()
,
edge_attr<-()
,
edge_attr_names()
,
graph_attr()
,
graph_attr_names()
,
igraph-attribute-combination
,
igraph-dollar
,
igraph-vs-attributes
,
set_edge_attr()
,
set_graph_attr()
,
set_vertex_attr()
,
vertex_attr()
,
vertex_attr<-()
,
vertex_attr_names()
g <- make_graph(~ A - B:C:D) graph_attr(g, "name") <- "4-star" g graph_attr(g) <- list( layout = layout_with_fr(g), name = "4-star layed out" ) plot(g)
g <- make_graph(~ A - B:C:D) graph_attr(g, "name") <- "4-star" g graph_attr(g) <- list( layout = layout_with_fr(g), name = "4-star layed out" ) plot(g)
The center of a graph is the set of its vertices with minimal eccentricity.
graph_center(graph, ..., weights = NULL, mode = c("all", "out", "in", "total"))
graph_center(graph, ..., weights = NULL, mode = c("all", "out", "in", "total"))
graph |
The input graph, it can be directed or undirected. |
... |
These dots are for future extensions and must be empty. |
weights |
Possibly a numeric vector giving edge weights. If this is
|
mode |
Character constant, gives whether the shortest paths to or from
the given vertices should be calculated for directed graphs. If |
The vertex IDs of the central vertices.
igraph_graph_center_dijkstra()
.
Other paths:
all_simple_paths()
,
diameter()
,
distance_table()
,
eccentricity()
,
radius()
tree <- make_tree(100, 7) graph_center(tree) graph_center(tree, mode = "in") graph_center(tree, mode = "out") # Without and with weights ring <- make_ring(10) graph_center(ring) # Add weights E(ring)$weight <- seq_len(ecount(ring)) graph_center(ring)
tree <- make_tree(100, 7) graph_center(tree) graph_center(tree, mode = "in") graph_center(tree, mode = "out") # Without and with weights ring <- make_ring(10) graph_center(ring) # Add weights E(ring)$weight <- seq_len(ecount(ring)) graph_center(ring)
An adjacency list is a list of numeric vectors, containing the neighbor vertices for each vertex. This function creates an igraph graph object from such a list.
graph_from_adj_list( adjlist, mode = c("out", "in", "all", "total"), duplicate = TRUE )
graph_from_adj_list( adjlist, mode = c("out", "in", "all", "total"), duplicate = TRUE )
adjlist |
The adjacency list. It should be consistent, i.e. the maximum throughout all vectors in the list must be less than the number of vectors (=the number of vertices in the graph). |
mode |
Character scalar, it specifies whether the graph to create is undirected (‘all’ or ‘total’) or directed; and in the latter case, whether it contains the outgoing (‘out’) or the incoming (‘in’) neighbors of the vertices. |
duplicate |
Logical scalar. For undirected graphs it gives whether
edges are included in the list twice. E.g. if it is This argument is ignored if |
Adjacency lists are handy if you intend to do many (small) modifications to a graph. In this case adjacency lists are more efficient than igraph graphs.
The idea is that you convert your graph to an adjacency list by
as_adj_list()
, do your modifications to the graphs and finally
create again an igraph graph by calling graph_from_adj_list()
.
An igraph graph object.
Gabor Csardi [email protected]
Other conversion:
as.matrix.igraph()
,
as_adj_list()
,
as_adjacency_matrix()
,
as_biadjacency_matrix()
,
as_data_frame()
,
as_directed()
,
as_edgelist()
,
as_graphnel()
,
as_long_data_frame()
,
graph_from_graphnel()
## Directed g <- make_ring(10, directed = TRUE) al <- as_adj_list(g, mode = "out") g2 <- graph_from_adj_list(al) graph.isomorphic(g, g2) ## Undirected g <- make_ring(10) al <- as_adj_list(g) g2 <- graph_from_adj_list(al, mode = "all") graph.isomorphic(g, g2) ecount(g2) g3 <- graph_from_adj_list(al, mode = "all", duplicate = FALSE) ecount(g3) which_multiple(g3)
## Directed g <- make_ring(10, directed = TRUE) al <- as_adj_list(g, mode = "out") g2 <- graph_from_adj_list(al) graph.isomorphic(g, g2) ## Undirected g <- make_ring(10) al <- as_adj_list(g) g2 <- graph_from_adj_list(al, mode = "all") graph.isomorphic(g, g2) ecount(g2) g3 <- graph_from_adj_list(al, mode = "all", duplicate = FALSE) ecount(g3) which_multiple(g3)
graph_from_adjacency_matrix()
is a flexible function for creating igraph
graphs from adjacency matrices.
graph_from_adjacency_matrix( adjmatrix, mode = c("directed", "undirected", "max", "min", "upper", "lower", "plus"), weighted = NULL, diag = TRUE, add.colnames = NULL, add.rownames = NA ) from_adjacency(...)
graph_from_adjacency_matrix( adjmatrix, mode = c("directed", "undirected", "max", "min", "upper", "lower", "plus"), weighted = NULL, diag = TRUE, add.colnames = NULL, add.rownames = NA ) from_adjacency(...)
adjmatrix |
A square adjacency matrix. From igraph version 0.5.1 this
can be a sparse matrix created with the |
mode |
Character scalar, specifies how igraph should interpret the
supplied matrix. See also the |
weighted |
This argument specifies whether to create a weighted graph
from an adjacency matrix. If it is |
diag |
Logical scalar, whether to include the diagonal of the matrix in
the calculation. If this is |
add.colnames |
Character scalar, whether to add the column names as
vertex attributes. If it is ‘ |
add.rownames |
Character scalar, whether to add the row names as vertex
attributes. Possible values the same as the previous argument. By default
row names are not added. If ‘ |
... |
Passed to |
The order of the vertices are preserved, i.e. the vertex corresponding to the first row will be vertex 0 in the graph, etc.
graph_from_adjacency_matrix()
operates in two main modes, depending on the
weighted
argument.
If this argument is NULL
then an unweighted graph is created and an
element of the adjacency matrix gives the number of edges to create between
the two corresponding vertices. The details depend on the value of the
mode
argument:
The graph will be directed and a matrix element gives the number of edges between two vertices.
This is exactly the same as max
,
for convenience. Note that it is not checked whether the matrix is
symmetric.
An undirected graph will be created and
max(A(i,j), A(j,i))
gives the number of edges.
An undirected graph will be created, only the upper right triangle (including the diagonal) is used for the number of edges.
An undirected graph will be created, only the lower left triangle (including the diagonal) is used for creating the edges.
undirected graph will be created with min(A(i,j), A(j,i))
edges between vertex i
and j
.
undirected graph will be created with A(i,j)+A(j,i)
edges between
vertex i
and j
.
If the weighted
argument is not NULL
then the elements of the
matrix give the weights of the edges (if they are not zero). The details
depend on the value of the mode
argument:
The graph will be directed and a matrix element gives the edge weights.
First we check that the matrix is symmetric. It is an error if not. Then only the upper triangle is used to create a weighted undirected graph.
An
undirected graph will be created and max(A(i,j), A(j,i))
gives the
edge weights.
An undirected graph will be created, only the upper right triangle (including the diagonal) is used (for the edge weights).
An undirected graph will be created, only the lower left triangle (including the diagonal) is used for creating the edges.
An undirected graph will be created,
min(A(i,j), A(j,i))
gives the edge weights.
An
undirected graph will be created, A(i,j)+A(j,i)
gives the edge
weights.
An igraph graph object.
Gabor Csardi [email protected]
make_graph()
and graph_from_literal()
for other ways to
create graphs.
g1 <- sample( x = 0:1, size = 100, replace = TRUE, prob = c(0.9, 0.1) ) %>% matrix(ncol = 10) %>% graph_from_adjacency_matrix() g2 <- sample( x = 0:5, size = 100, replace = TRUE, prob = c(0.9, 0.02, 0.02, 0.02, 0.02, 0.02) ) %>% matrix(ncol = 10) %>% graph_from_adjacency_matrix(weighted = TRUE) E(g2)$weight ## various modes for weighted graphs, with some tests non_zero_sort <- function(x) sort(x[x != 0]) adj_matrix <- matrix(runif(100), 10) adj_matrix[adj_matrix < 0.5] <- 0 g3 <- graph_from_adjacency_matrix( (adj_matrix + t(adj_matrix)) / 2, weighted = TRUE, mode = "undirected" ) g4 <- graph_from_adjacency_matrix( adj_matrix, weighted = TRUE, mode = "max" ) expected_g4_weights <- non_zero_sort( pmax(adj_matrix, t(adj_matrix))[upper.tri(adj_matrix, diag = TRUE)] ) actual_g4_weights <- sort(E(g4)$weight) all(expected_g4_weights == actual_g4_weights) g5 <- graph_from_adjacency_matrix( adj_matrix, weighted = TRUE, mode = "min" ) expected_g5_weights <- non_zero_sort( pmin(adj_matrix, t(adj_matrix))[upper.tri(adj_matrix, diag = TRUE)] ) actual_g5_weights <- sort(E(g5)$weight) all(expected_g5_weights == actual_g5_weights) g6 <- graph_from_adjacency_matrix( adj_matrix, weighted = TRUE, mode = "upper" ) expected_g6_weights <- non_zero_sort(adj_matrix[upper.tri(adj_matrix, diag = TRUE)]) actual_g6_weights <- sort(E(g6)$weight) all(expected_g6_weights == actual_g6_weights) g7 <- graph_from_adjacency_matrix( adj_matrix, weighted = TRUE, mode = "lower" ) expected_g7_weights <- non_zero_sort(adj_matrix[lower.tri(adj_matrix, diag = TRUE)]) actual_g7_weights <- sort(E(g7)$weight) all(expected_g7_weights == actual_g7_weights) g8 <- graph_from_adjacency_matrix( adj_matrix, weighted = TRUE, mode = "plus" ) halve_diag <- function(x) { diag(x) <- diag(x) / 2 x } expected_g8_weights <- non_zero_sort( halve_diag(adj_matrix + t(adj_matrix) )[lower.tri(adj_matrix, diag = TRUE)]) actual_g8_weights <- sort(E(g8)$weight) all(expected_g8_weights == actual_g8_weights) g9 <- graph_from_adjacency_matrix( adj_matrix, weighted = TRUE, mode = "plus", diag = FALSE ) zero_diag <- function(x) { diag(x) <- 0 } expected_g9_weights <- non_zero_sort((zero_diag(adj_matrix + t(adj_matrix)))[lower.tri(adj_matrix)]) actual_g9_weights <- sort(E(g9)$weight) all(expected_g9_weights == actual_g9_weights) ## row/column names rownames(adj_matrix) <- sample(letters, nrow(adj_matrix)) colnames(adj_matrix) <- seq(ncol(adj_matrix)) g10 <- graph_from_adjacency_matrix( adj_matrix, weighted = TRUE, add.rownames = "code" ) summary(g10)
g1 <- sample( x = 0:1, size = 100, replace = TRUE, prob = c(0.9, 0.1) ) %>% matrix(ncol = 10) %>% graph_from_adjacency_matrix() g2 <- sample( x = 0:5, size = 100, replace = TRUE, prob = c(0.9, 0.02, 0.02, 0.02, 0.02, 0.02) ) %>% matrix(ncol = 10) %>% graph_from_adjacency_matrix(weighted = TRUE) E(g2)$weight ## various modes for weighted graphs, with some tests non_zero_sort <- function(x) sort(x[x != 0]) adj_matrix <- matrix(runif(100), 10) adj_matrix[adj_matrix < 0.5] <- 0 g3 <- graph_from_adjacency_matrix( (adj_matrix + t(adj_matrix)) / 2, weighted = TRUE, mode = "undirected" ) g4 <- graph_from_adjacency_matrix( adj_matrix, weighted = TRUE, mode = "max" ) expected_g4_weights <- non_zero_sort( pmax(adj_matrix, t(adj_matrix))[upper.tri(adj_matrix, diag = TRUE)] ) actual_g4_weights <- sort(E(g4)$weight) all(expected_g4_weights == actual_g4_weights) g5 <- graph_from_adjacency_matrix( adj_matrix, weighted = TRUE, mode = "min" ) expected_g5_weights <- non_zero_sort( pmin(adj_matrix, t(adj_matrix))[upper.tri(adj_matrix, diag = TRUE)] ) actual_g5_weights <- sort(E(g5)$weight) all(expected_g5_weights == actual_g5_weights) g6 <- graph_from_adjacency_matrix( adj_matrix, weighted = TRUE, mode = "upper" ) expected_g6_weights <- non_zero_sort(adj_matrix[upper.tri(adj_matrix, diag = TRUE)]) actual_g6_weights <- sort(E(g6)$weight) all(expected_g6_weights == actual_g6_weights) g7 <- graph_from_adjacency_matrix( adj_matrix, weighted = TRUE, mode = "lower" ) expected_g7_weights <- non_zero_sort(adj_matrix[lower.tri(adj_matrix, diag = TRUE)]) actual_g7_weights <- sort(E(g7)$weight) all(expected_g7_weights == actual_g7_weights) g8 <- graph_from_adjacency_matrix( adj_matrix, weighted = TRUE, mode = "plus" ) halve_diag <- function(x) { diag(x) <- diag(x) / 2 x } expected_g8_weights <- non_zero_sort( halve_diag(adj_matrix + t(adj_matrix) )[lower.tri(adj_matrix, diag = TRUE)]) actual_g8_weights <- sort(E(g8)$weight) all(expected_g8_weights == actual_g8_weights) g9 <- graph_from_adjacency_matrix( adj_matrix, weighted = TRUE, mode = "plus", diag = FALSE ) zero_diag <- function(x) { diag(x) <- 0 } expected_g9_weights <- non_zero_sort((zero_diag(adj_matrix + t(adj_matrix)))[lower.tri(adj_matrix)]) actual_g9_weights <- sort(E(g9)$weight) all(expected_g9_weights == actual_g9_weights) ## row/column names rownames(adj_matrix) <- sample(letters, nrow(adj_matrix)) colnames(adj_matrix) <- seq(ncol(adj_matrix)) g10 <- graph_from_adjacency_matrix( adj_matrix, weighted = TRUE, add.rownames = "code" ) summary(g10)
graph_from_atlas()
creates graphs from the book
‘An Atlas of Graphs’ by
Roland C. Read and Robin J. Wilson. The atlas contains all undirected
graphs with up to seven vertices, numbered from 0 up to 1252. The
graphs are listed:
in increasing order of number of nodes;
for a fixed number of nodes, in increasing order of the number of edges;
for fixed numbers of nodes and edges, in increasing order of the degree sequence, for example 111223 < 112222;
for fixed degree sequence, in increasing number of automorphisms.
graph_from_atlas(n) atlas(...)
graph_from_atlas(n) atlas(...)
n |
The id of the graph to create. |
... |
Passed to |
An igraph graph.
Other deterministic constructors:
graph_from_edgelist()
,
graph_from_literal()
,
make_()
,
make_chordal_ring()
,
make_empty_graph()
,
make_full_citation_graph()
,
make_full_graph()
,
make_graph()
,
make_lattice()
,
make_ring()
,
make_star()
,
make_tree()
## Some randomly picked graphs from the atlas graph_from_atlas(sample(0:1252, 1)) graph_from_atlas(sample(0:1252, 1))
## Some randomly picked graphs from the atlas graph_from_atlas(sample(0:1252, 1)) graph_from_atlas(sample(0:1252, 1))
graph_from_biadjacency_matrix()
creates a bipartite igraph graph from an incidence
matrix.
graph_from_biadjacency_matrix( incidence, directed = FALSE, mode = c("all", "out", "in", "total"), multiple = FALSE, weighted = NULL, add.names = NULL )
graph_from_biadjacency_matrix( incidence, directed = FALSE, mode = c("all", "out", "in", "total"), multiple = FALSE, weighted = NULL, add.names = NULL )
incidence |
The input bipartite adjacency matrix. It can also be a sparse matrix
from the |
directed |
Logical scalar, whether to create a directed graph. |
mode |
A character constant, defines the direction of the edges in
directed graphs, ignored for undirected graphs. If ‘ |
multiple |
Logical scalar, specifies how to interpret the matrix elements. See details below. |
weighted |
This argument specifies whether to create a weighted graph
from the bipartite adjacency matrix. If it is |
add.names |
A character constant, |
Bipartite graphs have a ‘type
’ vertex attribute in igraph,
this is boolean and FALSE
for the vertices of the first kind and
TRUE
for vertices of the second kind.
graph_from_biadjacency_matrix()
can operate in two modes, depending on the
multiple
argument. If it is FALSE
then a single edge is
created for every non-zero element in the bipartite adjacency matrix. If
multiple
is TRUE
, then the matrix elements are rounded up to
the closest non-negative integer to get the number of edges to create
between a pair of vertices.
Some authors refer to the bipartite adjacency matrix as the "bipartite incidence matrix". igraph 1.6.0 and later does not use this naming to avoid confusion with the edge-vertex incidence matrix.
A bipartite igraph graph. In other words, an igraph graph that has a
vertex attribute type
.
Gabor Csardi [email protected]
make_bipartite_graph()
for another way to create bipartite
graphs
Other biadjacency:
as_data_frame()
inc <- matrix(sample(0:1, 15, repl = TRUE), 3, 5) colnames(inc) <- letters[1:5] rownames(inc) <- LETTERS[1:3] graph_from_biadjacency_matrix(inc)
inc <- matrix(sample(0:1, 15, repl = TRUE), 3, 5) colnames(inc) <- letters[1:5] rownames(inc) <- LETTERS[1:3] graph_from_biadjacency_matrix(inc)
graph_from_edgelist()
creates a graph from an edge list. Its argument
is a two-column matrix, each row defines one edge. If it is
a numeric matrix then its elements are interpreted as vertex ids. If
it is a character matrix then it is interpreted as symbolic vertex
names and a vertex id will be assigned to each name, and also a
name
vertex attribute will be added.
graph_from_edgelist(el, directed = TRUE) from_edgelist(...)
graph_from_edgelist(el, directed = TRUE) from_edgelist(...)
el |
The edge list, a two column matrix, character or numeric. |
directed |
Whether to create a directed graph. |
... |
Passed to |
An igraph graph.
Other deterministic constructors:
graph_from_atlas()
,
graph_from_literal()
,
make_()
,
make_chordal_ring()
,
make_empty_graph()
,
make_full_citation_graph()
,
make_full_graph()
,
make_graph()
,
make_lattice()
,
make_ring()
,
make_star()
,
make_tree()
el <- matrix(c("foo", "bar", "bar", "foobar"), nc = 2, byrow = TRUE) graph_from_edgelist(el) # Create a ring by hand graph_from_edgelist(cbind(1:10, c(2:10, 1)))
el <- matrix(c("foo", "bar", "bar", "foobar"), nc = 2, byrow = TRUE) graph_from_edgelist(el) # Create a ring by hand graph_from_edgelist(cbind(1:10, c(2:10, 1)))
This function downloads a graph from a database created for the evaluation of graph isomorphism testing algothitms.
graph_from_graphdb( url = NULL, prefix = "iso", type = "r001", nodes = NULL, pair = "A", which = 0, base = "http://cneurocvs.rmki.kfki.hu/graphdb/gzip", compressed = TRUE, directed = TRUE )
graph_from_graphdb( url = NULL, prefix = "iso", type = "r001", nodes = NULL, pair = "A", which = 0, base = "http://cneurocvs.rmki.kfki.hu/graphdb/gzip", compressed = TRUE, directed = TRUE )
url |
If not |
prefix |
Gives the prefix. See details below. Possible values:
|
type |
Gives the graph type identifier. See details below. Possible
values: |
nodes |
The number of vertices in the graph. |
pair |
Specifies which graph of the pair to read. Possible values:
|
which |
Gives the number of the graph to read. For every graph type there are a number of actual graphs in the database. This argument specifies which one to read. |
base |
The base address of the database. See details below. |
compressed |
Logical constant, if TRUE than the file is expected to be
compressed by gzip. If |
directed |
Logical constant, whether to create a directed graph. |
graph_from_graphdb()
reads a graph from the graph database from an FTP or
HTTP server or from a local copy. It has two modes of operation:
If the url
argument is specified then it should the complete path to
a local or remote graph database file. In this case we simply call
read_graph()
with the proper arguments to read the file.
If url
is NULL
, and this is the default, then the filename is
assembled from the base
, prefix
, type
, nodes
,
pair
and which
arguments.
Unfortunately the original graph database homepage is now defunct, but see its old version at http://web.archive.org/web/20090215182331/http://amalfi.dis.unina.it/graph/db/doc/graphdbat.html for the actual format of a graph database file and other information.
A new graph object.
g <- graph_from_graphdb(prefix="iso", type="r001", nodes=20, pair="A", which=10, compressed=TRUE) g2 <- graph_from_graphdb(prefix="iso", type="r001", nodes=20, pair="B", which=10, compressed=TRUE) graph.isomorphic.vf2(g, g2) % should be TRUE g3 <- graph_from_graphdb(url=paste(sep="/", "http://cneurocvs.rmki.kfki.hu", "graphdb/gzip/iso/bvg/b06m", "iso_b06m_m200.A09.gz"))
Gabor Csardi [email protected]
M. De Santo, P. Foggia, C. Sansone, M. Vento: A large database of graphs and its use for benchmarking graph isomorphism algorithms, Pattern Recognition Letters, Volume 24, Issue 8 (May 2003)
read_graph()
, graph.isomorphic.vf2()
Foreign format readers
read_graph()
,
write_graph()
The graphNEL class is defined in the graph
package, it is another
way to represent graphs. graph_from_graphnel()
takes a graphNEL
graph and converts it to an igraph graph. It handles all
graph/vertex/edge attributes. If the graphNEL graph has a vertex
attribute called ‘name
’ it will be used as igraph vertex
attribute ‘name
’ and the graphNEL vertex names will be
ignored.
graph_from_graphnel(graphNEL, name = TRUE, weight = TRUE, unlist.attrs = TRUE)
graph_from_graphnel(graphNEL, name = TRUE, weight = TRUE, unlist.attrs = TRUE)
graphNEL |
The graphNEL graph. |
name |
Logical scalar, whether to add graphNEL vertex names as an
igraph vertex attribute called ‘ |
weight |
Logical scalar, whether to add graphNEL edge weights as an
igraph edge attribute called ‘ |
unlist.attrs |
Logical scalar. graphNEL attribute query functions
return the values of the attributes in R lists, if this argument is
|
Because graphNEL graphs poorly support multiple edges, the edge attributes of the multiple edges are lost: they are all replaced by the attributes of the first of the multiple edges.
graph_from_graphnel()
returns an igraph graph object.
as_graphnel()
for the other direction,
as_adjacency_matrix()
, graph_from_adjacency_matrix()
,
as_adj_list()
and graph_from_adj_list()
for other
graph representations.
Other conversion:
as.matrix.igraph()
,
as_adj_list()
,
as_adjacency_matrix()
,
as_biadjacency_matrix()
,
as_data_frame()
,
as_directed()
,
as_edgelist()
,
as_graphnel()
,
as_long_data_frame()
,
graph_from_adj_list()
## Undirected g <- make_ring(10) V(g)$name <- letters[1:10] GNEL <- as_graphnel(g) g2 <- graph_from_graphnel(GNEL) g2 ## Directed g3 <- make_star(10, mode = "in") V(g3)$name <- letters[1:10] GNEL2 <- as_graphnel(g3) g4 <- graph_from_graphnel(GNEL2) g4
## Undirected g <- make_ring(10) V(g)$name <- letters[1:10] GNEL <- as_graphnel(g) g2 <- graph_from_graphnel(GNEL) g2 ## Directed g3 <- make_star(10, mode = "in") V(g3)$name <- letters[1:10] GNEL2 <- as_graphnel(g3) g4 <- graph_from_graphnel(GNEL2) g4
The isomorphism class is a non-negative integer number. Graphs (with the same number of vertices) having the same isomorphism class are isomorphic and isomorphic graphs always have the same isomorphism class. Currently it can handle directed graphs with 3 or 4 vertices and undirected graphd with 3 to 6 vertices.
graph_from_isomorphism_class(size, number, directed = TRUE)
graph_from_isomorphism_class(size, number, directed = TRUE)
size |
The number of vertices in the graph. |
number |
The isomorphism class. |
directed |
Whether to create a directed graph (the default). |
An igraph object, the graph of the given size, directedness and isomorphism class.
Other graph isomorphism:
canonical_permutation()
,
count_isomorphisms()
,
count_subgraph_isomorphisms()
,
isomorphic()
,
isomorphism_class()
,
isomorphisms()
,
subgraph_isomorphic()
,
subgraph_isomorphisms()
LCF is short for Lederberg-Coxeter-Frucht, it is a concise notation for 3-regular Hamiltonian graphs. It constists of three parameters, the number of vertices in the graph, a list of shifts giving additional edges to a cycle backbone and another integer giving how many times the shifts should be performed. See http://mathworld.wolfram.com/LCFNotation.html for details.
graph_from_lcf(n, shifts, repeats = 1)
graph_from_lcf(n, shifts, repeats = 1)
n |
Integer, the number of vertices in the graph. |
shifts |
Integer vector, the shifts. |
repeats |
Integer constant, how many times to repeat the shifts. |
A graph object.
Gabor Csardi [email protected]
make_graph()
can create arbitrary graphs, see also the other
functions on the its manual page for creating special graphs.
# This is the Franklin graph: g1 <- graph_from_lcf(12, c(5, -5), 6) g2 <- make_graph("Franklin") isomorphic(g1, g2)
# This is the Franklin graph: g1 <- graph_from_lcf(12, c(5, -5), 6) g2 <- make_graph("Franklin") isomorphic(g1, g2)
This function is useful if you want to create a small (named) graph quickly, it works for both directed and undirected graphs.
graph_from_literal(..., simplify = TRUE) from_literal(...)
graph_from_literal(..., simplify = TRUE) from_literal(...)
... |
For |
simplify |
Logical scalar, whether to call |
graph_from_literal()
is very handy for creating small graphs quickly.
You need to supply one or more R expressions giving the structure of
the graph. The expressions consist of vertex names and edge
operators. An edge operator is a sequence of ‘-
’ and
‘+
’ characters, the former is for the edges and the
latter is used for arrow heads. The edges can be arbitrarily long,
i.e. you may use as many ‘-
’ characters to “draw”
them as you like.
If all edge operators consist of only ‘-
’ characters
then the graph will be undirected, whereas a single ‘+
’
character implies a directed graph.
Let us see some simple examples. Without arguments the function creates an empty graph:
graph_from_literal()
A simple undirected graph with two vertices called ‘A’ and ‘B’ and one edge only:
graph_from_literal(A-B)
Remember that the length of the edges does not matter, so we could have written the following, this creates the same graph:
graph_from_literal( A-----B )
If you have many disconnected components in the graph, separate them with commas. You can also give isolate vertices.
graph_from_literal( A--B, C--D, E--F, G--H, I, J, K )
The ‘:
’ operator can be used to define vertex sets. If
an edge operator connects two vertex sets then every vertex from the
first set will be connected to every vertex in the second set. The
following form creates a full graph, including loop edges:
graph_from_literal( A:B:C:D -- A:B:C:D )
In directed graphs, edges will be created only if the edge operator includes a arrow head (‘+’) at the end of the edge:
graph_from_literal( A -+ B -+ C ) graph_from_literal( A +- B -+ C ) graph_from_literal( A +- B -- C )
Thus in the third example no edge is created between vertices B
and C
.
Mutual edges can be also created with a simple edge operator:
graph_from_literal( A +-+ B +---+ C ++ D + E)
Note again that the length of the edge operators is arbitrary,
‘+
’, ‘++
’ and ‘+-----+
’ have
exactly the same meaning.
If the vertex names include spaces or other special characters then you need to quote them:
graph_from_literal( "this is" +- "a silly" -+ "graph here" )
You can include any character in the vertex names this way, even ‘+’ and ‘-’ characters.
See more examples below.
An igraph graph
Other deterministic constructors:
graph_from_atlas()
,
graph_from_edgelist()
,
make_()
,
make_chordal_ring()
,
make_empty_graph()
,
make_full_citation_graph()
,
make_full_graph()
,
make_graph()
,
make_lattice()
,
make_ring()
,
make_star()
,
make_tree()
# A simple undirected graph g <- graph_from_literal( Alice - Bob - Cecil - Alice, Daniel - Cecil - Eugene, Cecil - Gordon ) g # Another undirected graph, ":" notation g2 <- graph_from_literal(Alice - Bob:Cecil:Daniel, Cecil:Daniel - Eugene:Gordon) g2 # A directed graph g3 <- graph_from_literal( Alice +-+ Bob --+ Cecil +-- Daniel, Eugene --+ Gordon:Helen ) g3 # A graph with isolate vertices g4 <- graph_from_literal(Alice -- Bob -- Daniel, Cecil:Gordon, Helen) g4 V(g4)$name # "Arrows" can be arbitrarily long g5 <- graph_from_literal(Alice +---------+ Bob) g5 # Special vertex names g6 <- graph_from_literal("+" -- "-", "*" -- "/", "%%" -- "%/%") g6
# A simple undirected graph g <- graph_from_literal( Alice - Bob - Cecil - Alice, Daniel - Cecil - Eugene, Cecil - Gordon ) g # Another undirected graph, ":" notation g2 <- graph_from_literal(Alice - Bob:Cecil:Daniel, Cecil:Daniel - Eugene:Gordon) g2 # A directed graph g3 <- graph_from_literal( Alice +-+ Bob --+ Cecil +-- Daniel, Eugene --+ Gordon:Helen ) g3 # A graph with isolate vertices g4 <- graph_from_literal(Alice -- Bob -- Daniel, Cecil:Gordon, Helen) g4 V(g4)$name # "Arrows" can be arbitrarily long g5 <- graph_from_literal(Alice +---------+ Bob) g5 # Special vertex names g6 <- graph_from_literal("+" -- "-", "*" -- "/", "%%" -- "%/%") g6
Graph ids are used to check that a vertex or edge sequence belongs to a graph. If you create a new graph by changing the structure of a graph, the new graph will have a new id. Changing the attributes will not change the id.
graph_id(x, ...)
graph_id(x, ...)
x |
A graph or a vertex sequence or an edge sequence. |
... |
Not used currently. |
The id of the graph, a character scalar. For vertex and edge sequences the id of the graph they were created from.
g <- make_ring(10) graph_id(g) graph_id(V(g)) graph_id(E(g)) g2 <- g + 1 graph_id(g2)
g <- make_ring(10) graph_id(g) graph_id(V(g)) graph_id(E(g)) g2 <- g + 1 graph_id(g2)
igraph's internal data representation changes sometimes between versions. This means that it is not always possible to use igraph objects that were created (and possibly saved to a file) with an older igraph version.
graph_version(graph)
graph_version(graph)
graph |
The input graph. If it is missing, then the version number of the current data format is returned. |
graph_version()
queries the current data format,
or the data format of a possibly older igraph graph.
upgrade_graph()
can convert an older data format
to the current one.
An integer scalar.
upgrade_graph to convert the data format of a graph.
Other versions:
upgrade_graph()
Graphlet decomposition models a weighted undirected graph via the union of potentially overlapping dense social groups. This is done by a two-step algorithm. In the first step a candidate set of groups (a candidate basis) is created by finding cliques if the thresholded input graph. In the second step these the graph is projected on the candidate basis, resulting a weight coefficient for each clique in the candidate basis.
graphlet_basis(graph, weights = NULL) graphlet_proj( graph, weights = NULL, cliques, niter = 1000, Mu = rep(1, length(cliques)) ) graphlets(graph, weights = NULL, niter = 1000)
graphlet_basis(graph, weights = NULL) graphlet_proj( graph, weights = NULL, cliques, niter = 1000, Mu = rep(1, length(cliques)) ) graphlets(graph, weights = NULL, niter = 1000)
graph |
The input graph, edge directions are ignored. Only simple graph (i.e. graphs without self-loops and multiple edges) are supported. |
weights |
Edge weights. If the graph has a |
cliques |
A list of vertex ids, the graphlet basis to use for the projection. |
niter |
Integer scalar, the number of iterations to perform. |
Mu |
Starting weights for the projection. |
igraph contains three functions for performing the graph decomponsition of a
graph. The first is graphlets()
, which performed both steps on the
method and returns a list of subgraphs, with their corresponding weights.
The second and third functions correspond to the first and second steps of
the algorithm, and they are useful if the user wishes to perform them
individually: graphlet_basis()
and graphlet_proj()
.
graphlets()
returns a list with two members:
cliques |
A list of subgraphs, the candidate graphlet basis. Each subgraph is give by a vector of vertex ids. |
Mu |
The weights of the subgraphs in graphlet basis. |
graphlet_basis()
returns a list of two elements:
cliques |
A list of subgraphs, the candidate graphlet basis. Each subgraph is give by a vector of vertex ids. |
thresholds |
The weight thresholds used for finding the subgraphs. |
graphlet_proj()
return a numeric vector, the weights of the graphlet
basis subgraphs.
## Create an example graph first D1 <- matrix(0, 5, 5) D2 <- matrix(0, 5, 5) D3 <- matrix(0, 5, 5) D1[1:3, 1:3] <- 2 D2[3:5, 3:5] <- 3 D3[2:5, 2:5] <- 1 g <- simplify(graph_from_adjacency_matrix(D1 + D2 + D3, mode = "undirected", weighted = TRUE )) V(g)$color <- "white" E(g)$label <- E(g)$weight E(g)$label.cex <- 2 E(g)$color <- "black" layout(matrix(1:6, nrow = 2, byrow = TRUE)) co <- layout_with_kk(g) par(mar = c(1, 1, 1, 1)) plot(g, layout = co) ## Calculate graphlets gl <- graphlets(g, niter = 1000) ## Plot graphlets for (i in 1:length(gl$cliques)) { sel <- gl$cliques[[i]] V(g)$color <- "white" V(g)[sel]$color <- "#E495A5" E(g)$width <- 1 E(g)[V(g)[sel] %--% V(g)[sel]]$width <- 2 E(g)$label <- "" E(g)[width == 2]$label <- round(gl$Mu[i], 2) E(g)$color <- "black" E(g)[width == 2]$color <- "#E495A5" plot(g, layout = co) }
## Create an example graph first D1 <- matrix(0, 5, 5) D2 <- matrix(0, 5, 5) D3 <- matrix(0, 5, 5) D1[1:3, 1:3] <- 2 D2[3:5, 3:5] <- 3 D3[2:5, 2:5] <- 1 g <- simplify(graph_from_adjacency_matrix(D1 + D2 + D3, mode = "undirected", weighted = TRUE )) V(g)$color <- "white" E(g)$label <- E(g)$weight E(g)$label.cex <- 2 E(g)$color <- "black" layout(matrix(1:6, nrow = 2, byrow = TRUE)) co <- layout_with_kk(g) par(mar = c(1, 1, 1, 1)) plot(g, layout = co) ## Calculate graphlets gl <- graphlets(g, niter = 1000) ## Plot graphlets for (i in 1:length(gl$cliques)) { sel <- gl$cliques[[i]] V(g)$color <- "white" V(g)[sel]$color <- "#E495A5" E(g)$width <- 1 E(g)[V(g)[sel] %--% V(g)[sel]]$width <- 2 E(g)$label <- "" E(g)[width == 2]$label <- round(gl$Mu[i], 2) E(g)$color <- "black" E(g)[width == 2]$color <- "#E495A5" plot(g, layout = co) }
greedy_vertex_coloring()
finds a coloring for the vertices of a graph
based on a simple greedy algorithm.
greedy_vertex_coloring(graph, heuristic = c("colored_neighbors", "dsatur"))
greedy_vertex_coloring(graph, heuristic = c("colored_neighbors", "dsatur"))
graph |
The graph object to color. |
heuristic |
The selection heuristic for the next vertex to consider. Possible values are: “colored_neighbors” selects the vertex with the largest number of already colored neighbors. “dsatur” selects the vertex with the largest number of unique colors in its neighborhood, i.e. its "saturation degree"; when there are several maximum saturation degree vertices, the one with the most uncolored neighbors will be selected. |
The goal of vertex coloring is to assign a "color" (represented as a positive integer) to each vertex of the graph such that neighboring vertices never have the same color. This function solves the problem by considering the vertices one by one according to a heuristic, always choosing the smallest color that differs from that of already colored neighbors. The coloring obtained this way is not necessarily minimum but it can be calculated in linear time.
A numeric vector where item i
contains the color index
associated to vertex i
.
igraph_vertex_coloring_greedy()
.
g <- make_graph("petersen") col <- greedy_vertex_coloring(g) plot(g, vertex.color = col)
g <- make_graph("petersen") col <- greedy_vertex_coloring(g) plot(g, vertex.color = col)
Create a list of vertex groups from some graph clustering or community structure.
groups(x)
groups(x)
x |
Some object that represents a grouping of the vertices. See details below. |
Currently two methods are defined for this function. The default method
works on the output of components()
. (In fact it works on any
object that is a list with an entry called membership
.)
The second method works on communities()
objects.
A named list of numeric or character vectors. The names are just numbers that refer to the groups. The vectors themselves are numeric or symbolic vertex ids.
components()
and the various community finding
functions.
Community detection
as_membership()
,
cluster_edge_betweenness()
,
cluster_fast_greedy()
,
cluster_fluid_communities()
,
cluster_infomap()
,
cluster_label_prop()
,
cluster_leading_eigen()
,
cluster_leiden()
,
cluster_louvain()
,
cluster_optimal()
,
cluster_spinglass()
,
cluster_walktrap()
,
compare()
,
make_clusters()
,
membership()
,
modularity.igraph()
,
plot_dendrogram()
,
split_join_distance()
,
voronoi_cells()
g <- make_graph("Zachary") fgc <- cluster_fast_greedy(g) groups(fgc) g2 <- make_ring(10) + make_full_graph(5) groups(components(g2))
g <- make_graph("Zachary") fgc <- cluster_fast_greedy(g) groups(fgc) g2 <- make_ring(10) + make_full_graph(5) groups(components(g2))
ecount()
and gsize()
are aliases.
gsize(graph) ecount(graph)
gsize(graph) ecount(graph)
graph |
The graph. |
Numeric scalar, the number of edges.
Other structural queries:
[.igraph()
,
[[.igraph()
,
adjacent_vertices()
,
are_adjacent()
,
ends()
,
get_edge_ids()
,
gorder()
,
head_of()
,
incident()
,
incident_edges()
,
is_directed()
,
neighbors()
,
tail_of()
g <- sample_gnp(100, 2 / 100) gsize(g) ecount(g) # Number of edges in a G(n,p) graph replicate(100, sample_gnp(10, 1 / 2), simplify = FALSE) %>% vapply(gsize, 0) %>% hist()
g <- sample_gnp(100, 2 / 100) gsize(g) ecount(g) # Number of edges in a G(n,p) graph replicate(100, sample_gnp(10, 1 / 2), simplify = FALSE) %>% vapply(gsize, 0) %>% hist()
The harmonic centrality of a vertex is the mean inverse distance to all other vertices. The inverse distance to an unreachable vertex is considered to be zero.
harmonic_centrality( graph, vids = V(graph), mode = c("out", "in", "all", "total"), weights = NULL, normalized = FALSE, cutoff = -1 )
harmonic_centrality( graph, vids = V(graph), mode = c("out", "in", "all", "total"), weights = NULL, normalized = FALSE, cutoff = -1 )
graph |
The graph to analyze. |
vids |
The vertices for which harmonic centrality will be calculated. |
mode |
Character string, defining the types of the paths used for measuring the distance in directed graphs. “out” follows paths along the edge directions only, “in” traverses the edges in reverse, while “all” ignores edge directions. This argument is ignored for undirected graphs. |
weights |
Optional positive weight vector for calculating weighted
harmonic centrality. If the graph has a |
normalized |
Logical scalar, whether to calculate the normalized harmonic centrality. If true, the result is the mean inverse path length to other vertices, i.e. it is normalized by the number of vertices minus one. If false, the result is the sum of inverse path lengths to other vertices. |
cutoff |
The maximum path length to consider when calculating the harmonic centrality. There is no such limit when the cutoff is negative. Note that zero cutoff means that only paths of at most length 0 are considered. |
The cutoff
argument can be used to restrict the calculation to paths
of length cutoff
or smaller only; this can be used for larger graphs
to speed up the calculation. If cutoff
is negative (which is the
default), then the function calculates the exact harmonic centrality scores.
Numeric vector with the harmonic centrality scores of all the vertices in
v
.
igraph_harmonic_centrality_cutoff()
.
M. Marchiori and V. Latora, Harmony in the small-world, Physica A 285, pp. 539-546 (2000).
Centrality measures
alpha_centrality()
,
authority_score()
,
betweenness()
,
closeness()
,
diversity()
,
eigen_centrality()
,
hits_scores()
,
page_rank()
,
power_centrality()
,
spectrum()
,
strength()
,
subgraph_centrality()
g <- make_ring(10) g2 <- make_star(10) harmonic_centrality(g) harmonic_centrality(g2, mode = "in") harmonic_centrality(g2, mode = "out") harmonic_centrality(g %du% make_full_graph(5), mode = "all")
g <- make_ring(10) g2 <- make_star(10) harmonic_centrality(g) harmonic_centrality(g2, mode = "in") harmonic_centrality(g2, mode = "out") harmonic_centrality(g %du% make_full_graph(5), mode = "all")
has_eulerian_path()
and has_eulerian_cycle()
checks whether there
is an Eulerian path or cycle in the input graph. eulerian_path()
and
eulerian_cycle()
return such a path or cycle if it exists, and throws
an error otherwise.
has_eulerian_path(graph) has_eulerian_cycle(graph) eulerian_path(graph) eulerian_cycle(graph)
has_eulerian_path(graph) has_eulerian_cycle(graph) eulerian_path(graph) eulerian_cycle(graph)
graph |
An igraph graph object |
has_eulerian_path()
decides whether the input graph has an Eulerian
path, i.e. a path that passes through every edge of the graph exactly
once, and returns a logical value as a result. eulerian_path()
returns
a possible Eulerian path, described with its edge and vertex sequence, or
throws an error if no such path exists.
has_eulerian_cycle()
decides whether the input graph has an Eulerian
cycle, i.e. a path that passes through every edge of the graph exactly
once and that returns to its starting point, and returns a logical value as
a result. eulerian_cycle()
returns a possible Eulerian cycle, described
with its edge and vertex sequence, or throws an error if no such cycle exists.
For has_eulerian_path()
and has_eulerian_cycle()
, a logical
value that indicates whether the graph contains an Eulerian path or cycle.
For eulerian_path()
and eulerian_cycle()
, a named list with two
entries:
epath |
A vector containing the edge ids along the Eulerian path or cycle. |
vpath |
A vector containing the vertex ids along the Eulerian path or cycle. |
igraph_is_eulerian()
, igraph_eulerian_path()
, igraph_eulerian_cycle()
.
Graph cycles
feedback_arc_set()
,
girth()
,
is_acyclic()
,
is_dag()
g <- make_graph(~ A - B - C - D - E - A - F - D - B - F - E) has_eulerian_path(g) eulerian_path(g) has_eulerian_cycle(g) try(eulerian_cycle(g))
g <- make_graph(~ A - B - C - D - E - A - F - D - B - F - E) has_eulerian_path(g) eulerian_path(g) has_eulerian_cycle(g) try(eulerian_cycle(g))
For undirected graphs, head and tail is not defined. In this case
head_of()
returns vertices incident to the supplied edges, and
tail_of()
returns the other end(s) of the edge(s).
head_of(graph, es)
head_of(graph, es)
graph |
The input graph. |
es |
The edges to query. |
A vertex sequence with the head(s) of the edge(s).
Other structural queries:
[.igraph()
,
[[.igraph()
,
adjacent_vertices()
,
are_adjacent()
,
ends()
,
get_edge_ids()
,
gorder()
,
gsize()
,
incident()
,
incident_edges()
,
is_directed()
,
neighbors()
,
tail_of()
Print the only the head of an R object
head_print( x, max_lines = 20, header = "", footer = "", omitted_footer = "", ... )
head_print( x, max_lines = 20, header = "", footer = "", omitted_footer = "", ... )
x |
The object to print, or a callback function. See
|
max_lines |
Maximum number of lines to print, not including the header and the footer. |
header |
The header, if a function, then it will be called,
otherwise printed using |
footer |
The footer, if a function, then it will be called,
otherwise printed using |
omitted_footer |
Footer that is only printed if anything
is omitted from the printout. If a function, then it will be called,
otherwise printed using |
... |
Extra arguments to pass to |
x
, invisibly.
The hub scores of the vertices are defined as the principal eigenvector
of , where
is the adjacency matrix of the
graph.
hits_scores( graph, ..., scale = TRUE, weights = NULL, options = arpack_defaults() )
hits_scores( graph, ..., scale = TRUE, weights = NULL, options = arpack_defaults() )
graph |
The input graph. |
... |
These dots are for future extensions and must be empty. |
scale |
Logical scalar, whether to scale the result to have a maximum score of one. If no scaling is used then the result vector has unit length in the Euclidean norm. |
weights |
Optional positive weight vector for calculating weighted
scores. If the graph has a |
options |
A named list, to override some ARPACK options. See
|
Similarly, the authority scores of the vertices are defined as the principal
eigenvector of , where
is the adjacency matrix of
the graph.
For undirected matrices the adjacency matrix is symmetric and the hub scores are the same as authority scores.
A named list with members:
hub |
The hub score of the vertices. |
authority |
The authority score of the vertices. |
value |
The corresponding eigenvalue of the calculated principal eigenvector. |
options |
Some information about the ARPACK computation, it has
the same members as the |
igraph_hub_and_authority_scores()
.
J. Kleinberg. Authoritative sources in a hyperlinked environment. Proc. 9th ACM-SIAM Symposium on Discrete Algorithms, 1998. Extended version in Journal of the ACM 46(1999). Also appears as IBM Research Report RJ 10076, May 1997.
eigen_centrality()
for eigenvector centrality,
page_rank()
for the Page Rank scores. arpack()
for
the underlining machinery of the computation.
Centrality measures
alpha_centrality()
,
authority_score()
,
betweenness()
,
closeness()
,
diversity()
,
eigen_centrality()
,
harmonic_centrality()
,
page_rank()
,
power_centrality()
,
spectrum()
,
strength()
,
subgraph_centrality()
## An in-star g <- make_star(10) hits_scores(g) ## A ring g2 <- make_ring(10) hits_scores(g2)
## An in-star g <- make_star(10) hits_scores(g) ## A ring g2 <- make_ring(10) hits_scores(g2)
hrg()
creates a HRG from an igraph graph. The igraph graph must be
a directed binary tree, with internal and
leaf
vertices. The
prob
argument contains the HRG probability labels
for each vertex; these are ignored for leaf vertices.
hrg(graph, prob)
hrg(graph, prob)
graph |
The igraph graph to create the HRG from. |
prob |
A vector of probabilities, one for each vertex, in the order of vertex ids. |
hrg()
returns an igraphHRG
object.
Other hierarchical random graph functions:
consensus_tree()
,
fit_hrg()
,
hrg-methods
,
hrg_tree()
,
predict_edges()
,
print.igraphHRG()
,
print.igraphHRGConsensus()
,
sample_hrg()
hrg_tree()
creates the corresponsing igraph tree of a hierarchical
random graph model.
hrg_tree(hrg)
hrg_tree(hrg)
hrg |
A hierarchical random graph model. |
An igraph graph with a vertex attribute called "probability"
.
Other hierarchical random graph functions:
consensus_tree()
,
fit_hrg()
,
hrg()
,
hrg-methods
,
predict_edges()
,
print.igraphHRG()
,
print.igraphHRGConsensus()
,
sample_hrg()
Fitting and sampling hierarchical random graph models.
A hierarchical random graph is an ensemble of undirected graphs with
vertices. It is defined via a binary tree with
leaf and
internal vertices, where the internal vertices are labeled with
probabilities. The probability that two vertices are connected in the
random graph is given by the probability label at their closest common
ancestor.
Please see references below for more about hierarchical random graphs.
igraph contains functions for fitting HRG models to a given network
(fit_hrg()
, for generating networks from a given HRG ensemble
(sample_hrg()
), converting an igraph graph to a HRG and back
(hrg()
, hrg_tree()
), for calculating a consensus tree from a set
of sampled HRGs (consensus_tree()
) and for predicting missing edges in
a network based on its HRG models (predict_edges()
).
The igraph HRG implementation is heavily based on the code published by Aaron Clauset, at his website (not functional any more).
Other hierarchical random graph functions:
consensus_tree()
,
fit_hrg()
,
hrg()
,
hrg_tree()
,
predict_edges()
,
print.igraphHRG()
,
print.igraphHRGConsensus()
,
sample_hrg()
Two graphs are considered identical by this function if and only if they are represented in exactly the same way in the internal R representation. This means that the two graphs must have the same list of vertices and edges, in exactly the same order, with same directedness, and the two graphs must also have identical graph, vertex and edge attributes.
identical_graphs(g1, g2, attrs = TRUE)
identical_graphs(g1, g2, attrs = TRUE)
g1 , g2
|
The two graphs |
attrs |
Whether to compare the attributes of the graphs |
This is similar to identical
in the base
package,
but it ignores the mutable piece of igraph objects; those might be
different even if the two graphs are identical.
Attribute comparison can be turned off with the attrs
parameter if
the attributes of the two graphs are allowed to be different.
Logical scalar
Run one of the accompanying igraph demos, somewhat interactively, using a Tk window.
igraph_demo(which)
igraph_demo(which)
which |
If not given, then the names of the available demos are listed. Otherwise it should be either a filename or the name of an igraph demo. |
This function provides a somewhat nicer interface to igraph demos that come
with the package, than the standard demo()
function. igraph
demos are divided into chunks and igraph_demo()
runs them chunk by
chunk, with the possibility of inspecting the workspace between two chunks.
The tcltk
package is needed for igraph_demo()
.
Returns NULL
, invisibly.
Gabor Csardi [email protected]
igraph_demo() if (interactive() && requireNamespace("tcltk", quietly = TRUE)) { igraph_demo("centrality") }
igraph_demo() if (interactive() && requireNamespace("tcltk", quietly = TRUE)) { igraph_demo("centrality") }
igraph has some parameters which (usually) affect the behavior of many
functions. These can be set for the whole session via igraph_options()
.
igraph_options(...) igraph_opt(x, default = NULL)
igraph_options(...) igraph_opt(x, default = NULL)
... |
A list may be given as the only argument, or any number of
arguments may be in the |
x |
A character string holding an option name. |
default |
If the specified option is not set in the options list, this value is returned. This facilitates retrieving an option and checking whether it is set and setting it separately if not. |
The parameter values set via a call to the igraph_options()
function
will remain in effect for the rest of the session, affecting the subsequent
behaviour of the other functions of the igraph
package for which the
given parameters are relevant.
This offers the possibility of customizing the functioning of the
igraph
package, for instance by insertions of appropriate calls to
igraph_options()
in a load hook for package igraph.
The currently used parameters in alphabetical order:
Logical scalar, whether to add model
parameter to the graphs that are created by the various
graph constructors. By default it is TRUE
.
Logical scalar, whether to add
vertex names to node level indices, like degree, betweenness
scores, etc. By default it is TRUE
.
Logical scalar, whether to annotate igraph
plots with the graph's name (name
graph attribute, if
present) as main
, and with the number of vertices and edges
as xlab
. Defaults to FALSE
.
The plotting function to use when plotting
community structure dendrograms via
plot_dendrogram()
. Possible values are ‘auto’ (the
default), ‘phylo’, ‘hclust’ and
‘dendrogram’. See plot_dendrogram()
for details.
Specifies what to do with the edge
attributes if the graph is modified. The default value is
list(weight="sum", name="concat", "ignore")
. See
attribute.combination()
for details on this.
Logical constant, whether to print edge
attributes when printing graphs. Defaults to FALSE
.
Logical scalar, whether print.igraph()
should show the graph structure as well, or only a summary of the
graph.
Logical constant, whether to print
graph attributes when printing graphs. Defaults to FALSE
.
Logical constant, whether to print
vertex attributes when printing graphs. Defaults to FALSE
.
Whether functions that return a set or sequence
of vertices/edges should return formal vertex/edge sequence
objects. This option was introduced in igraph version 1.0.0 and
defaults to TRUE. If your package requires the old behavior,
you can set it to FALSE in the .onLoad
function of
your package, without affecting other packages.
Whether to use the Matrix
package for
(sparse) matrices. It is recommended, if the user works with
larger graphs.
Logical constant, whether igraph functions should
talk more than minimal. E.g. if TRUE
then some functions
will use progress bars while computing. Defaults to FALSE
.
Specifies what to do with the vertex
attributes if the graph is modified. The default value is
list(name="concat", "ignore")
See
attribute.combination()
for details on this.
igraph_options()
returns a list with the old values of the
updated parameters, invisibly. Without any arguments, it returns the
values of all options.
For igraph_opt()
, the current value set for option x
, or
NULL
if the option is unset.
Gabor Csardi [email protected]
igraph_options()
is similar to options()
and
igraph_opt()
is similar to getOption()
.
Other igraph options:
with_igraph_opt()
oldval <- igraph_opt("verbose") igraph_options(verbose = TRUE) layout_with_kk(make_ring(10)) igraph_options(verbose = oldval) oldval <- igraph_options(verbose = TRUE, sparsematrices = FALSE) make_ring(10)[] igraph_options(oldval) igraph_opt("verbose")
oldval <- igraph_opt("verbose") igraph_options(verbose = TRUE) layout_with_kk(make_ring(10)) igraph_options(verbose = oldval) oldval <- igraph_options(verbose = TRUE, sparsematrices = FALSE) make_ring(10)[] igraph_options(oldval) igraph_opt("verbose")
Many times, when the structure of a graph is modified, vertices/edges map of
the original graph map to vertices/edges in the newly created (modified)
graph. For example simplify()
maps multiple edges to single
edges. igraph provides a flexible mechanism to specify what to do with the
vertex/edge attributes in these cases.
The functions that support the combination of attributes have one or two
extra arguments called vertex.attr.comb
and/or edge.attr.comb
that specify how to perform the mapping of the attributes. E.g.
contract()
contracts many vertices into a single one, the
attributes of the vertices can be combined and stores as the vertex
attributes of the new graph.
The specification of the combination of (vertex or edge) attributes can be given as
a character scalar,
a function object or
a list of character scalars and/or function objects.
If it is a character scalar, then it refers to one of the predefined combinations, see their list below.
If it is a function, then the given function is expected to perform the combination. It will be called once for each new vertex/edge in the graph, with a single argument: the attribute values of the vertices that map to that single vertex.
The third option, a list can be used to specify different combination methods for different attributes. A named entry of the list corresponds to the attribute with the same name. An unnamed entry (i.e. if the name is the empty string) of the list specifies the default combination method. I.e.
list(weight="sum", "ignore")
specifies that the weight of the new edge should be sum of the weights of the corresponding edges in the old graph; and that the rest of the attributes should be ignored (=dropped).
The following combination behaviors are predefined:
The attribute is ignored and dropped.
The sum of the attributes is
calculated. This does not work for character attributes and works for
complex attributes only if they have a sum
generic defined. (E.g. it
works for sparse matrices from the Matrix
package, because they have
a sum
method.)
The product of the attributes is
calculated. This does not work for character attributes and works for
complex attributes only if they have a prod
function defined.
The minimum of the attributes is calculated and returned.
For character and complex attributes the standard R min
function is
used.
The maximum of the attributes is calculated and
returned. For character and complex attributes the standard R max
function is used.
Chooses one of the supplied
attribute values, uniformly randomly. For character and complex attributes
this is implemented by calling sample
.
Always
chooses the first attribute value. It is implemented by calling the
head
function.
Always chooses the last attribute
value. It is implemented by calling the tail
function.
The mean of the attributes is calculated and returned.
For character and complex attributes this simply calls the mean
function.
The median of the attributes is selected.
Calls the R median
function for all attribute types.
Concatenate the attributes, using the c
function. This results almost always a complex attribute.
Gabor Csardi [email protected]
graph_attr()
, vertex_attr()
,
edge_attr()
on how to use graph/vertex/edge attributes in
general. igraph_options()
on igraph parameters.
Vertex, edge and graph attributes
delete_edge_attr()
,
delete_graph_attr()
,
delete_vertex_attr()
,
edge_attr()
,
edge_attr<-()
,
edge_attr_names()
,
graph_attr()
,
graph_attr<-()
,
graph_attr_names()
,
igraph-dollar
,
igraph-vs-attributes
,
set_edge_attr()
,
set_graph_attr()
,
set_vertex_attr()
,
vertex_attr()
,
vertex_attr<-()
,
vertex_attr_names()
g <- make_graph(c(1, 2, 1, 2, 1, 2, 2, 3, 3, 4)) E(g)$weight <- 1:5 ## print attribute values with the graph igraph_options(print.graph.attributes = TRUE) igraph_options(print.vertex.attributes = TRUE) igraph_options(print.edge.attributes = TRUE) ## new attribute is the sum of the old ones simplify(g, edge.attr.comb = "sum") ## collect attributes into a string simplify(g, edge.attr.comb = toString) ## concatenate them into a vector, this creates a complex ## attribute simplify(g, edge.attr.comb = "concat") E(g)$name <- letters[seq_len(ecount(g))] ## both attributes are collected into strings simplify(g, edge.attr.comb = toString) ## harmonic average of weights, names are dropped simplify(g, edge.attr.comb = list( weight = function(x) length(x) / sum(1 / x), name = "ignore" ))
g <- make_graph(c(1, 2, 1, 2, 1, 2, 2, 3, 3, 4)) E(g)$weight <- 1:5 ## print attribute values with the graph igraph_options(print.graph.attributes = TRUE) igraph_options(print.vertex.attributes = TRUE) igraph_options(print.edge.attributes = TRUE) ## new attribute is the sum of the old ones simplify(g, edge.attr.comb = "sum") ## collect attributes into a string simplify(g, edge.attr.comb = toString) ## concatenate them into a vector, this creates a complex ## attribute simplify(g, edge.attr.comb = "concat") E(g)$name <- letters[seq_len(ecount(g))] ## both attributes are collected into strings simplify(g, edge.attr.comb = toString) ## harmonic average of weights, names are dropped simplify(g, edge.attr.comb = list( weight = function(x) length(x) / sum(1 / x), name = "ignore" ))
The $
operator is a shortcut to get and and set
graph attributes. It is shorter and just as readable as
graph_attr()
and set_graph_attr()
.
## S3 method for class 'igraph' x$name ## S3 replacement method for class 'igraph' x$name <- value
## S3 method for class 'igraph' x$name ## S3 replacement method for class 'igraph' x$name <- value
x |
An igraph graph |
name |
Name of the attribute to get/set. |
value |
New value of the graph attribute. |
Vertex, edge and graph attributes
delete_edge_attr()
,
delete_graph_attr()
,
delete_vertex_attr()
,
edge_attr()
,
edge_attr<-()
,
edge_attr_names()
,
graph_attr()
,
graph_attr<-()
,
graph_attr_names()
,
igraph-attribute-combination
,
igraph-vs-attributes
,
set_edge_attr()
,
set_graph_attr()
,
set_vertex_attr()
,
vertex_attr()
,
vertex_attr<-()
,
vertex_attr_names()
g <- make_ring(10) g$name g$name <- "10-ring" g$name
g <- make_ring(10) g$name g$name <- "10-ring" g$name
The $
operator is a syntactic sugar to query and set
edge attributes, for edges in an edge sequence.
## S3 replacement method for class 'igraph.es' x[[i]] <- value ## S3 replacement method for class 'igraph.es' x[i] <- value ## S3 method for class 'igraph.es' x$name ## S3 replacement method for class 'igraph.es' x$name <- value E(x, path = NULL, P = NULL, directed = NULL) <- value
## S3 replacement method for class 'igraph.es' x[[i]] <- value ## S3 replacement method for class 'igraph.es' x[i] <- value ## S3 method for class 'igraph.es' x$name ## S3 replacement method for class 'igraph.es' x$name <- value E(x, path = NULL, P = NULL, directed = NULL) <- value
x |
An edge sequence. For |
i |
Index. |
value |
New value of the attribute, for the edges in the edge sequence. |
name |
Name of the edge attribute to query or set. |
path |
Select edges along a path, given by a vertex sequence See
|
P |
Select edges via pairs of vertices. See |
directed |
Whether to use edge directions for the |
The query form of $
is a shortcut for edge_attr()
,
e.g. E(g)[idx]$attr
is equivalent to edge_attr(g, attr, E(g)[idx])
.
The assignment form of $
is a shortcut for
set_edge_attr()
, e.g. E(g)[idx]$attr <- value
is
equivalent to g <- set_edge_attr(g, attr, E(g)[idx], value)
.
A vector or list, containing the values of the attribute
name
for the edges in the sequence. For numeric, character or
logical attributes, it is a vector of the appropriate type, otherwise
it is a list.
Other vertex and edge sequences:
E()
,
V()
,
as_ids()
,
igraph-es-indexing
,
igraph-es-indexing2
,
igraph-vs-attributes
,
igraph-vs-indexing
,
igraph-vs-indexing2
,
print.igraph.es()
,
print.igraph.vs()
# color edges of the largest component largest_comp <- function(graph) { cl <- components(graph) V(graph)[which.max(cl$csize) == cl$membership] } g <- sample_( gnp(100, 1 / 100), with_vertex_(size = 3, label = ""), with_graph_(layout = layout_with_fr) ) giant_v <- largest_comp(g) E(g)$color <- "orange" E(g)[giant_v %--% giant_v]$color <- "blue" plot(g)
# color edges of the largest component largest_comp <- function(graph) { cl <- components(graph) V(graph)[which.max(cl$csize) == cl$membership] } g <- sample_( gnp(100, 1 / 100), with_vertex_(size = 3, label = ""), with_graph_(layout = layout_with_fr) ) giant_v <- largest_comp(g) E(g)$color <- "orange" E(g)[giant_v %--% giant_v]$color <- "blue" plot(g)
Edge sequences can be indexed very much like a plain numeric R vector, with some extras.
## S3 method for class 'igraph.es' x[...]
## S3 method for class 'igraph.es' x[...]
x |
An edge sequence |
... |
Indices, see details below. |
Another edge sequence, referring to the same graph.
When using multiple indices within the bracket, all of them
are evaluated independently, and then the results are concatenated
using the c()
function. E.g. E(g)[1, 2, .inc(1)]
is equivalent to c(E(g)[1], E(g)[2], E(g)[.inc(1)])
.
Edge sequences can be indexed with positive numeric vectors, negative numeric vectors, logical vectors, character vectors:
When indexed with positive numeric vectors, the edges at the given positions in the sequence are selected. This is the same as indexing a regular R atomic vector with positive numeric vectors.
When indexed with negative numeric vectors, the edges at the given positions in the sequence are omitted. Again, this is the same as indexing a regular R atomic vector.
When indexed with a logical vector, the lengths of the edge
sequence and the index must match, and the edges for which the
index is TRUE
are selected.
Named graphs can be indexed with character vectors,
to select edges with the given names. Note that a graph may
have edge names and vertex names, and both can be used to select
edges. Edge names are simply used as names of the numeric
edge id vector. Vertex names effectively only work in graphs without
multiple edges, and must be separated with a |
bar character
to select an edges that incident to the two given vertices. See
examples below.
When indexing edge sequences, edge attributes can be referred
to simply by using their names. E.g. if a graph has a weight
edge
attribute, then E(G)[weight > 1]
selects all edges with a weight
larger than one. See more examples below. Note that attribute names mask the
names of variables present in the calling environment; if you need to look up
a variable and you do not want a similarly named edge attribute to mask it,
use the .env
pronoun to perform the name lookup in the calling
environment. In other words, use E(g)[.env$weight > 1]
to make sure
that weight
is looked up from the calling environment even if there is
an edge attribute with the same name. Similarly, you can use .data
to
match attribute names only.
There are some special igraph functions that can be used only in expressions indexing edge sequences:
.inc
takes a vertex sequence, and selects all edges that have at least one incident vertex in the vertex sequence.
.from
similar to .inc()
, but only
the tails of the edges are considered.
.to
is similar to .inc()
, but only
the heads of the edges are considered.
\%--\%
a special operator that can be used to select all edges between two sets of vertices. It ignores the edge directions in directed graphs.
\%->\%
similar to \%--\%
,
but edges from the left hand side argument, pointing
to the right hand side argument, are selected, in directed
graphs.
\%<-\%
similar to \%--\%
,
but edges to the left hand side argument, pointing
from the right hand side argument, are selected, in directed
graphs.
Note that multiple special functions can be used together, or with regular indices, and then their results are concatenated. See more examples below.
Other vertex and edge sequences:
E()
,
V()
,
as_ids()
,
igraph-es-attributes
,
igraph-es-indexing2
,
igraph-vs-attributes
,
igraph-vs-indexing
,
igraph-vs-indexing2
,
print.igraph.es()
,
print.igraph.vs()
Other vertex and edge sequence operations:
c.igraph.es()
,
c.igraph.vs()
,
difference.igraph.es()
,
difference.igraph.vs()
,
igraph-es-indexing2
,
igraph-vs-indexing
,
igraph-vs-indexing2
,
intersection.igraph.es()
,
intersection.igraph.vs()
,
rev.igraph.es()
,
rev.igraph.vs()
,
union.igraph.es()
,
union.igraph.vs()
,
unique.igraph.es()
,
unique.igraph.vs()
# ----------------------------------------------------------------- # Special operators for indexing based on graph structure g <- sample_pa(100, power = 0.3) E(g)[1:3 %--% 2:6] E(g)[1:5 %->% 1:6] E(g)[1:3 %<-% 2:6] # ----------------------------------------------------------------- # The edges along the diameter g <- sample_pa(100, directed = FALSE) d <- get_diameter(g) E(g, path = d) # ----------------------------------------------------------------- # Select edges based on attributes g <- sample_gnp(20, 3 / 20) %>% set_edge_attr("weight", value = rnorm(gsize(.))) E(g)[[weight < 0]] # Indexing with a variable whose name matches the name of an attribute # may fail; use .env to force the name lookup in the parent environment E(g)$x <- E(g)$weight x <- 2 E(g)[.env$x]
# ----------------------------------------------------------------- # Special operators for indexing based on graph structure g <- sample_pa(100, power = 0.3) E(g)[1:3 %--% 2:6] E(g)[1:5 %->% 1:6] E(g)[1:3 %<-% 2:6] # ----------------------------------------------------------------- # The edges along the diameter g <- sample_pa(100, directed = FALSE) d <- get_diameter(g) E(g, path = d) # ----------------------------------------------------------------- # Select edges based on attributes g <- sample_gnp(20, 3 / 20) %>% set_edge_attr("weight", value = rnorm(gsize(.))) E(g)[[weight < 0]] # Indexing with a variable whose name matches the name of an attribute # may fail; use .env to force the name lookup in the parent environment E(g)$x <- E(g)$weight x <- 2 E(g)[.env$x]
The double bracket operator can be used on edge sequences, to print the meta-data (edge attributes) of the edges in the sequence.
## S3 method for class 'igraph.es' x[[...]]
## S3 method for class 'igraph.es' x[[...]]
x |
An edge sequence. |
... |
Additional arguments, passed to |
Technically, when used with edge sequences, the double bracket operator does exactly the same as the single bracket operator, but the resulting edge sequence is printed differently: all attributes of the edges in the sequence are printed as well.
See [.igraph.es
for more about indexing edge sequences.
Another edge sequence, with metadata printing turned on. See details below.
Other vertex and edge sequences:
E()
,
V()
,
as_ids()
,
igraph-es-attributes
,
igraph-es-indexing
,
igraph-vs-attributes
,
igraph-vs-indexing
,
igraph-vs-indexing2
,
print.igraph.es()
,
print.igraph.vs()
Other vertex and edge sequence operations:
c.igraph.es()
,
c.igraph.vs()
,
difference.igraph.es()
,
difference.igraph.vs()
,
igraph-es-indexing
,
igraph-vs-indexing
,
igraph-vs-indexing2
,
intersection.igraph.es()
,
intersection.igraph.vs()
,
rev.igraph.es()
,
rev.igraph.vs()
,
union.igraph.es()
,
union.igraph.vs()
,
unique.igraph.es()
,
unique.igraph.vs()
g <- make_( ring(10), with_vertex_(name = LETTERS[1:10]), with_edge_(weight = 1:10, color = "green") ) E(g) E(g)[[]] E(g)[[.inc("A")]]
g <- make_( ring(10), with_vertex_(name = LETTERS[1:10]), with_edge_(weight = 1:10, color = "green") ) E(g) E(g)[[]] E(g)[[.inc("A")]]
Delete vertices or edges from a graph
## S3 method for class 'igraph' e1 - e2
## S3 method for class 'igraph' e1 - e2
e1 |
Left argument, see details below. |
e2 |
Right argument, see details below. |
The minus operator (‘-
’) can be used to remove vertices
or edges from the graph. The operation performed is selected based on
the type of the right hand side argument:
If it is an igraph graph object, then the difference of the
two graphs is calculated, see difference()
.
If it is a numeric or character vector, then it is interpreted as a vector of vertex ids and the specified vertices will be deleted from the graph. Example:
g <- make_ring(10) V(g)$name <- letters[1:10] g <- g - c("a", "b")
If e2
is a vertex sequence (e.g. created by the
V()
function), then these vertices will be deleted from
the graph.
If it is an edge sequence (e.g. created by the E()
function), then these edges will be deleted from the graph.
If it is an object created with the vertex()
(or the
vertices()
) function, then all arguments of vertices()
are
concatenated and the result is interpreted as a vector of vertex
ids. These vertices will be removed from the graph.
If it is an object created with the edge()
(or the
edges()
) function, then all arguments of edges()
are
concatenated and then interpreted as edges to be removed from the
graph.
Example:
g <- make_ring(10) V(g)$name <- letters[1:10] E(g)$name <- LETTERS[1:10] g <- g - edge("e|f") g <- g - edge("H")
If it is an object created with the path()
function,
then all path()
arguments are concatenated and then interpreted
as a path along which edges will be removed from the graph.
Example:
g <- make_ring(10) V(g)$name <- letters[1:10] g <- g - path("a", "b", "c", "d")
An igraph graph.
Other functions for manipulating graph structure:
+.igraph()
,
add_edges()
,
add_vertices()
,
complementer()
,
compose()
,
connect()
,
contract()
,
delete_edges()
,
delete_vertices()
,
difference()
,
difference.igraph()
,
disjoint_union()
,
edge()
,
intersection()
,
intersection.igraph()
,
path()
,
permute()
,
rep.igraph()
,
reverse_edges()
,
simplify()
,
union()
,
union.igraph()
,
vertex()
The $
operator is a syntactic sugar to query and set the
attributes of the vertices in a vertex sequence.
## S3 replacement method for class 'igraph.vs' x[[i]] <- value ## S3 replacement method for class 'igraph.vs' x[i] <- value ## S3 method for class 'igraph.vs' x$name ## S3 replacement method for class 'igraph.vs' x$name <- value V(x) <- value
## S3 replacement method for class 'igraph.vs' x[[i]] <- value ## S3 replacement method for class 'igraph.vs' x[i] <- value ## S3 method for class 'igraph.vs' x$name ## S3 replacement method for class 'igraph.vs' x$name <- value V(x) <- value
x |
A vertex sequence. For |
i |
Index. |
value |
New value of the attribute, for the vertices in the vertex sequence. |
name |
Name of the vertex attribute to query or set. |
The query form of $
is a shortcut for
vertex_attr()
, e.g. V(g)[idx]$attr
is equivalent
to vertex_attr(g, attr, V(g)[idx])
.
The assignment form of $
is a shortcut for
set_vertex_attr()
, e.g. V(g)[idx]$attr <- value
is
equivalent to g <- set_vertex_attr(g, attr, V(g)[idx], value)
.
A vector or list, containing the values of
attribute name
for the vertices in the vertex sequence.
For numeric, character or logical attributes, it is a vector of the
appropriate type, otherwise it is a list.
Other vertex and edge sequences:
E()
,
V()
,
as_ids()
,
igraph-es-attributes
,
igraph-es-indexing
,
igraph-es-indexing2
,
igraph-vs-indexing
,
igraph-vs-indexing2
,
print.igraph.es()
,
print.igraph.vs()
Vertex, edge and graph attributes
delete_edge_attr()
,
delete_graph_attr()
,
delete_vertex_attr()
,
edge_attr()
,
edge_attr<-()
,
edge_attr_names()
,
graph_attr()
,
graph_attr<-()
,
graph_attr_names()
,
igraph-attribute-combination
,
igraph-dollar
,
set_edge_attr()
,
set_graph_attr()
,
set_vertex_attr()
,
vertex_attr()
,
vertex_attr<-()
,
vertex_attr_names()
g <- make_( ring(10), with_vertex_( name = LETTERS[1:10], color = sample(1:2, 10, replace = TRUE) ) ) V(g)$name V(g)$color V(g)$frame.color <- V(g)$color # color vertices of the largest component largest_comp <- function(graph) { cl <- components(graph) V(graph)[which.max(cl$csize) == cl$membership] } g <- sample_( gnp(100, 2 / 100), with_vertex_(size = 3, label = ""), with_graph_(layout = layout_with_fr) ) giant_v <- largest_comp(g) V(g)$color <- "blue" V(g)[giant_v]$color <- "orange" plot(g)
g <- make_( ring(10), with_vertex_( name = LETTERS[1:10], color = sample(1:2, 10, replace = TRUE) ) ) V(g)$name V(g)$color V(g)$frame.color <- V(g)$color # color vertices of the largest component largest_comp <- function(graph) { cl <- components(graph) V(graph)[which.max(cl$csize) == cl$membership] } g <- sample_( gnp(100, 2 / 100), with_vertex_(size = 3, label = ""), with_graph_(layout = layout_with_fr) ) giant_v <- largest_comp(g) V(g)$color <- "blue" V(g)[giant_v]$color <- "orange" plot(g)
Vertex sequences can be indexed very much like a plain numeric R vector, with some extras.
## S3 method for class 'igraph.vs' x[..., na_ok = FALSE]
## S3 method for class 'igraph.vs' x[..., na_ok = FALSE]
x |
A vertex sequence. |
... |
Indices, see details below. |
na_ok |
Whether it is OK to have |
Vertex sequences can be indexed using both the single bracket and the double bracket operators, and they both work the same way. The only difference between them is that the double bracket operator marks the result for printing vertex attributes.
Another vertex sequence, referring to the same graph.
When using multiple indices within the bracket, all of them
are evaluated independently, and then the results are concatenated
using the c()
function (except for the na_ok
argument,
which is special an must be named. E.g. V(g)[1, 2, .nei(1)]
is equivalent to c(V(g)[1], V(g)[2], V(g)[.nei(1)])
.
Vertex sequences can be indexed with positive numeric vectors, negative numeric vectors, logical vectors, character vectors:
When indexed with positive numeric vectors, the vertices at the given positions in the sequence are selected. This is the same as indexing a regular R atomic vector with positive numeric vectors.
When indexed with negative numeric vectors, the vertices at the given positions in the sequence are omitted. Again, this is the same as indexing a regular R atomic vector.
When indexed with a logical vector, the lengths of the vertex
sequence and the index must match, and the vertices for which the
index is TRUE
are selected.
Named graphs can be indexed with character vectors, to select vertices with the given names.
When indexing vertex sequences, vertex attributes can be referred
to simply by using their names. E.g. if a graph has a name
vertex
attribute, then V(g)[name == "foo"]
is equivalent to
V(g)[V(g)$name == "foo"]
. See more examples below. Note that attribute
names mask the names of variables present in the calling environment; if
you need to look up a variable and you do not want a similarly named
vertex attribute to mask it, use the .env
pronoun to perform the
name lookup in the calling environment. In other words, use
V(g)[.env$name == "foo"]
to make sure that name
is looked up
from the calling environment even if there is a vertex attribute with the
same name. Similarly, you can use .data
to match attribute names only.
There are some special igraph functions that can be used only in expressions indexing vertex sequences:
.nei
takes a vertex sequence as its argument
and selects neighbors of these vertices. An optional mode
argument can be used to select successors (mode="out"
), or
predecessors (mode="in"
) in directed graphs.
.inc
Takes an edge sequence as an argument, and selects vertices that have at least one incident edge in this edge sequence.
.from
Similar to .inc
, but only considers the
tails of the edges.
.to
Similar to .inc
, but only considers the
heads of the edges.
.innei
, .outnei
.innei(v)
is a shorthand for
.nei(v, mode = "in")
, and .outnei(v)
is a shorthand for
.nei(v, mode = "out")
.
Note that multiple special functions can be used together, or with regular indices, and then their results are concatenated. See more examples below.
Other vertex and edge sequences:
E()
,
V()
,
as_ids()
,
igraph-es-attributes
,
igraph-es-indexing
,
igraph-es-indexing2
,
igraph-vs-attributes
,
igraph-vs-indexing2
,
print.igraph.es()
,
print.igraph.vs()
Other vertex and edge sequence operations:
c.igraph.es()
,
c.igraph.vs()
,
difference.igraph.es()
,
difference.igraph.vs()
,
igraph-es-indexing
,
igraph-es-indexing2
,
igraph-vs-indexing2
,
intersection.igraph.es()
,
intersection.igraph.vs()
,
rev.igraph.es()
,
rev.igraph.vs()
,
union.igraph.es()
,
union.igraph.vs()
,
unique.igraph.es()
,
unique.igraph.vs()
# ----------------------------------------------------------------- # Setting attributes for subsets of vertices largest_comp <- function(graph) { cl <- components(graph) V(graph)[which.max(cl$csize) == cl$membership] } g <- sample_( gnp(100, 2 / 100), with_vertex_(size = 3, label = ""), with_graph_(layout = layout_with_fr) ) giant_v <- largest_comp(g) V(g)$color <- "green" V(g)[giant_v]$color <- "red" plot(g) # ----------------------------------------------------------------- # nei() special function g <- make_graph(c(1, 2, 2, 3, 2, 4, 4, 2)) V(g)[.nei(c(2, 4))] V(g)[.nei(c(2, 4), "in")] V(g)[.nei(c(2, 4), "out")] # ----------------------------------------------------------------- # The same with vertex names g <- make_graph(~ A -+ B, B -+ C:D, D -+ B) V(g)[.nei(c("B", "D"))] V(g)[.nei(c("B", "D"), "in")] V(g)[.nei(c("B", "D"), "out")] # ----------------------------------------------------------------- # Resolving attributes g <- make_graph(~ A -+ B, B -+ C:D, D -+ B) V(g)$color <- c("red", "red", "green", "green") V(g)[color == "red"] # Indexing with a variable whose name matches the name of an attribute # may fail; use .env to force the name lookup in the parent environment V(g)$x <- 10:13 x <- 2 V(g)[.env$x]
# ----------------------------------------------------------------- # Setting attributes for subsets of vertices largest_comp <- function(graph) { cl <- components(graph) V(graph)[which.max(cl$csize) == cl$membership] } g <- sample_( gnp(100, 2 / 100), with_vertex_(size = 3, label = ""), with_graph_(layout = layout_with_fr) ) giant_v <- largest_comp(g) V(g)$color <- "green" V(g)[giant_v]$color <- "red" plot(g) # ----------------------------------------------------------------- # nei() special function g <- make_graph(c(1, 2, 2, 3, 2, 4, 4, 2)) V(g)[.nei(c(2, 4))] V(g)[.nei(c(2, 4), "in")] V(g)[.nei(c(2, 4), "out")] # ----------------------------------------------------------------- # The same with vertex names g <- make_graph(~ A -+ B, B -+ C:D, D -+ B) V(g)[.nei(c("B", "D"))] V(g)[.nei(c("B", "D"), "in")] V(g)[.nei(c("B", "D"), "out")] # ----------------------------------------------------------------- # Resolving attributes g <- make_graph(~ A -+ B, B -+ C:D, D -+ B) V(g)$color <- c("red", "red", "green", "green") V(g)[color == "red"] # Indexing with a variable whose name matches the name of an attribute # may fail; use .env to force the name lookup in the parent environment V(g)$x <- 10:13 x <- 2 V(g)[.env$x]
The double bracket operator can be used on vertex sequences, to print the meta-data (vertex attributes) of the vertices in the sequence.
## S3 method for class 'igraph.vs' x[[...]]
## S3 method for class 'igraph.vs' x[[...]]
x |
A vertex sequence. |
... |
Additional arguments, passed to |
Technically, when used with vertex sequences, the double bracket operator does exactly the same as the single bracket operator, but the resulting vertex sequence is printed differently: all attributes of the vertices in the sequence are printed as well.
See [.igraph.vs
for more about indexing vertex sequences.
The double bracket operator returns another vertex sequence, with meta-data (attribute) printing turned on. See details below.
Other vertex and edge sequences:
E()
,
V()
,
as_ids()
,
igraph-es-attributes
,
igraph-es-indexing
,
igraph-es-indexing2
,
igraph-vs-attributes
,
igraph-vs-indexing
,
print.igraph.es()
,
print.igraph.vs()
Other vertex and edge sequence operations:
c.igraph.es()
,
c.igraph.vs()
,
difference.igraph.es()
,
difference.igraph.vs()
,
igraph-es-indexing
,
igraph-es-indexing2
,
igraph-vs-indexing
,
intersection.igraph.es()
,
intersection.igraph.vs()
,
rev.igraph.es()
,
rev.igraph.vs()
,
union.igraph.es()
,
union.igraph.vs()
,
unique.igraph.es()
,
unique.igraph.vs()
g <- make_ring(10) %>% set_vertex_attr("color", value = "red") %>% set_vertex_attr("name", value = LETTERS[1:10]) V(g) V(g)[[]] V(g)[1:5] V(g)[[1:5]]
g <- make_ring(10) %>% set_vertex_attr("color", value = "red") %>% set_vertex_attr("name", value = LETTERS[1:10]) V(g) V(g)[[]] V(g)[1:5] V(g)[[1:5]]
Incident edges of a vertex in a graph
incident(graph, v, mode = c("all", "out", "in", "total"))
incident(graph, v, mode = c("all", "out", "in", "total"))
graph |
The input graph. |
v |
The vertex of which the incident edges are queried. |
mode |
Whether to query outgoing (‘out’), incoming (‘in’) edges, or both types (‘all’). This is ignored for undirected graphs. |
An edge sequence containing the incident edges of the input vertex.
Other structural queries:
[.igraph()
,
[[.igraph()
,
adjacent_vertices()
,
are_adjacent()
,
ends()
,
get_edge_ids()
,
gorder()
,
gsize()
,
head_of()
,
incident_edges()
,
is_directed()
,
neighbors()
,
tail_of()
g <- make_graph("Zachary") incident(g, 1) incident(g, 34)
g <- make_graph("Zachary") incident(g, 1) incident(g, 34)
This function is similar to incident()
, but it
queries multiple vertices at once.
incident_edges(graph, v, mode = c("out", "in", "all", "total"))
incident_edges(graph, v, mode = c("out", "in", "all", "total"))
graph |
Input graph. |
v |
The vertices to query |
mode |
Whether to query outgoing (‘out’), incoming (‘in’) edges, or both types (‘all’). This is ignored for undirected graphs. |
A list of edge sequences.
Other structural queries:
[.igraph()
,
[[.igraph()
,
adjacent_vertices()
,
are_adjacent()
,
ends()
,
get_edge_ids()
,
gorder()
,
gsize()
,
head_of()
,
incident()
,
is_directed()
,
neighbors()
,
tail_of()
g <- make_graph("Zachary") incident_edges(g, c(1, 34))
g <- make_graph("Zachary") incident_edges(g, c(1, 34))
Indent a printout
indent_print(..., .indent = " ", .printer = print)
indent_print(..., .indent = " ", .printer = print)
... |
Passed to the printing function. |
.indent |
Character scalar, indent the printout with this. |
.printer |
The printing function, defaults to print. |
The first element in ...
, invisibly.
This is an S3 generic function. See methods("intersection")
for the actual implementations for various S3 classes. Initially
it is implemented for igraph graphs and igraph vertex and edge
sequences. See
intersection.igraph()
, and
intersection.igraph.vs()
.
intersection(...)
intersection(...)
... |
Arguments, their number and interpretation depends on
the function that implements |
Depends on the function that implements this method.
Other functions for manipulating graph structure:
+.igraph()
,
add_edges()
,
add_vertices()
,
complementer()
,
compose()
,
connect()
,
contract()
,
delete_edges()
,
delete_vertices()
,
difference()
,
difference.igraph()
,
disjoint_union()
,
edge()
,
igraph-minus
,
intersection.igraph()
,
path()
,
permute()
,
rep.igraph()
,
reverse_edges()
,
simplify()
,
union()
,
union.igraph()
,
vertex()
The intersection of two or more graphs are created. The graphs may have identical or overlapping vertex sets.
## S3 method for class 'igraph' intersection(..., byname = "auto", keep.all.vertices = TRUE)
## S3 method for class 'igraph' intersection(..., byname = "auto", keep.all.vertices = TRUE)
... |
Graph objects or lists of graph objects. |
byname |
A logical scalar, or the character scalar |
keep.all.vertices |
Logical scalar, whether to keep vertices that only appear in a subset of the input graphs. |
intersection()
creates the intersection of two or more graphs:
only edges present in all graphs will be included. The corresponding
operator is %s%
.
If the byname
argument is TRUE
(or auto
and all graphs
are named), then the operation is performed on symbolic vertex names instead
of the internal numeric vertex ids.
intersection()
keeps the attributes of all graphs. All graph,
vertex and edge attributes are copied to the result. If an attribute is
present in multiple graphs and would result a name clash, then this
attribute is renamed by adding suffixes: _1, _2, etc.
The name
vertex attribute is treated specially if the operation is
performed based on symbolic vertex names. In this case name
must be
present in all graphs, and it is not renamed in the result graph.
An error is generated if some input graphs are directed and others are undirected.
A new graph object.
Gabor Csardi [email protected]
Other functions for manipulating graph structure:
+.igraph()
,
add_edges()
,
add_vertices()
,
complementer()
,
compose()
,
connect()
,
contract()
,
delete_edges()
,
delete_vertices()
,
difference()
,
difference.igraph()
,
disjoint_union()
,
edge()
,
igraph-minus
,
intersection()
,
path()
,
permute()
,
rep.igraph()
,
reverse_edges()
,
simplify()
,
union()
,
union.igraph()
,
vertex()
## Common part of two social networks net1 <- graph_from_literal( D - A:B:F:G, A - C - F - A, B - E - G - B, A - B, F - G, H - F:G, H - I - J ) net2 <- graph_from_literal(D - A:F:Y, B - A - X - F - H - Z, F - Y) print_all(net1 %s% net2)
## Common part of two social networks net1 <- graph_from_literal( D - A:B:F:G, A - C - F - A, B - E - G - B, A - B, F - G, H - F:G, H - I - J ) net2 <- graph_from_literal(D - A:F:Y, B - A - X - F - H - Z, F - Y) print_all(net1 %s% net2)
Intersection of edge sequences
## S3 method for class 'igraph.es' intersection(...)
## S3 method for class 'igraph.es' intersection(...)
... |
The edge sequences to take the intersection of. |
They must belong to the same graph. Note that this function has ‘set’ semantics and the multiplicity of edges is lost in the result.
An edge sequence that contains edges that appear in all given sequences, each edge exactly once.
Other vertex and edge sequence operations:
c.igraph.es()
,
c.igraph.vs()
,
difference.igraph.es()
,
difference.igraph.vs()
,
igraph-es-indexing
,
igraph-es-indexing2
,
igraph-vs-indexing
,
igraph-vs-indexing2
,
intersection.igraph.vs()
,
rev.igraph.es()
,
rev.igraph.vs()
,
union.igraph.es()
,
union.igraph.vs()
,
unique.igraph.es()
,
unique.igraph.vs()
g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) intersection(E(g)[1:6], E(g)[5:9])
g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) intersection(E(g)[1:6], E(g)[5:9])
Intersection of vertex sequences
## S3 method for class 'igraph.vs' intersection(...)
## S3 method for class 'igraph.vs' intersection(...)
... |
The vertex sequences to take the intersection of. |
They must belong to the same graph. Note that this function has ‘set’ semantics and the multiplicity of vertices is lost in the result.
A vertex sequence that contains vertices that appear in all given sequences, each vertex exactly once.
Other vertex and edge sequence operations:
c.igraph.es()
,
c.igraph.vs()
,
difference.igraph.es()
,
difference.igraph.vs()
,
igraph-es-indexing
,
igraph-es-indexing2
,
igraph-vs-indexing
,
igraph-vs-indexing2
,
intersection.igraph.es()
,
rev.igraph.es()
,
rev.igraph.vs()
,
union.igraph.es()
,
union.igraph.vs()
,
unique.igraph.es()
,
unique.igraph.vs()
g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) intersection(E(g)[1:6], E(g)[5:9])
g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) intersection(E(g)[1:6], E(g)[5:9])
This function tests whether the given graph is free of cycles.
is_acyclic(graph)
is_acyclic(graph)
graph |
The input graph. |
This function looks for directed cycles in directed graphs and undirected cycles in undirected graphs.
A logical vector of length one.
is_forest()
and is_dag()
for functions specific to undirected
and directed graphs.
Graph cycles
feedback_arc_set()
,
girth()
,
has_eulerian_path()
,
is_dag()
Other structural.properties:
bfs()
,
component_distribution()
,
connect()
,
constraint()
,
coreness()
,
degree()
,
dfs()
,
distance_table()
,
edge_density()
,
feedback_arc_set()
,
girth()
,
is_dag()
,
is_matching()
,
k_shortest_paths()
,
knn()
,
reciprocity()
,
subcomponent()
,
subgraph()
,
topo_sort()
,
transitivity()
,
unfold_tree()
,
which_multiple()
,
which_mutual()
g <- make_graph(c(1,2, 1,3, 2,4, 3,4), directed = TRUE) is_acyclic(g) is_acyclic(as_undirected(g))
g <- make_graph(c(1,2, 1,3, 2,4, 3,4), directed = TRUE) is_acyclic(g) is_acyclic(as_undirected(g))
Tests whether a graph is biconnected.
is_biconnected(graph)
is_biconnected(graph)
graph |
The input graph. Edge directions are ignored. |
A graph is biconnected if the removal of any single vertex (and its adjacent edges) does not disconnect it.
igraph does not consider single-vertex graphs biconnected.
Note that some authors do not consider the graph consisting of two connected vertices as biconnected, however, igraph does.
Logical, TRUE
if the graph is biconnected.
articulation_points()
, biconnected_components()
,
is_connected()
, vertex_connectivity()
Connected components
articulation_points()
,
biconnected_components()
,
component_distribution()
,
decompose()
is_biconnected(make_graph("bull")) is_biconnected(make_graph("dodecahedron")) is_biconnected(make_full_graph(1)) is_biconnected(make_full_graph(2))
is_biconnected(make_graph("bull")) is_biconnected(make_graph("dodecahedron")) is_biconnected(make_full_graph(1)) is_biconnected(make_full_graph(2))
type
.It does not check whether the graph is bipartite in the
mathematical sense. Use bipartite_mapping()
for that.
is_bipartite(graph)
is_bipartite(graph)
graph |
The input graph |
Bipartite graphs
bipartite_mapping()
,
bipartite_projection()
,
make_bipartite_graph()
A graph is chordal (or triangulated) if each of its cycles of four or more nodes has a chord, which is an edge joining two nodes that are not adjacent in the cycle. An equivalent definition is that any chordless cycles have at most three nodes.
is_chordal( graph, alpha = NULL, alpham1 = NULL, fillin = FALSE, newgraph = FALSE )
is_chordal( graph, alpha = NULL, alpham1 = NULL, fillin = FALSE, newgraph = FALSE )
graph |
The input graph. It may be directed, but edge directions are ignored, as the algorithm is defined for undirected graphs. |
alpha |
Numeric vector, the maximal chardinality ordering of the
vertices. If it is |
alpham1 |
Numeric vector, the inverse of |
fillin |
Logical scalar, whether to calculate the fill-in edges. |
newgraph |
Logical scalar, whether to calculate the triangulated graph. |
The chordality of the graph is decided by first performing maximum
cardinality search on it (if the alpha
and alpham1
arguments
are NULL
), and then calculating the set of fill-in edges.
The set of fill-in edges is empty if and only if the graph is chordal.
It is also true that adding the fill-in edges to the graph makes it chordal.
A list with three members:
chordal |
Logical scalar, it is
|
fillin |
If requested,
then a numeric vector giving the fill-in edges. |
newgraph |
If requested, then the triangulated graph, an |
Gabor Csardi [email protected]
Robert E Tarjan and Mihalis Yannakakis. (1984). Simple linear-time algorithms to test chordality of graphs, test acyclicity of hypergraphs, and selectively reduce acyclic hypergraphs. SIAM Journal of Computation 13, 566–579.
Other chordal:
max_cardinality()
## The examples from the Tarjan-Yannakakis paper g1 <- graph_from_literal( A - B:C:I, B - A:C:D, C - A:B:E:H, D - B:E:F, E - C:D:F:H, F - D:E:G, G - F:H, H - C:E:G:I, I - A:H ) max_cardinality(g1) is_chordal(g1, fillin = TRUE) g2 <- graph_from_literal( A - B:E, B - A:E:F:D, C - E:D:G, D - B:F:E:C:G, E - A:B:C:D:F, F - B:D:E, G - C:D:H:I, H - G:I:J, I - G:H:J, J - H:I ) max_cardinality(g2) is_chordal(g2, fillin = TRUE)
## The examples from the Tarjan-Yannakakis paper g1 <- graph_from_literal( A - B:C:I, B - A:C:D, C - A:B:E:H, D - B:E:F, E - C:D:F:H, F - D:E:G, G - F:H, H - C:E:G:I, I - A:H ) max_cardinality(g1) is_chordal(g1, fillin = TRUE) g2 <- graph_from_literal( A - B:E, B - A:E:F:D, C - E:D:G, D - B:F:E:C:G, E - A:B:C:D:F, F - B:D:E, G - C:D:H:I, H - G:I:J, I - G:H:J, J - H:I ) max_cardinality(g2) is_chordal(g2, fillin = TRUE)
This function tests whether the given graph is a DAG, a directed acyclic graph.
is_dag(graph)
is_dag(graph)
graph |
The input graph. It may be undirected, in which case
|
is_dag()
checks whether there is a directed cycle in the graph. If not,
the graph is a DAG.
A logical vector of length one.
Tamas Nepusz [email protected] for the C code, Gabor Csardi [email protected] for the R interface.
Graph cycles
feedback_arc_set()
,
girth()
,
has_eulerian_path()
,
is_acyclic()
Other structural.properties:
bfs()
,
component_distribution()
,
connect()
,
constraint()
,
coreness()
,
degree()
,
dfs()
,
distance_table()
,
edge_density()
,
feedback_arc_set()
,
girth()
,
is_acyclic()
,
is_matching()
,
k_shortest_paths()
,
knn()
,
reciprocity()
,
subcomponent()
,
subgraph()
,
topo_sort()
,
transitivity()
,
unfold_tree()
,
which_multiple()
,
which_mutual()
g <- make_tree(10) is_dag(g) g2 <- g + edge(5, 1) is_dag(g2)
g <- make_tree(10) is_dag(g) g2 <- g + edge(5, 1) is_dag(g2)
is_degseq()
checks whether the given vertex degrees (in- and
out-degrees for directed graphs) can be realized by a graph. Note that the
graph does not have to be simple, it may contain loop and multiple edges.
For undirected graphs, it also checks whether the sum of degrees is even.
For directed graphs, the function checks whether the lengths of the two
degree vectors are equal and whether their sums are also equal. These are
known sufficient and necessary conditions for a degree sequence to be valid.
is_degseq(out.deg, in.deg = NULL)
is_degseq(out.deg, in.deg = NULL)
out.deg |
Integer vector, the degree sequence for undirected graphs, or the out-degree sequence for directed graphs. |
in.deg |
|
A logical scalar.
Tamás Nepusz [email protected] and Szabolcs Horvát [email protected]
Z Király, Recognizing graphic degree sequences and generating all realizations. TR-2011-11, Egerváry Research Group, H-1117, Budapest, Hungary. ISSN 1587-4451 (2012).
B. Cloteaux, Is This for Real? Fast Graphicality Testing, Comput. Sci. Eng. 17, 91 (2015).
A. Berger, A note on the characterization of digraphic sequences, Discrete Math. 314, 38 (2014).
G. Cairns and S. Mendan, Degree Sequence for Graphs with Loops (2013).
Other graphical degree sequences:
is_graphical()
g <- sample_gnp(100, 2 / 100) is_degseq(degree(g)) is_graphical(degree(g))
g <- sample_gnp(100, 2 / 100) is_degseq(degree(g)) is_graphical(degree(g))
Check whether a graph is directed
is_directed(graph)
is_directed(graph)
graph |
The input graph |
Logical scalar, whether the graph is directed.
Other structural queries:
[.igraph()
,
[[.igraph()
,
adjacent_vertices()
,
are_adjacent()
,
ends()
,
get_edge_ids()
,
gorder()
,
gsize()
,
head_of()
,
incident()
,
incident_edges()
,
neighbors()
,
tail_of()
g <- make_ring(10) is_directed(g) g2 <- make_ring(10, directed = TRUE) is_directed(g2)
g <- make_ring(10) is_directed(g) g2 <- make_ring(10, directed = TRUE) is_directed(g2)
is_forest()
decides whether a graph is a forest, and optionally returns a
set of possible root vertices for its components.
is_forest(graph, mode = c("out", "in", "all", "total"), details = FALSE)
is_forest(graph, mode = c("out", "in", "all", "total"), details = FALSE)
graph |
An igraph graph object |
mode |
Whether to consider edge directions in a directed graph. ‘all’ ignores edge directions; ‘out’ requires edges to be oriented outwards from the root, ‘in’ requires edges to be oriented towards the root. |
details |
Whether to return only whether the graph is a tree ( |
An undirected graph is a forest if it has no cycles. In the directed case, a possible additional requirement is that edges in each tree are oriented away from the root (out-trees or arborescences) or all edges are oriented towards the root (in-trees or anti-arborescences). This test can be controlled using the mode parameter.
By convention, the null graph (i.e. the graph with no vertices) is considered to be a forest.
When details
is FALSE
, a logical value that indicates
whether the graph is a tree. When details
is TRUE
, a named
list with two entries:
res |
Logical value that indicates whether the graph is a tree. |
root |
The root vertex of the tree; undefined if the graph is not a tree. |
Other trees:
is_tree()
,
make_from_prufer()
,
sample_spanning_tree()
,
to_prufer()
g <- make_tree(3) + make_tree(5,3) is_forest(g) is_forest(g, details = TRUE)
g <- make_tree(3) + make_tree(5,3) is_forest(g) is_forest(g, details = TRUE)
Determine whether the given vertex degrees (in- and out-degrees for directed graphs) can be realized by a graph.
is_graphical( out.deg, in.deg = NULL, allowed.edge.types = c("simple", "loops", "multi", "all") )
is_graphical( out.deg, in.deg = NULL, allowed.edge.types = c("simple", "loops", "multi", "all") )
out.deg |
Integer vector, the degree sequence for undirected graphs, or the out-degree sequence for directed graphs. |
in.deg |
|
allowed.edge.types |
The allowed edge types in the graph. ‘simple’ means that neither loop nor multiple edges are allowed (i.e. the graph must be simple). ‘loops’ means that loop edges are allowed but mutiple edges are not. ‘multi’ means that multiple edges are allowed but loop edges are not. ‘all’ means that both loop edges and multiple edges are allowed. |
The classical concept of graphicality assumes simple graphs. This function can perform the check also when self-loops, multi-edges, or both are allowed in the graph.
A logical scalar.
Tamás Nepusz [email protected]
Hakimi SL: On the realizability of a set of integers as degrees of the vertices of a simple graph. J SIAM Appl Math 10:496-506, 1962.
PL Erdős, I Miklós and Z Toroczkai: A simple Havel-Hakimi type algorithm to realize graphical degree sequences of directed graphs. The Electronic Journal of Combinatorics 17(1):R66, 2010.
Other graphical degree sequences:
is_degseq()
g <- sample_gnp(100, 2 / 100) is_degseq(degree(g)) is_graphical(degree(g))
g <- sample_gnp(100, 2 / 100) is_degseq(degree(g)) is_graphical(degree(g))
Is this object an igraph graph?
is_igraph(graph)
is_igraph(graph)
graph |
An R object. |
A logical constant, TRUE
if argument graph
is a graph
object.
Gabor Csardi [email protected]
g <- make_ring(10) is_igraph(g) is_igraph(numeric(10))
g <- make_ring(10) is_igraph(g) is_igraph(numeric(10))
A matching in a graph means the selection of a set of edges that are pairwise non-adjacent, i.e. they have no common incident vertices. A matching is maximal if it is not a proper subset of any other matching.
is_matching(graph, matching, types = NULL) is_max_matching(graph, matching, types = NULL) max_bipartite_match( graph, types = NULL, weights = NULL, eps = .Machine$double.eps )
is_matching(graph, matching, types = NULL) is_max_matching(graph, matching, types = NULL) max_bipartite_match( graph, types = NULL, weights = NULL, eps = .Machine$double.eps )
graph |
The input graph. It might be directed, but edge directions will be ignored. |
matching |
A potential matching. An integer vector that gives the
pair in the matching for each vertex. For vertices without a pair,
supply |
types |
Vertex types, if the graph is bipartite. By default they
are taken from the ‘ |
weights |
Potential edge weights. If the graph has an edge
attribute called ‘ |
eps |
A 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 |
is_matching()
checks a matching vector and verifies whether its
length matches the number of vertices in the given graph, its values are
between zero (inclusive) and the number of vertices (inclusive), and
whether there exists a corresponding edge in the graph for every matched
vertex pair. For bipartite graphs, it also verifies whether the matched
vertices are in different parts of the graph.
is_max_matching()
checks whether a matching is maximal. A matching
is maximal if and only if there exists no unmatched vertex in a graph
such that one of its neighbors is also unmatched.
max_bipartite_match()
calculates a maximum matching in a bipartite
graph. A matching in a bipartite graph is a partial assignment of
vertices of the first kind to vertices of the second kind such that each
vertex of the first kind is matched to at most one vertex of the second
kind and vice versa, and matched vertices must be connected by an edge
in the graph. The size (or cardinality) of a matching is the number of
edges. A matching is a maximum matching if there exists no other
matching with larger cardinality. For weighted graphs, a maximum
matching is a matching whose edges have the largest possible total
weight among all possible matchings.
Maximum matchings in bipartite graphs are found by the push-relabel
algorithm with greedy initialization and a global relabeling after every
steps where
is the number of vertices in the graph.
is_matching()
and is_max_matching()
return a logical
scalar.
max_bipartite_match()
returns a list with components:
matching_size |
The size of the matching, i.e. the number of edges connecting the matched vertices. |
matching_weight |
The weights of the matching, if the graph was weighted. For unweighted graphs this is the same as the size of the matching. |
matching |
The matching itself. Numeric vertex id, or vertex
names if the graph was named. Non-matched vertices are denoted by
|
Tamas Nepusz [email protected]
Other structural.properties:
bfs()
,
component_distribution()
,
connect()
,
constraint()
,
coreness()
,
degree()
,
dfs()
,
distance_table()
,
edge_density()
,
feedback_arc_set()
,
girth()
,
is_acyclic()
,
is_dag()
,
k_shortest_paths()
,
knn()
,
reciprocity()
,
subcomponent()
,
subgraph()
,
topo_sort()
,
transitivity()
,
unfold_tree()
,
which_multiple()
,
which_mutual()
g <- graph_from_literal(a - b - c - d - e - f) m1 <- c("b", "a", "d", "c", "f", "e") # maximal matching m2 <- c("b", "a", "d", "c", NA, NA) # non-maximal matching m3 <- c("b", "c", "d", "c", NA, NA) # not a matching is_matching(g, m1) is_matching(g, m2) is_matching(g, m3) is_max_matching(g, m1) is_max_matching(g, m2) is_max_matching(g, m3) V(g)$type <- rep(c(FALSE, TRUE), 3) print_all(g, v = TRUE) max_bipartite_match(g) g2 <- graph_from_literal(a - b - c - d - e - f - g) V(g2)$type <- rep(c(FALSE, TRUE), length.out = vcount(g2)) print_all(g2, v = TRUE) max_bipartite_match(g2) #' @keywords graphs
g <- graph_from_literal(a - b - c - d - e - f) m1 <- c("b", "a", "d", "c", "f", "e") # maximal matching m2 <- c("b", "a", "d", "c", NA, NA) # non-maximal matching m3 <- c("b", "c", "d", "c", NA, NA) # not a matching is_matching(g, m1) is_matching(g, m2) is_matching(g, m3) is_max_matching(g, m1) is_max_matching(g, m2) is_max_matching(g, m3) V(g)$type <- rep(c(FALSE, TRUE), 3) print_all(g, v = TRUE) max_bipartite_match(g) g2 <- graph_from_literal(a - b - c - d - e - f - g) V(g2)$type <- rep(c(FALSE, TRUE), length.out = vcount(g2)) print_all(g2, v = TRUE) max_bipartite_match(g2) #' @keywords graphs
Check whether a given set of vertices is a minimal vertex separator.
is_min_separator(graph, candidate)
is_min_separator(graph, candidate)
graph |
The input graph. It may be directed, but edge directions are ignored. |
candidate |
A numeric vector giving the vertex ids of the candidate separator. |
is_min_separator()
decides whether the supplied vertex set is a minimal
vertex separator. A minimal vertex separator is a vertex separator, such
that none of its proper subsets are a vertex separator.
A logical scalar, whether the supplied vertex set is a (minimal) vertex separator or not.
igraph_is_minimal_separator()
.
Other flow:
dominator_tree()
,
edge_connectivity()
,
is_separator()
,
max_flow()
,
min_cut()
,
min_separators()
,
min_st_separators()
,
st_cuts()
,
st_min_cuts()
,
vertex_connectivity()
# The graph from the Moody-White paper mw <- graph_from_literal( 1 - 2:3:4:5:6, 2 - 3:4:5:7, 3 - 4:6:7, 4 - 5:6:7, 5 - 6:7:21, 6 - 7, 7 - 8:11:14:19, 8 - 9:11:14, 9 - 10, 10 - 12:13, 11 - 12:14, 12 - 16, 13 - 16, 14 - 15, 15 - 16, 17 - 18:19:20, 18 - 20:21, 19 - 20:22:23, 20 - 21, 21 - 22:23, 22 - 23 ) # Cohesive subgraphs mw1 <- induced_subgraph(mw, as.character(c(1:7, 17:23))) mw2 <- induced_subgraph(mw, as.character(7:16)) mw3 <- induced_subgraph(mw, as.character(17:23)) mw4 <- induced_subgraph(mw, as.character(c(7, 8, 11, 14))) mw5 <- induced_subgraph(mw, as.character(1:7)) check.sep <- function(G) { sep <- min_separators(G) sapply(sep, is_min_separator, graph = G) } check.sep(mw) check.sep(mw1) check.sep(mw2) check.sep(mw3) check.sep(mw4) check.sep(mw5)
# The graph from the Moody-White paper mw <- graph_from_literal( 1 - 2:3:4:5:6, 2 - 3:4:5:7, 3 - 4:6:7, 4 - 5:6:7, 5 - 6:7:21, 6 - 7, 7 - 8:11:14:19, 8 - 9:11:14, 9 - 10, 10 - 12:13, 11 - 12:14, 12 - 16, 13 - 16, 14 - 15, 15 - 16, 17 - 18:19:20, 18 - 20:21, 19 - 20:22:23, 20 - 21, 21 - 22:23, 22 - 23 ) # Cohesive subgraphs mw1 <- induced_subgraph(mw, as.character(c(1:7, 17:23))) mw2 <- induced_subgraph(mw, as.character(7:16)) mw3 <- induced_subgraph(mw, as.character(17:23)) mw4 <- induced_subgraph(mw, as.character(c(7, 8, 11, 14))) mw5 <- induced_subgraph(mw, as.character(1:7)) check.sep <- function(G) { sep <- min_separators(G) sapply(sep, is_min_separator, graph = G) } check.sep(mw) check.sep(mw1) check.sep(mw2) check.sep(mw3) check.sep(mw4) check.sep(mw5)
An igraph graph is named, if there is a symbolic name associated with its vertices.
is_named(graph)
is_named(graph)
graph |
The input graph. |
In igraph vertices can always be identified and specified via their numeric vertex ids. This is, however, not always convenient, and in many cases there exist symbolic ids that correspond to the vertices. To allow this more flexible identification of vertices, one can assign a vertex attribute called ‘name’ to an igraph graph. After doing this, the symbolic vertex names can be used in all igraph functions, instead of the numeric ids.
Note that the uniqueness of vertex names are currently not enforced in igraph, you have to check that for yourself, when assigning the vertex names.
A logical scalar.
Gabor Csardi [email protected]
g <- make_ring(10) is_named(g) V(g)$name <- letters[1:10] is_named(g) neighbors(g, "a")
g <- make_ring(10) is_named(g) V(g)$name <- letters[1:10] is_named(g) neighbors(g, "a")
Is this a printer callback?
is_printer_callback(x)
is_printer_callback(x)
x |
An R object. |
Other printer callbacks:
printer_callback()
is_separator()
determines whether the supplied vertex set is a vertex
separator:
A vertex set is a separator if there are vertices
and
in the graph such that all paths between
and
pass
through some vertices in
.
is_separator(graph, candidate)
is_separator(graph, candidate)
graph |
The input graph. It may be directed, but edge directions are ignored. |
candidate |
A numeric vector giving the vertex ids of the candidate separator. |
A logical scalar, whether the supplied vertex set is a (minimal) vertex separator or not. lists all vertex separator of minimum size.
Other flow:
dominator_tree()
,
edge_connectivity()
,
is_min_separator()
,
max_flow()
,
min_cut()
,
min_separators()
,
min_st_separators()
,
st_cuts()
,
st_min_cuts()
,
vertex_connectivity()
ring <- make_ring(4) min_st_separators(ring) is_separator(ring, 1) is_separator(ring, c(1, 3)) is_separator(ring, c(2, 4)) is_separator(ring, c(2, 3))
ring <- make_ring(4) min_st_separators(ring) is_separator(ring, 1) is_separator(ring, c(1, 3)) is_separator(ring, c(2, 4)) is_separator(ring, c(2, 3))
is_tree()
decides whether a graph is a tree, and optionally returns a
possible root vertex if the graph is a tree.
is_tree(graph, mode = c("out", "in", "all", "total"), details = FALSE)
is_tree(graph, mode = c("out", "in", "all", "total"), details = FALSE)
graph |
An igraph graph object |
mode |
Whether to consider edge directions in a directed graph. ‘all’ ignores edge directions; ‘out’ requires edges to be oriented outwards from the root, ‘in’ requires edges to be oriented towards the root. |
details |
Whether to return only whether the graph is a tree ( |
An undirected graph is a tree if it is connected and has no cycles. In the directed case, a possible additional requirement is that all edges are oriented away from a root (out-tree or arborescence) or all edges are oriented towards a root (in-tree or anti-arborescence). This test can be controlled using the mode parameter.
By convention, the null graph (i.e. the graph with no vertices) is considered not to be a tree.
When details
is FALSE
, a logical value that indicates
whether the graph is a tree. When details
is TRUE
, a named
list with two entries:
res |
Logical value that indicates whether the graph is a tree. |
root |
The root vertex of the tree; undefined if the graph is not a tree. |
Other trees:
is_forest()
,
make_from_prufer()
,
sample_spanning_tree()
,
to_prufer()
g <- make_tree(7, 2) is_tree(g) is_tree(g, details = TRUE)
g <- make_tree(7, 2) is_tree(g) is_tree(g, details = TRUE)
In weighted graphs, a real number is assigned to each (directed or undirected) edge.
is_weighted(graph)
is_weighted(graph)
graph |
The input graph. |
In igraph edge weights are represented via an edge attribute, called
‘weight’. The is_weighted()
function only checks that such an
attribute exists. (It does not even checks that it is a numeric edge
attribute.)
Edge weights are used for different purposes by the different functions. E.g. shortest path functions use it as the cost of the path; community finding methods use it as the strength of the relationship between two vertices, etc. Check the manual pages of the functions working with weighted graphs for details.
A logical scalar.
Gabor Csardi [email protected]
g <- make_ring(10) shortest_paths(g, 8, 2) E(g)$weight <- seq_len(ecount(g)) shortest_paths(g, 8, 2)
g <- make_ring(10) shortest_paths(g, 8, 2) E(g)$weight <- seq_len(ecount(g)) shortest_paths(g, 8, 2)
Decide if two graphs are isomorphic
isomorphic(graph1, graph2, method = c("auto", "direct", "vf2", "bliss"), ...) is_isomorphic_to( graph1, graph2, method = c("auto", "direct", "vf2", "bliss"), ... )
isomorphic(graph1, graph2, method = c("auto", "direct", "vf2", "bliss"), ...) is_isomorphic_to( graph1, graph2, method = c("auto", "direct", "vf2", "bliss"), ... )
graph1 |
The first graph. |
graph2 |
The second graph. |
method |
The method to use. Possible values: ‘auto’, ‘direct’, ‘vf2’, ‘bliss’. See their details below. |
... |
Additional arguments, passed to the various methods. |
Logical scalar, TRUE
if the graphs are isomorphic.
It tries to select the appropriate method based on the two graphs. This is the algorithm it uses:
If the two graphs do not agree on their order and size
(i.e. number of vertices and edges), then return FALSE
.
If the graphs have three or four vertices, then the ‘direct’ method is used.
If the graphs are directed, then the ‘vf2’ method is used.
Otherwise the ‘bliss’ method is used.
This method only works on graphs with three or four vertices, and it is based on a pre-calculated and stored table. It does not have any extra arguments.
This method uses the VF2 algorithm by Cordella, Foggia et al., see references below. It supports vertex and edge colors and have the following extra arguments:
Optional integer vectors giving the
colors of the vertices for colored graph isomorphism. If they
are not given, but the graph has a “color” vertex attribute,
then it will be used. If you want to ignore these attributes, then
supply NULL
for both of these arguments. See also examples
below.
Optional integer vectors giving the
colors of the edges for edge-colored (sub)graph isomorphism. If they
are not given, but the graph has a “color” edge attribute,
then it will be used. If you want to ignore these attributes, then
supply NULL
for both of these arguments.
Uses the BLISS algorithm by Junttila and Kaski, and it works for
undirected graphs. For both graphs the
canonical_permutation()
and then the permute()
function is called to transfer them into canonical form; finally the
canonical forms are compared.
Extra arguments:
Character constant, the heuristics to use in the BLISS
algorithm for graph1
and graph2
. See the sh
argument of
canonical_permutation()
for possible values.
sh
defaults to ‘fm’.
Tommi Junttila and Petteri Kaski: Engineering an Efficient Canonical Labeling Tool for Large and Sparse Graphs, Proceedings of the Ninth Workshop on Algorithm Engineering and Experiments and the Fourth Workshop on Analytic Algorithms and Combinatorics. 2007.
LP Cordella, P Foggia, C Sansone, and M Vento: An improved algorithm for matching large graphs, Proc. of the 3rd IAPR TC-15 Workshop on Graphbased Representations in Pattern Recognition, 149–159, 2001.
Other graph isomorphism:
canonical_permutation()
,
count_isomorphisms()
,
count_subgraph_isomorphisms()
,
graph_from_isomorphism_class()
,
isomorphism_class()
,
isomorphisms()
,
subgraph_isomorphic()
,
subgraph_isomorphisms()
# create some non-isomorphic graphs g1 <- graph_from_isomorphism_class(3, 10) g2 <- graph_from_isomorphism_class(3, 11) isomorphic(g1, g2) # create two isomorphic graphs, by permuting the vertices of the first g1 <- sample_pa(30, m = 2, directed = FALSE) g2 <- permute(g1, sample(vcount(g1))) # should be TRUE isomorphic(g1, g2) isomorphic(g1, g2, method = "bliss") isomorphic(g1, g2, method = "vf2") # colored graph isomorphism g1 <- make_ring(10) g2 <- make_ring(10) isomorphic(g1, g2) V(g1)$color <- rep(1:2, length = vcount(g1)) V(g2)$color <- rep(2:1, length = vcount(g2)) # consider colors by default count_isomorphisms(g1, g2) # ignore colors count_isomorphisms(g1, g2, vertex.color1 = NULL, vertex.color2 = NULL )
# create some non-isomorphic graphs g1 <- graph_from_isomorphism_class(3, 10) g2 <- graph_from_isomorphism_class(3, 11) isomorphic(g1, g2) # create two isomorphic graphs, by permuting the vertices of the first g1 <- sample_pa(30, m = 2, directed = FALSE) g2 <- permute(g1, sample(vcount(g1))) # should be TRUE isomorphic(g1, g2) isomorphic(g1, g2, method = "bliss") isomorphic(g1, g2, method = "vf2") # colored graph isomorphism g1 <- make_ring(10) g2 <- make_ring(10) isomorphic(g1, g2) V(g1)$color <- rep(1:2, length = vcount(g1)) V(g2)$color <- rep(2:1, length = vcount(g2)) # consider colors by default count_isomorphisms(g1, g2) # ignore colors count_isomorphisms(g1, g2, vertex.color1 = NULL, vertex.color2 = NULL )
The isomorphism class is a non-negative integer number. Graphs (with the same number of vertices) having the same isomorphism class are isomorphic and isomorphic graphs always have the same isomorphism class. Currently it can handle directed graphs with 3 or 4 vertices and undirected graphs with 3 to 6 vertices.
isomorphism_class(graph, v)
isomorphism_class(graph, v)
graph |
The input graph. |
v |
Optionally a vertex sequence. If not missing, then an induced subgraph of the input graph, consisting of this vertices, is used. |
An integer number.
Other graph isomorphism:
canonical_permutation()
,
count_isomorphisms()
,
count_subgraph_isomorphisms()
,
graph_from_isomorphism_class()
,
isomorphic()
,
isomorphisms()
,
subgraph_isomorphic()
,
subgraph_isomorphisms()
# create some non-isomorphic graphs g1 <- graph_from_isomorphism_class(3, 10) g2 <- graph_from_isomorphism_class(3, 11) isomorphism_class(g1) isomorphism_class(g2) isomorphic(g1, g2)
# create some non-isomorphic graphs g1 <- graph_from_isomorphism_class(3, 10) g2 <- graph_from_isomorphism_class(3, 11) isomorphism_class(g1) isomorphism_class(g2) isomorphic(g1, g2)
Calculate all isomorphic mappings between the vertices of two graphs
isomorphisms(graph1, graph2, method = "vf2", ...)
isomorphisms(graph1, graph2, method = "vf2", ...)
graph1 |
The first graph. |
graph2 |
The second graph. |
method |
Currently only ‘vf2’ is supported, see
|
... |
Extra arguments, passed to the various methods. |
A list of vertex sequences, corresponding to all mappings from the first graph to the second.
Other graph isomorphism:
canonical_permutation()
,
count_isomorphisms()
,
count_subgraph_isomorphisms()
,
graph_from_isomorphism_class()
,
isomorphic()
,
isomorphism_class()
,
subgraph_isomorphic()
,
subgraph_isomorphisms()
A vertex set is called independent if there no edges between any two vertices in it. These functions find independent vertex sets in undirected graphs
ivs(graph, min = NULL, max = NULL) largest_ivs(graph) max_ivs(graph) ivs_size(graph) independence_number(graph)
ivs(graph, min = NULL, max = NULL) largest_ivs(graph) max_ivs(graph) ivs_size(graph) independence_number(graph)
graph |
The input graph, directed graphs are considered as undirected, loop edges and multiple edges are ignored. |
min |
Numeric constant, limit for the minimum size of the independent
vertex sets to find. |
max |
Numeric constant, limit for the maximum size of the independent
vertex sets to find. |
ivs()
finds all independent vertex sets in the
network, obeying the size limitations given in the min
and max
arguments.
largest_ivs()
finds the largest independent vertex
sets in the graph. An independent vertex set is largest if there is no
independent vertex set with more vertices.
max_ivs()
finds the maximal independent vertex
sets in the graph. An independent vertex set is maximal if it cannot be
extended to a larger independent vertex set. The largest independent vertex
sets are maximal, but the opposite is not always true.
ivs_size()
calculate the size of the largest independent
vertex set(s).
independence_number()
is an alias for ivs_size()
.
These functions use the algorithm described by Tsukiyama et al., see reference below.
ivs()
,
largest_ivs()
and
max_ivs()
return a list containing numeric
vertex ids, each list element is an independent vertex set.
ivs_size()
returns an integer constant.
Tamas Nepusz [email protected] ported it from the Very Nauty Graph Library by Keith Briggs (http://keithbriggs.info/) and Gabor Csardi [email protected] wrote the R interface and this manual page.
S. Tsukiyama, M. Ide, H. Ariyoshi and I. Shirawaka. A new algorithm for generating all the maximal independent sets. SIAM J Computing, 6:505–517, 1977.
Other cliques:
cliques()
,
weighted_cliques()
# Do not run, takes a couple of seconds # A quite dense graph set.seed(42) g <- sample_gnp(100, 0.9) ivs_size(g) ivs(g, min = ivs_size(g)) largest_ivs(g) # Empty graph induced_subgraph(g, largest_ivs(g)[[1]]) length(max_ivs(g))
# Do not run, takes a couple of seconds # A quite dense graph set.seed(42) g <- sample_gnp(100, 0.9) ivs_size(g) ivs(g, min = ivs_size(g)) largest_ivs(g) # Empty graph induced_subgraph(g, largest_ivs(g)[[1]]) length(max_ivs(g))
shortest paths between two verticesFinds the shortest paths between the given source and target
vertex in order of increasing length. Currently this function uses
Yen's algorithm.
k_shortest_paths( graph, from, to, ..., k, weights = NULL, mode = c("out", "in", "all", "total") )
k_shortest_paths( graph, from, to, ..., k, weights = NULL, mode = c("out", "in", "all", "total") )
graph |
The input graph. |
from |
The source vertex of the shortest paths. |
to |
The target vertex of the shortest paths. |
... |
These dots are for future extensions and must be empty. |
k |
The number of paths to find. They will be returned in order of increasing length. |
weights |
Possibly a numeric vector giving edge weights. If this is
|
mode |
Character constant, gives whether the shortest paths to or from
the given vertices should be calculated for directed graphs. If |
A named list with two components is returned:
vpaths |
The list of |
epaths |
The list of |
igraph_get_k_shortest_paths()
.
Yen, Jin Y.: An algorithm for finding shortest routes from all source nodes to a given destination in general networks. Quarterly of Applied Mathematics. 27 (4): 526–530. (1970) doi:10.1090/qam/253822
shortest_paths()
, all_shortest_paths()
Other structural.properties:
bfs()
,
component_distribution()
,
connect()
,
constraint()
,
coreness()
,
degree()
,
dfs()
,
distance_table()
,
edge_density()
,
feedback_arc_set()
,
girth()
,
is_acyclic()
,
is_dag()
,
is_matching()
,
knn()
,
reciprocity()
,
subcomponent()
,
subgraph()
,
topo_sort()
,
transitivity()
,
unfold_tree()
,
which_multiple()
,
which_mutual()
This function can be used together with rewire()
to
randomly rewire the edges while preserving the original graph's degree
distribution.
keeping_degseq(loops = FALSE, niter = 100)
keeping_degseq(loops = FALSE, niter = 100)
loops |
Whether to allow destroying and creating loop edges. |
niter |
Number of rewiring trials to perform. |
The rewiring algorithm chooses two arbitrary edges in each step ((a,b) and (c,d)) and substitutes them with (a,d) and (c,b), if they not already exists in the graph. The algorithm does not create multiple edges.
Tamas Nepusz [email protected] and Gabor Csardi [email protected]
Other rewiring functions:
each_edge()
,
rewire()
g <- make_ring(10) g %>% rewire(keeping_degseq(niter = 20)) %>% degree() print_all(rewire(g, with = keeping_degseq(niter = vcount(g) * 10)))
g <- make_ring(10) g %>% rewire(keeping_degseq(niter = 20)) %>% degree() print_all(rewire(g, with = keeping_degseq(niter = vcount(g) * 10)))
Calculate the average nearest neighbor degree of the given vertices and the same quantity in the function of vertex degree
knn( graph, vids = V(graph), mode = c("all", "out", "in", "total"), neighbor.degree.mode = c("all", "out", "in", "total"), weights = NULL )
knn( graph, vids = V(graph), mode = c("all", "out", "in", "total"), neighbor.degree.mode = c("all", "out", "in", "total"), weights = NULL )
graph |
The input graph. It may be directed. |
vids |
The vertices for which the calculation is performed. Normally it
includes all vertices. Note, that if not all vertices are given here, then
both ‘ |
mode |
Character constant to indicate the type of neighbors to consider
in directed graphs. |
neighbor.degree.mode |
The type of degree to average in directed graphs.
|
weights |
Weight vector. If the graph has a |
Note that for zero degree vertices the answer in ‘knn
’ is
NaN
(zero divided by zero), the same is true for ‘knnk
’
if a given degree never appears in the network.
The weighted version computes a weighted average of the neighbor degrees as
where is the sum of the incident
edge weights of vertex
u
, i.e. its strength.
The sum runs over the neighbors v
of vertex u
as indicated by mode
. denotes the weighted adjacency matrix
and
is the neighbors' degree, specified by
neighbor_degree_mode
.
A list with two members:
knn |
A numeric vector giving the
average nearest neighbor degree for all vertices in |
knnk |
A numeric vector, its length is the maximum (total) vertex degree in the graph. The first element is the average nearest neighbor degree of vertices with degree one, etc. |
igraph_avg_nearest_neighbor_degree()
.
Gabor Csardi [email protected]
Alain Barrat, Marc Barthelemy, Romualdo Pastor-Satorras, Alessandro Vespignani: The architecture of complex weighted networks, Proc. Natl. Acad. Sci. USA 101, 3747 (2004)
Other structural.properties:
bfs()
,
component_distribution()
,
connect()
,
constraint()
,
coreness()
,
degree()
,
dfs()
,
distance_table()
,
edge_density()
,
feedback_arc_set()
,
girth()
,
is_acyclic()
,
is_dag()
,
is_matching()
,
k_shortest_paths()
,
reciprocity()
,
subcomponent()
,
subgraph()
,
topo_sort()
,
transitivity()
,
unfold_tree()
,
which_multiple()
,
which_mutual()
# Some trivial ones g <- make_ring(10) knn(g) g2 <- make_star(10) knn(g2) # A scale-free one, try to plot 'knnk' g3 <- sample_pa(1000, m = 5) knn(g3) # A random graph g4 <- sample_gnp(1000, p = 5 / 1000) knn(g4) # A weighted graph g5 <- make_star(10) E(g5)$weight <- seq(ecount(g5)) knn(g5)
# Some trivial ones g <- make_ring(10) knn(g) g2 <- make_star(10) knn(g2) # A scale-free one, try to plot 'knnk' g3 <- sample_pa(1000, m = 5) knn(g3) # A random graph g4 <- sample_gnp(1000, p = 5 / 1000) knn(g4) # A weighted graph g5 <- make_star(10) E(g5)$weight <- seq(ecount(g5)) knn(g5)
The Laplacian of a graph.
laplacian_matrix( graph, weights = NULL, sparse = igraph_opt("sparsematrices"), normalization = c("unnormalized", "symmetric", "left", "right"), normalized )
laplacian_matrix( graph, weights = NULL, sparse = igraph_opt("sparsematrices"), normalization = c("unnormalized", "symmetric", "left", "right"), normalized )
graph |
The input graph. |
weights |
An optional vector giving edge weights for weighted Laplacian
matrix. If this is |
sparse |
Logical scalar, whether to return the result as a sparse
matrix. The |
normalization |
The normalization method to use when calculating the Laplacian matrix. See the "Normalization methods" section on this page. |
normalized |
Deprecated, use |
The Laplacian Matrix of a graph is a symmetric matrix having the same number of rows and columns as the number of vertices in the graph and element (i,j) is d[i], the degree of vertex i if if i==j, -1 if i!=j and there is an edge between vertices i and j and 0 otherwise.
The Laplacian matrix can also be normalized, with several conventional normalization methods. See the "Normalization methods" section on this page.
The weighted version of the Laplacian simply works with the weighted degree instead of the plain degree. I.e. (i,j) is d[i], the weighted degree of vertex i if if i==j, -w if i!=j and there is an edge between vertices i and j with weight w, and 0 otherwise. The weighted degree of a vertex is the sum of the weights of its adjacent edges.
A numeric matrix.
The Laplacian matrix is defined in terms of the adjacency matrix
and a diagonal matrix
containing the degrees as follows:
"unnormalized": Unnormalized Laplacian, .
"symmetric": Symmetrically normalized Laplacian,
.
"left": Left-stochastic normalized Laplacian, .
"rigth": Right-stochastic normalized Laplacian, .
igraph_get_laplacian_sparse()
, igraph_get_laplacian()
.
Gabor Csardi [email protected]
g <- make_ring(10) laplacian_matrix(g) laplacian_matrix(g, normalization = "unnormalized") laplacian_matrix(g, normalization = "unnormalized", sparse = FALSE)
g <- make_ring(10) laplacian_matrix(g) laplacian_matrix(g, normalization = "unnormalized") laplacian_matrix(g, normalization = "unnormalized", sparse = FALSE)
This is a generic function to apply a layout function to a graph.
layout_(graph, layout, ...) ## S3 method for class 'igraph_layout_spec' print(x, ...) ## S3 method for class 'igraph_layout_modifier' print(x, ...)
layout_(graph, layout, ...) ## S3 method for class 'igraph_layout_spec' print(x, ...) ## S3 method for class 'igraph_layout_modifier' print(x, ...)
graph |
The input graph. |
layout |
The layout specification. It must be a call to a layout specification function. |
... |
Further modifiers, see a complete list below.
For the |
x |
The layout specification |
There are two ways to calculate graph layouts in igraph.
The first way is to call a layout function (they all have
prefix layout_()
on a graph, to get the vertex coordinates.
The second way (new in igraph 0.8.0), has two steps, and it
is more flexible. First you call a layout specification
function (the one without the layout_()
prefix, and
then layout_()
(or add_layout_()
) to
perform the layouting.
The second way is preferred, as it is more flexible. It allows
operations before and after the layouting. E.g. using the
component_wise()
argument, the layout can be calculated
separately for each component, and then merged to get the
final results.
The return value of the layout function, usually a two column matrix. For 3D layouts a three column matrix.
Modifiers modify how a layout calculation is performed. Currently implemented modifiers:
component_wise()
calculates the layout separately
for each component of the graph, and then merges
them.
normalize()
scales the layout to a square.
add_layout_()
to add the layout to the
graph as an attribute.
Other graph layouts:
add_layout_()
,
component_wise()
,
layout_as_bipartite()
,
layout_as_star()
,
layout_as_tree()
,
layout_in_circle()
,
layout_nicely()
,
layout_on_grid()
,
layout_on_sphere()
,
layout_randomly()
,
layout_with_dh()
,
layout_with_fr()
,
layout_with_gem()
,
layout_with_graphopt()
,
layout_with_kk()
,
layout_with_lgl()
,
layout_with_mds()
,
layout_with_sugiyama()
,
merge_coords()
,
norm_coords()
,
normalize()
g <- make_ring(10) + make_full_graph(5) coords <- layout_(g, as_star()) plot(g, layout = coords)
g <- make_ring(10) + make_full_graph(5) coords <- layout_(g, as_star()) plot(g, layout = coords)
Minimize edge-crossings in a simple two-row (or column) layout for bipartite graphs.
layout_as_bipartite(graph, types = NULL, hgap = 1, vgap = 1, maxiter = 100) as_bipartite(...)
layout_as_bipartite(graph, types = NULL, hgap = 1, vgap = 1, maxiter = 100) as_bipartite(...)
graph |
The bipartite input graph. It should have a logical
‘ |
types |
A logical vector, the vertex types. If this argument is
|
hgap |
Real scalar, the minimum horizontal gap between vertices in the same layer. |
vgap |
Real scalar, the distance between the two layers. |
maxiter |
Integer scalar, the maximum number of iterations in the crossing minimization stage. 100 is a reasonable default; if you feel that you have too many edge crossings, increase this. |
... |
Arguments to pass to |
The layout is created by first placing the vertices in two rows, according
to their types. Then the positions within the rows are optimized to minimize
edge crossings, using the Sugiyama algorithm (see
layout_with_sugiyama()
).
A matrix with two columns and as many rows as the number of vertices in the input graph.
Gabor Csardi [email protected]
Other graph layouts:
add_layout_()
,
component_wise()
,
layout_()
,
layout_as_star()
,
layout_as_tree()
,
layout_in_circle()
,
layout_nicely()
,
layout_on_grid()
,
layout_on_sphere()
,
layout_randomly()
,
layout_with_dh()
,
layout_with_fr()
,
layout_with_gem()
,
layout_with_graphopt()
,
layout_with_kk()
,
layout_with_lgl()
,
layout_with_mds()
,
layout_with_sugiyama()
,
merge_coords()
,
norm_coords()
,
normalize()
# Random bipartite graph inc <- matrix(sample(0:1, 50, replace = TRUE, prob = c(2, 1)), 10, 5) g <- graph_from_biadjacency_matrix(inc) plot(g, layout = layout_as_bipartite, vertex.color = c("green", "cyan")[V(g)$type + 1] ) # Two columns g %>% add_layout_(as_bipartite()) %>% plot()
# Random bipartite graph inc <- matrix(sample(0:1, 50, replace = TRUE, prob = c(2, 1)), 10, 5) g <- graph_from_biadjacency_matrix(inc) plot(g, layout = layout_as_bipartite, vertex.color = c("green", "cyan")[V(g)$type + 1] ) # Two columns g %>% add_layout_(as_bipartite()) %>% plot()
A simple layout generator, that places one vertex in the center of a circle and the rest of the vertices equidistantly on the perimeter.
layout_as_star(graph, center = V(graph)[1], order = NULL) as_star(...)
layout_as_star(graph, center = V(graph)[1], order = NULL) as_star(...)
graph |
The graph to layout. |
center |
The id of the vertex to put in the center. By default it is the first vertex. |
order |
Numeric vector, the order of the vertices along the perimeter. The default ordering is given by the vertex ids. |
... |
Arguments to pass to |
It is possible to choose the vertex that will be in the center, and the order of the vertices can be also given.
A matrix with two columns and as many rows as the number of vertices in the input graph.
Gabor Csardi [email protected]
layout()
and layout_with_drl()
for other layout
algorithms, plot.igraph()
and tkplot()
on how to
plot graphs and star()
on how to create ring graphs.
Other graph layouts:
add_layout_()
,
component_wise()
,
layout_()
,
layout_as_bipartite()
,
layout_as_tree()
,
layout_in_circle()
,
layout_nicely()
,
layout_on_grid()
,
layout_on_sphere()
,
layout_randomly()
,
layout_with_dh()
,
layout_with_fr()
,
layout_with_gem()
,
layout_with_graphopt()
,
layout_with_kk()
,
layout_with_lgl()
,
layout_with_mds()
,
layout_with_sugiyama()
,
merge_coords()
,
norm_coords()
,
normalize()
g <- make_star(10) layout_as_star(g) ## Alternative form layout_(g, as_star())
g <- make_star(10) layout_as_star(g) ## Alternative form layout_(g, as_star())
A tree-like layout, it is perfect for trees, acceptable for graphs with not too many cycles.
layout_as_tree( graph, root = numeric(), circular = FALSE, rootlevel = numeric(), mode = c("out", "in", "all"), flip.y = TRUE ) as_tree(...)
layout_as_tree( graph, root = numeric(), circular = FALSE, rootlevel = numeric(), mode = c("out", "in", "all"), flip.y = TRUE ) as_tree(...)
graph |
The input graph. |
root |
The index of the root vertex or root vertices. If this is a
non-empty vector then the supplied vertex ids are used as the roots of the
trees (or a single tree if the graph is connected). If it is an empty
vector, then the root vertices are automatically calculated based on
topological sorting, performed with the opposite mode than the |
circular |
Logical scalar, whether to plot the tree in a circular
fashion. Defaults to |
rootlevel |
This argument can be useful when drawing forests which are
not trees (i.e. they are unconnected and have tree components). It specifies
the level of the root vertices for every tree in the forest. It is only
considered if the |
mode |
Specifies which edges to consider when building the tree. If it
is ‘out’, then only the outgoing, if it is ‘in’, then only the
incoming edges of a parent are considered. If it is ‘all’ then all
edges are used (this was the behavior in igraph 0.5 and before). This
parameter also influences how the root vertices are calculated, if they are
not given. See the |
flip.y |
Logical scalar, whether to flip the ‘y’ coordinates. The default is flipping because that puts the root vertex on the top. |
... |
Passed to |
Arranges the nodes in a tree where the given node is used as the root. The tree is directed downwards and the parents are centered above its children. For the exact algorithm, the reference below.
If the given graph is not a tree, a breadth-first search is executed first to obtain a possible spanning tree.
A numeric matrix with two columns, and one row for each vertex.
Tamas Nepusz [email protected] and Gabor Csardi [email protected]
Reingold, E and Tilford, J (1981). Tidier drawing of trees. IEEE Trans. on Softw. Eng., SE-7(2):223–228.
Other graph layouts:
add_layout_()
,
component_wise()
,
layout_()
,
layout_as_bipartite()
,
layout_as_star()
,
layout_in_circle()
,
layout_nicely()
,
layout_on_grid()
,
layout_on_sphere()
,
layout_randomly()
,
layout_with_dh()
,
layout_with_fr()
,
layout_with_gem()
,
layout_with_graphopt()
,
layout_with_kk()
,
layout_with_lgl()
,
layout_with_mds()
,
layout_with_sugiyama()
,
merge_coords()
,
norm_coords()
,
normalize()
tree <- make_tree(20, 3) plot(tree, layout = layout_as_tree) plot(tree, layout = layout_as_tree(tree, flip.y = FALSE)) plot(tree, layout = layout_as_tree(tree, circular = TRUE)) tree2 <- make_tree(10, 3) + make_tree(10, 2) plot(tree2, layout = layout_as_tree) plot(tree2, layout = layout_as_tree(tree2, root = c(1, 11), rootlevel = c(2, 1) ))
tree <- make_tree(20, 3) plot(tree, layout = layout_as_tree) plot(tree, layout = layout_as_tree(tree, flip.y = FALSE)) plot(tree, layout = layout_as_tree(tree, circular = TRUE)) tree2 <- make_tree(10, 3) + make_tree(10, 2) plot(tree2, layout = layout_as_tree) plot(tree2, layout = layout_as_tree(tree2, root = c(1, 11), rootlevel = c(2, 1) ))
Place vertices on a circle, in the order of their vertex ids.
layout_in_circle(graph, order = V(graph)) in_circle(...)
layout_in_circle(graph, order = V(graph)) in_circle(...)
graph |
The input graph. |
order |
The vertices to place on the circle, in the order of their desired placement. Vertices that are not included here will be placed at (0,0). |
... |
Passed to |
If you want to order the vertices differently, then permute them using the
permute()
function.
A numeric matrix with two columns, and one row for each vertex.
Gabor Csardi [email protected]
Other graph layouts:
add_layout_()
,
component_wise()
,
layout_()
,
layout_as_bipartite()
,
layout_as_star()
,
layout_as_tree()
,
layout_nicely()
,
layout_on_grid()
,
layout_on_sphere()
,
layout_randomly()
,
layout_with_dh()
,
layout_with_fr()
,
layout_with_gem()
,
layout_with_graphopt()
,
layout_with_kk()
,
layout_with_lgl()
,
layout_with_mds()
,
layout_with_sugiyama()
,
merge_coords()
,
norm_coords()
,
normalize()
## Place vertices on a circle, order them according to their ## community library(igraphdata) data(karate) karate_groups <- cluster_optimal(karate) coords <- layout_in_circle(karate, order = order(membership(karate_groups)) ) V(karate)$label <- sub("Actor ", "", V(karate)$name) V(karate)$label.color <- membership(karate_groups) V(karate)$shape <- "none" plot(karate, layout = coords)
## Place vertices on a circle, order them according to their ## community library(igraphdata) data(karate) karate_groups <- cluster_optimal(karate) coords <- layout_in_circle(karate, order = order(membership(karate_groups)) ) V(karate)$label <- sub("Actor ", "", V(karate)$name) V(karate)$label.color <- membership(karate_groups) V(karate)$shape <- "none" plot(karate, layout = coords)
This function tries to choose an appropriate graph layout algorithm for the graph, automatically, based on a simple algorithm. See details below.
layout_nicely(graph, dim = 2, ...) nicely(...)
layout_nicely(graph, dim = 2, ...) nicely(...)
graph |
The input graph |
dim |
Dimensions, should be 2 or 3. |
... |
For |
layout_nicely()
tries to choose an appropriate layout function for the
supplied graph, and uses that to generate the layout. The current
implementation works like this:
If the graph has a graph attribute called ‘layout’, then this is used. If this attribute is an R function, then it is called, with the graph and any other extra arguments.
Otherwise, if the graph has vertex attributes called ‘x’ and ‘y’, then these are used as coordinates. If the graph has an additional ‘z’ vertex attribute, that is also used.
Otherwise,
if the graph is connected and has less than 1000 vertices, the
Fruchterman-Reingold layout is used, by calling layout_with_fr()
.
Otherwise the DrL layout is used, layout_with_drl()
is called.
In layout algorithm implementations, an argument named ‘weights’ is
typically used to specify the weights of the edges if the layout algorithm
supports them. In this case, omitting ‘weights’ or setting it to
NULL
will make igraph use the 'weight' edge attribute from the graph
if it is present. However, most layout algorithms do not support non-positive
weights, so layout_nicely()
would fail if you simply called it on
your graph without specifying explicit weights and the weights happened to
include non-positive numbers. We strive to ensure that layout_nicely()
works out-of-the-box for most graphs, so the rule is that if you omit
‘weights’ or set it to NULL
and layout_nicely()
would
end up calling layout_with_fr()
or layout_with_drl()
, we do not
forward the weights to these functions and issue a warning about this. You
can use weights = NA
to silence the warning.
A numeric matrix with two or three columns.
Gabor Csardi [email protected]
Other graph layouts:
add_layout_()
,
component_wise()
,
layout_()
,
layout_as_bipartite()
,
layout_as_star()
,
layout_as_tree()
,
layout_in_circle()
,
layout_on_grid()
,
layout_on_sphere()
,
layout_randomly()
,
layout_with_dh()
,
layout_with_fr()
,
layout_with_gem()
,
layout_with_graphopt()
,
layout_with_kk()
,
layout_with_lgl()
,
layout_with_mds()
,
layout_with_sugiyama()
,
merge_coords()
,
norm_coords()
,
normalize()
This layout places vertices on a rectangular grid, in two or three dimensions.
layout_on_grid(graph, width = 0, height = 0, dim = 2) on_grid(...)
layout_on_grid(graph, width = 0, height = 0, dim = 2) on_grid(...)
graph |
The input graph. |
width |
The number of vertices in a single row of the grid. If this is zero or negative, then for 2d layouts the width of the grid will be the square root of the number of vertices in the graph, rounded up to the next integer. Similarly, it will be the cube root for 3d layouts. |
height |
The number of vertices in a single column of the grid, for three dimensional layouts. If this is zero or negative, then it is determinted automatically. |
dim |
Two or three. Whether to make 2d or a 3d layout. |
... |
Passed to |
The function places the vertices on a simple rectangular grid, one after the
other. If you want to change the order of the vertices, then see the
permute()
function.
A two-column or three-column matrix.
Tamas Nepusz [email protected]
layout()
for other layout generators
Other graph layouts:
add_layout_()
,
component_wise()
,
layout_()
,
layout_as_bipartite()
,
layout_as_star()
,
layout_as_tree()
,
layout_in_circle()
,
layout_nicely()
,
layout_on_sphere()
,
layout_randomly()
,
layout_with_dh()
,
layout_with_fr()
,
layout_with_gem()
,
layout_with_graphopt()
,
layout_with_kk()
,
layout_with_lgl()
,
layout_with_mds()
,
layout_with_sugiyama()
,
merge_coords()
,
norm_coords()
,
normalize()
g <- make_lattice(c(3, 3)) layout_on_grid(g) g2 <- make_lattice(c(3, 3, 3)) layout_on_grid(g2, dim = 3) plot(g, layout = layout_on_grid) if (interactive() && requireNamespace("rgl", quietly = TRUE)) { rglplot(g, layout = layout_on_grid(g, dim = 3)) }
g <- make_lattice(c(3, 3)) layout_on_grid(g) g2 <- make_lattice(c(3, 3, 3)) layout_on_grid(g2, dim = 3) plot(g, layout = layout_on_grid) if (interactive() && requireNamespace("rgl", quietly = TRUE)) { rglplot(g, layout = layout_on_grid(g, dim = 3)) }
Place vertices on a sphere, approximately uniformly, in the order of their vertex ids.
layout_on_sphere(graph) on_sphere(...)
layout_on_sphere(graph) on_sphere(...)
graph |
The input graph. |
... |
Passed to |
layout_on_sphere()
places the vertices (approximately) uniformly on the
surface of a sphere, this is thus a 3d layout. It is not clear however what
“uniformly on a sphere” means.
If you want to order the vertices differently, then permute them using the
permute()
function.
A numeric matrix with three columns, and one row for each vertex.
Gabor Csardi [email protected]
Other graph layouts:
add_layout_()
,
component_wise()
,
layout_()
,
layout_as_bipartite()
,
layout_as_star()
,
layout_as_tree()
,
layout_in_circle()
,
layout_nicely()
,
layout_on_grid()
,
layout_randomly()
,
layout_with_dh()
,
layout_with_fr()
,
layout_with_gem()
,
layout_with_graphopt()
,
layout_with_kk()
,
layout_with_lgl()
,
layout_with_mds()
,
layout_with_sugiyama()
,
merge_coords()
,
norm_coords()
,
normalize()
This function uniformly randomly places the vertices of the graph in two or three dimensions.
layout_randomly(graph, dim = 2) randomly(...)
layout_randomly(graph, dim = 2) randomly(...)
graph |
The input graph. |
dim |
Integer scalar, the dimension of the space to use. It must be 2 or 3. |
... |
Parameters to pass to |
Randomly places vertices on a [-1,1] square (in 2d) or in a cube (in 3d). It is probably a useless layout, but it can use as a starting point for other layout generators.
A numeric matrix with two or three columns.
Gabor Csardi [email protected]
Other graph layouts:
add_layout_()
,
component_wise()
,
layout_()
,
layout_as_bipartite()
,
layout_as_star()
,
layout_as_tree()
,
layout_in_circle()
,
layout_nicely()
,
layout_on_grid()
,
layout_on_sphere()
,
layout_with_dh()
,
layout_with_fr()
,
layout_with_gem()
,
layout_with_graphopt()
,
layout_with_kk()
,
layout_with_lgl()
,
layout_with_mds()
,
layout_with_sugiyama()
,
merge_coords()
,
norm_coords()
,
normalize()
Place vertices of a graph on the plane, according to the simulated annealing algorithm by Davidson and Harel.
layout_with_dh( graph, coords = NULL, maxiter = 10, fineiter = max(10, log2(vcount(graph))), cool.fact = 0.75, weight.node.dist = 1, weight.border = 0, weight.edge.lengths = edge_density(graph)/10, weight.edge.crossings = 1 - sqrt(edge_density(graph)), weight.node.edge.dist = 0.2 * (1 - edge_density(graph)) ) with_dh(...)
layout_with_dh( graph, coords = NULL, maxiter = 10, fineiter = max(10, log2(vcount(graph))), cool.fact = 0.75, weight.node.dist = 1, weight.border = 0, weight.edge.lengths = edge_density(graph)/10, weight.edge.crossings = 1 - sqrt(edge_density(graph)), weight.node.edge.dist = 0.2 * (1 - edge_density(graph)) ) with_dh(...)
graph |
The graph to lay out. Edge directions are ignored. |
coords |
Optional starting positions for the vertices. If this argument
is not |
maxiter |
Number of iterations to perform in the first phase. |
fineiter |
Number of iterations in the fine tuning phase. |
cool.fact |
Cooling factor. |
weight.node.dist |
Weight for the node-node distances component of the energy function. |
weight.border |
Weight for the distance from the border component of the energy function. It can be set to zero, if vertices are allowed to sit on the border. |
weight.edge.lengths |
Weight for the edge length component of the energy function. |
weight.edge.crossings |
Weight for the edge crossing component of the energy function. |
weight.node.edge.dist |
Weight for the node-edge distance component of the energy function. |
... |
Passed to |
This function implements the algorithm by Davidson and Harel, see Ron Davidson, David Harel: Drawing Graphs Nicely Using Simulated Annealing. ACM Transactions on Graphics 15(4), pp. 301-331, 1996.
The algorithm uses simulated annealing and a sophisticated energy function, which is unfortunately hard to parameterize for different graphs. The original publication did not disclose any parameter values, and the ones below were determined by experimentation.
The algorithm consists of two phases, an annealing phase, and a fine-tuning phase. There is no simulated annealing in the second phase.
Our implementation tries to follow the original publication, as much as possible. The only major difference is that coordinates are explicitly kept within the bounds of the rectangle of the layout.
A two- or three-column matrix, each row giving the coordinates of a vertex, according to the ids of the vertex ids.
Gabor Csardi [email protected]
Ron Davidson, David Harel: Drawing Graphs Nicely Using Simulated Annealing. ACM Transactions on Graphics 15(4), pp. 301-331, 1996.
layout_with_fr()
,
layout_with_kk()
for other layout algorithms.
Other graph layouts:
add_layout_()
,
component_wise()
,
layout_()
,
layout_as_bipartite()
,
layout_as_star()
,
layout_as_tree()
,
layout_in_circle()
,
layout_nicely()
,
layout_on_grid()
,
layout_on_sphere()
,
layout_randomly()
,
layout_with_fr()
,
layout_with_gem()
,
layout_with_graphopt()
,
layout_with_kk()
,
layout_with_lgl()
,
layout_with_mds()
,
layout_with_sugiyama()
,
merge_coords()
,
norm_coords()
,
normalize()
set.seed(42) ## Figures from the paper g_1b <- make_star(19, mode = "undirected") + path(c(2:19, 2)) + path(c(seq(2, 18, by = 2), 2)) plot(g_1b, layout = layout_with_dh) g_2 <- make_lattice(c(8, 3)) + edges(1, 8, 9, 16, 17, 24) plot(g_2, layout = layout_with_dh) g_3 <- make_empty_graph(n = 70) plot(g_3, layout = layout_with_dh) g_4 <- make_empty_graph(n = 70, directed = FALSE) + edges(1:70) plot(g_4, layout = layout_with_dh, vertex.size = 5, vertex.label = NA) g_5a <- make_ring(24) plot(g_5a, layout = layout_with_dh, vertex.size = 5, vertex.label = NA) g_5b <- make_ring(40) plot(g_5b, layout = layout_with_dh, vertex.size = 5, vertex.label = NA) g_6 <- make_lattice(c(2, 2, 2)) plot(g_6, layout = layout_with_dh) g_7 <- graph_from_literal(1:3:5 -- 2:4:6) plot(g_7, layout = layout_with_dh, vertex.label = V(g_7)$name) g_8 <- make_ring(5) + make_ring(10) + make_ring(5) + edges( 1, 6, 2, 8, 3, 10, 4, 12, 5, 14, 7, 16, 9, 17, 11, 18, 13, 19, 15, 20 ) plot(g_8, layout = layout_with_dh, vertex.size = 5, vertex.label = NA) g_9 <- make_lattice(c(3, 2, 2)) plot(g_9, layout = layout_with_dh, vertex.size = 5, vertex.label = NA) g_10 <- make_lattice(c(6, 6)) plot(g_10, layout = layout_with_dh, vertex.size = 5, vertex.label = NA) g_11a <- make_tree(31, 2, mode = "undirected") plot(g_11a, layout = layout_with_dh, vertex.size = 5, vertex.label = NA) g_11b <- make_tree(21, 4, mode = "undirected") plot(g_11b, layout = layout_with_dh, vertex.size = 5, vertex.label = NA) g_12 <- make_empty_graph(n = 37, directed = FALSE) + path(1:5, 10, 22, 31, 37:33, 27, 16, 6, 1) + path(6, 7, 11, 9, 10) + path(16:22) + path(27:31) + path(2, 7, 18, 28, 34) + path(3, 8, 11, 19, 29, 32, 35) + path(4, 9, 20, 30, 36) + path(1, 7, 12, 14, 19, 24, 26, 30, 37) + path(5, 9, 13, 15, 19, 23, 25, 28, 33) + path(3, 12, 16, 25, 35, 26, 22, 13, 3) plot(g_12, layout = layout_with_dh, vertex.size = 5, vertex.label = NA)
set.seed(42) ## Figures from the paper g_1b <- make_star(19, mode = "undirected") + path(c(2:19, 2)) + path(c(seq(2, 18, by = 2), 2)) plot(g_1b, layout = layout_with_dh) g_2 <- make_lattice(c(8, 3)) + edges(1, 8, 9, 16, 17, 24) plot(g_2, layout = layout_with_dh) g_3 <- make_empty_graph(n = 70) plot(g_3, layout = layout_with_dh) g_4 <- make_empty_graph(n = 70, directed = FALSE) + edges(1:70) plot(g_4, layout = layout_with_dh, vertex.size = 5, vertex.label = NA) g_5a <- make_ring(24) plot(g_5a, layout = layout_with_dh, vertex.size = 5, vertex.label = NA) g_5b <- make_ring(40) plot(g_5b, layout = layout_with_dh, vertex.size = 5, vertex.label = NA) g_6 <- make_lattice(c(2, 2, 2)) plot(g_6, layout = layout_with_dh) g_7 <- graph_from_literal(1:3:5 -- 2:4:6) plot(g_7, layout = layout_with_dh, vertex.label = V(g_7)$name) g_8 <- make_ring(5) + make_ring(10) + make_ring(5) + edges( 1, 6, 2, 8, 3, 10, 4, 12, 5, 14, 7, 16, 9, 17, 11, 18, 13, 19, 15, 20 ) plot(g_8, layout = layout_with_dh, vertex.size = 5, vertex.label = NA) g_9 <- make_lattice(c(3, 2, 2)) plot(g_9, layout = layout_with_dh, vertex.size = 5, vertex.label = NA) g_10 <- make_lattice(c(6, 6)) plot(g_10, layout = layout_with_dh, vertex.size = 5, vertex.label = NA) g_11a <- make_tree(31, 2, mode = "undirected") plot(g_11a, layout = layout_with_dh, vertex.size = 5, vertex.label = NA) g_11b <- make_tree(21, 4, mode = "undirected") plot(g_11b, layout = layout_with_dh, vertex.size = 5, vertex.label = NA) g_12 <- make_empty_graph(n = 37, directed = FALSE) + path(1:5, 10, 22, 31, 37:33, 27, 16, 6, 1) + path(6, 7, 11, 9, 10) + path(16:22) + path(27:31) + path(2, 7, 18, 28, 34) + path(3, 8, 11, 19, 29, 32, 35) + path(4, 9, 20, 30, 36) + path(1, 7, 12, 14, 19, 24, 26, 30, 37) + path(5, 9, 13, 15, 19, 23, 25, 28, 33) + path(3, 12, 16, 25, 35, 26, 22, 13, 3) plot(g_12, layout = layout_with_dh, vertex.size = 5, vertex.label = NA)
DrL is a force-directed graph layout toolbox focused on real-world large-scale graphs, developed by Shawn Martin and colleagues at Sandia National Laboratories.
layout_with_drl( graph, use.seed = FALSE, seed = matrix(runif(vcount(graph) * 2), ncol = 2), options = drl_defaults$default, weights = NULL, dim = 2 ) with_drl(...)
layout_with_drl( graph, use.seed = FALSE, seed = matrix(runif(vcount(graph) * 2), ncol = 2), options = drl_defaults$default, weights = NULL, dim = 2 ) with_drl(...)
graph |
The input graph, in can be directed or undirected. |
use.seed |
Logical scalar, whether to use the coordinates given in the
|
seed |
A matrix with two columns, the starting coordinates for the
vertices is |
options |
Options for the layout generator, a named list. See details below. |
weights |
The weights of the edges. It must be a positive numeric vector,
|
dim |
Either ‘2’ or ‘3’, it specifies whether we want a two dimensional or a three dimensional layout. Note that because of the nature of the DrL algorithm, the three dimensional layout takes significantly longer to compute. |
... |
Passed to |
This function implements the force-directed DrL layout generator.
The generator has the following parameters:
Edge cutting is done in the late stages of the algorithm in order to achieve less dense layouts. Edges are cut if there is a lot of stress on them (a large value in the objective function sum). The edge cutting parameter is a value between 0 and 1 with 0 representing no edge cutting and 1 representing maximal edge cutting.
Number of iterations in the first phase.
Start temperature, first phase.
Attraction, first phase.
Damping, first phase.
Number of iterations, liquid phase.
Start temperature, liquid phase.
Attraction, liquid phase.
Damping, liquid phase.
Number of iterations, expansion phase.
Start temperature, expansion phase.
Attraction, expansion phase.
Damping, expansion phase.
Number of iterations, cooldown phase.
Start temperature, cooldown phase.
Attraction, cooldown phase.
Damping, cooldown phase.
Number of iterations, crunch phase.
Start temperature, crunch phase.
Attraction, crunch phase.
Damping, crunch phase.
Number of iterations, simmer phase.
Start temperature, simmer phase.
Attraction, simmer phase.
Damping, simmer phase.
There are five pre-defined parameter settings as well, these are called
drl_defaults$default
, drl_defaults$coarsen
,
drl_defaults$coarsest
, drl_defaults$refine
and
drl_defaults$final
.
A numeric matrix with two columns.
Shawn Martin (http://www.cs.otago.ac.nz/homepages/smartin/) and Gabor Csardi [email protected] for the R/igraph interface and the three dimensional version.
See the following technical report: Martin, S., Brown, W.M., Klavans, R., Boyack, K.W., DrL: Distributed Recursive (Graph) Layout. SAND Reports, 2008. 2936: p. 1-10.
layout()
for other layout generators.
g <- as_undirected(sample_pa(100, m = 1)) l <- layout_with_drl(g, options = list(simmer.attraction = 0)) plot(g, layout = l, vertex.size = 3, vertex.label = NA)
g <- as_undirected(sample_pa(100, m = 1)) l <- layout_with_drl(g, options = list(simmer.attraction = 0)) plot(g, layout = l, vertex.size = 3, vertex.label = NA)
Place vertices on the plane using the force-directed layout algorithm by Fruchterman and Reingold.
layout_with_fr( graph, coords = NULL, dim = 2, niter = 500, start.temp = sqrt(vcount(graph)), grid = c("auto", "grid", "nogrid"), weights = NULL, minx = NULL, maxx = NULL, miny = NULL, maxy = NULL, minz = NULL, maxz = NULL, coolexp = deprecated(), maxdelta = deprecated(), area = deprecated(), repulserad = deprecated(), maxiter = deprecated() ) with_fr(...)
layout_with_fr( graph, coords = NULL, dim = 2, niter = 500, start.temp = sqrt(vcount(graph)), grid = c("auto", "grid", "nogrid"), weights = NULL, minx = NULL, maxx = NULL, miny = NULL, maxy = NULL, minz = NULL, maxz = NULL, coolexp = deprecated(), maxdelta = deprecated(), area = deprecated(), repulserad = deprecated(), maxiter = deprecated() ) with_fr(...)
See the referenced paper below for the details of the algorithm.
This function was rewritten from scratch in igraph version 0.8.0.
A two- or three-column matrix, each row giving the coordinates of a vertex, according to the ids of the vertex ids.
Gabor Csardi [email protected]
Fruchterman, T.M.J. and Reingold, E.M. (1991). Graph Drawing by Force-directed Placement. Software - Practice and Experience, 21(11):1129-1164.
layout_with_drl()
, layout_with_kk()
for
other layout algorithms.
Other graph layouts:
add_layout_()
,
component_wise()
,
layout_()
,
layout_as_bipartite()
,
layout_as_star()
,
layout_as_tree()
,
layout_in_circle()
,
layout_nicely()
,
layout_on_grid()
,
layout_on_sphere()
,
layout_randomly()
,
layout_with_dh()
,
layout_with_gem()
,
layout_with_graphopt()
,
layout_with_kk()
,
layout_with_lgl()
,
layout_with_mds()
,
layout_with_sugiyama()
,
merge_coords()
,
norm_coords()
,
normalize()
# Fixing ego g <- sample_pa(20, m = 2) minC <- rep(-Inf, vcount(g)) maxC <- rep(Inf, vcount(g)) minC[1] <- maxC[1] <- 0 co <- layout_with_fr(g, minx = minC, maxx = maxC, miny = minC, maxy = maxC ) co[1, ] plot(g, layout = co, vertex.size = 30, edge.arrow.size = 0.2, vertex.label = c("ego", rep("", vcount(g) - 1)), rescale = FALSE, xlim = range(co[, 1]), ylim = range(co[, 2]), vertex.label.dist = 0, vertex.label.color = "red" ) axis(1) axis(2)
# Fixing ego g <- sample_pa(20, m = 2) minC <- rep(-Inf, vcount(g)) maxC <- rep(Inf, vcount(g)) minC[1] <- maxC[1] <- 0 co <- layout_with_fr(g, minx = minC, maxx = maxC, miny = minC, maxy = maxC ) co[1, ] plot(g, layout = co, vertex.size = 30, edge.arrow.size = 0.2, vertex.label = c("ego", rep("", vcount(g) - 1)), rescale = FALSE, xlim = range(co[, 1]), ylim = range(co[, 2]), vertex.label.dist = 0, vertex.label.color = "red" ) axis(1) axis(2)
Place vertices on the plane using the GEM force-directed layout algorithm.
layout_with_gem( graph, coords = NULL, maxiter = 40 * vcount(graph)^2, temp.max = max(vcount(graph), 1), temp.min = 1/10, temp.init = sqrt(max(vcount(graph), 1)) ) with_gem(...)
layout_with_gem( graph, coords = NULL, maxiter = 40 * vcount(graph)^2, temp.max = max(vcount(graph), 1), temp.min = 1/10, temp.init = sqrt(max(vcount(graph), 1)) ) with_gem(...)
graph |
The input graph. Edge directions are ignored. |
coords |
If not |
maxiter |
The maximum number of iterations to perform. Updating a single vertex counts as an iteration. A reasonable default is 40 * n * n, where n is the number of vertices. The original paper suggests 4 * n * n, but this usually only works if the other parameters are set up carefully. |
temp.max |
The maximum allowed local temperature. A reasonable default is the number of vertices. |
temp.min |
The global temperature at which the algorithm terminates
(even before reaching |
temp.init |
Initial local temperature of all vertices. A reasonable default is the square root of the number of vertices. |
... |
Passed to |
See the referenced paper below for the details of the algorithm.
A numeric matrix with two columns, and as many rows as the number of vertices.
Gabor Csardi [email protected]
Arne Frick, Andreas Ludwig, Heiko Mehldau: A Fast Adaptive Layout Algorithm for Undirected Graphs, Proc. Graph Drawing 1994, LNCS 894, pp. 388-403, 1995.
layout_with_fr()
,
plot.igraph()
, tkplot()
Other graph layouts:
add_layout_()
,
component_wise()
,
layout_()
,
layout_as_bipartite()
,
layout_as_star()
,
layout_as_tree()
,
layout_in_circle()
,
layout_nicely()
,
layout_on_grid()
,
layout_on_sphere()
,
layout_randomly()
,
layout_with_dh()
,
layout_with_fr()
,
layout_with_graphopt()
,
layout_with_kk()
,
layout_with_lgl()
,
layout_with_mds()
,
layout_with_sugiyama()
,
merge_coords()
,
norm_coords()
,
normalize()
set.seed(42) g <- make_ring(10) plot(g, layout = layout_with_gem)
set.seed(42) g <- make_ring(10) plot(g, layout = layout_with_gem)
A force-directed layout algorithm, that scales relatively well to large graphs.
layout_with_graphopt( graph, start = NULL, niter = 500, charge = 0.001, mass = 30, spring.length = 0, spring.constant = 1, max.sa.movement = 5 ) with_graphopt(...)
layout_with_graphopt( graph, start = NULL, niter = 500, charge = 0.001, mass = 30, spring.length = 0, spring.constant = 1, max.sa.movement = 5 ) with_graphopt(...)
graph |
The input graph. |
start |
If given, then it should be a matrix with two columns and one line for each vertex. This matrix will be used as starting positions for the algorithm. If not given, then a random starting matrix is used. |
niter |
Integer scalar, the number of iterations to perform. Should be
a couple of hundred in general. If you have a large graph then you might
want to only do a few iterations and then check the result. If it is not
good enough you can feed it in again in the |
charge |
The charge of the vertices, used to calculate electric repulsion. The default is 0.001. |
mass |
The mass of the vertices, used for the spring forces. The default is 30. |
spring.length |
The length of the springs, an integer number. The default value is zero. |
spring.constant |
The spring constant, the default value is one. |
max.sa.movement |
Real constant, it gives the maximum amount of movement allowed in a single step along a single axis. The default value is 5. |
... |
Passed to |
layout_with_graphopt()
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 (might be added later) and a code was a bit reorganized
to avoid some unnecessary steps is the node charge (see below) is zero.
graphopt uses physical analogies for defining attracting and repelling forces among the vertices and then the physical system is simulated until it reaches an equilibrium. (There is no simulated annealing or anything like that, so a stable fixed point is not guaranteed.)
A numeric matrix with two columns, and a row for each vertex.
Michael Schmuhl for the original graphopt code, rewritten and wrapped by Gabor Csardi [email protected].
Other graph layouts:
add_layout_()
,
component_wise()
,
layout_()
,
layout_as_bipartite()
,
layout_as_star()
,
layout_as_tree()
,
layout_in_circle()
,
layout_nicely()
,
layout_on_grid()
,
layout_on_sphere()
,
layout_randomly()
,
layout_with_dh()
,
layout_with_fr()
,
layout_with_gem()
,
layout_with_kk()
,
layout_with_lgl()
,
layout_with_mds()
,
layout_with_sugiyama()
,
merge_coords()
,
norm_coords()
,
normalize()
Place the vertices on the plane, or in 3D space, based on a physical model of springs.
layout_with_kk( graph, coords = NULL, dim = 2, maxiter = 50 * vcount(graph), epsilon = 0, kkconst = max(vcount(graph), 1), weights = NULL, minx = NULL, maxx = NULL, miny = NULL, maxy = NULL, minz = NULL, maxz = NULL, niter = deprecated(), sigma = deprecated(), initemp = deprecated(), coolexp = deprecated(), start = deprecated() ) with_kk(...)
layout_with_kk( graph, coords = NULL, dim = 2, maxiter = 50 * vcount(graph), epsilon = 0, kkconst = max(vcount(graph), 1), weights = NULL, minx = NULL, maxx = NULL, miny = NULL, maxy = NULL, minz = NULL, maxz = NULL, niter = deprecated(), sigma = deprecated(), initemp = deprecated(), coolexp = deprecated(), start = deprecated() ) with_kk(...)
graph |
The input graph. Edge directions are ignored. |
coords |
If not |
dim |
Integer scalar, 2 or 3, the dimension of the layout. Two dimensional layouts are places on a plane, three dimensional ones in the 3d space. |
maxiter |
The maximum number of iterations to perform. The algorithm
might terminate earlier, see the |
epsilon |
Numeric scalar, the algorithm terminates, if the maximal
delta is less than this. (See the reference below for what delta means.) If
you set this to zero, then the function always performs |
kkconst |
Numeric scalar, the Kamada-Kawai vertex attraction constant. Typical (and default) value is the number of vertices. |
weights |
Edge weights, larger values will result longer edges.
Note that this is opposite to |
minx |
If not |
maxx |
Similar to |
miny |
Similar to |
maxy |
Similar to |
minz |
Similar to |
maxz |
Similar to |
niter , sigma , initemp , coolexp
|
These arguments are not supported from igraph version 0.8.0 and are ignored (with a warning). |
start |
Deprecated synonym for |
... |
Passed to |
See the referenced paper below for the details of the algorithm.
This function was rewritten from scratch in igraph version 0.8.0 and it follows truthfully the original publication by Kamada and Kawai now.
A numeric matrix with two (dim=2) or three (dim=3) columns, and as many rows as the number of vertices, the x, y and potentially z coordinates of the vertices.
Gabor Csardi [email protected]
Kamada, T. and Kawai, S.: An Algorithm for Drawing General Undirected Graphs. Information Processing Letters, 31/1, 7–15, 1989.
layout_with_drl()
, plot.igraph()
,
tkplot()
Other graph layouts:
add_layout_()
,
component_wise()
,
layout_()
,
layout_as_bipartite()
,
layout_as_star()
,
layout_as_tree()
,
layout_in_circle()
,
layout_nicely()
,
layout_on_grid()
,
layout_on_sphere()
,
layout_randomly()
,
layout_with_dh()
,
layout_with_fr()
,
layout_with_gem()
,
layout_with_graphopt()
,
layout_with_lgl()
,
layout_with_mds()
,
layout_with_sugiyama()
,
merge_coords()
,
norm_coords()
,
normalize()
g <- make_ring(10) E(g)$weight <- rep(1:2, length.out = ecount(g)) plot(g, layout = layout_with_kk, edge.label = E(g)$weight)
g <- make_ring(10) E(g)$weight <- rep(1:2, length.out = ecount(g)) plot(g, layout = layout_with_kk, edge.label = E(g)$weight)
A layout generator for larger graphs.
layout_with_lgl( graph, maxiter = 150, maxdelta = vcount(graph), area = vcount(graph)^2, coolexp = 1.5, repulserad = area * vcount(graph), cellsize = sqrt(sqrt(area)), root = NULL ) with_lgl(...)
layout_with_lgl( graph, maxiter = 150, maxdelta = vcount(graph), area = vcount(graph)^2, coolexp = 1.5, repulserad = area * vcount(graph), cellsize = sqrt(sqrt(area)), root = NULL ) with_lgl(...)
graph |
The input graph |
maxiter |
The maximum number of iterations to perform (150). |
maxdelta |
The maximum change for a vertex during an iteration (the number of vertices). |
area |
The area of the surface on which the vertices are placed (square of the number of vertices). |
coolexp |
The cooling exponent of the simulated annealing (1.5). |
repulserad |
Cancellation radius for the repulsion (the |
cellsize |
The size of the cells for the grid. When calculating the
repulsion forces between vertices only vertices in the same or neighboring
grid cells are taken into account (the fourth root of the number of
|
root |
The id of the vertex to place at the middle of the layout. The default value is -1 which means that a random vertex is selected. |
... |
Passed to |
layout_with_lgl()
is for large connected graphs, it is similar to the layout
generator of the Large Graph Layout software
(https://lgl.sourceforge.net/).
A numeric matrix with two columns and as many rows as vertices.
Gabor Csardi [email protected]
Other graph layouts:
add_layout_()
,
component_wise()
,
layout_()
,
layout_as_bipartite()
,
layout_as_star()
,
layout_as_tree()
,
layout_in_circle()
,
layout_nicely()
,
layout_on_grid()
,
layout_on_sphere()
,
layout_randomly()
,
layout_with_dh()
,
layout_with_fr()
,
layout_with_gem()
,
layout_with_graphopt()
,
layout_with_kk()
,
layout_with_mds()
,
layout_with_sugiyama()
,
merge_coords()
,
norm_coords()
,
normalize()
Multidimensional scaling of some distance matrix defined on the vertices of a graph.
layout_with_mds(graph, dist = NULL, dim = 2, options = arpack_defaults()) with_mds(...)
layout_with_mds(graph, dist = NULL, dim = 2, options = arpack_defaults()) with_mds(...)
graph |
The input graph. |
dist |
The distance matrix for the multidimensional scaling. If
|
dim |
|
options |
This is currently ignored, as ARPACK is not used any more for solving the eigenproblem |
... |
Passed to |
layout_with_mds()
uses classical multidimensional scaling (Torgerson scaling)
for generating the coordinates. Multidimensional scaling aims to place points
from a higher dimensional space in a (typically) 2 dimensional plane, so that
the distances between the points are kept as much as this is possible.
By default igraph uses the shortest path matrix as the distances between the
nodes, but the user can override this via the dist
argument.
Warning: If the graph is symmetric to the exchange of two vertices (as is the case with leaves of a tree connecting to the same parent), classical multidimensional scaling may assign the same coordinates to these vertices.
This function generates the layout separately for each graph component and
then merges them via merge_coords()
.
A numeric matrix with dim
columns.
Tamas Nepusz [email protected] and Gabor Csardi [email protected]
Cox, T. F. and Cox, M. A. A. (2001) Multidimensional Scaling. Second edition. Chapman and Hall.
Other graph layouts:
add_layout_()
,
component_wise()
,
layout_()
,
layout_as_bipartite()
,
layout_as_star()
,
layout_as_tree()
,
layout_in_circle()
,
layout_nicely()
,
layout_on_grid()
,
layout_on_sphere()
,
layout_randomly()
,
layout_with_dh()
,
layout_with_fr()
,
layout_with_gem()
,
layout_with_graphopt()
,
layout_with_kk()
,
layout_with_lgl()
,
layout_with_sugiyama()
,
merge_coords()
,
norm_coords()
,
normalize()
g <- sample_gnp(100, 2 / 100) l <- layout_with_mds(g) plot(g, layout = l, vertex.label = NA, vertex.size = 3)
g <- sample_gnp(100, 2 / 100) l <- layout_with_mds(g) plot(g, layout = l, vertex.label = NA, vertex.size = 3)
Sugiyama layout algorithm for layered directed acyclic graphs. The algorithm minimized edge crossings.
layout_with_sugiyama( graph, layers = NULL, hgap = 1, vgap = 1, maxiter = 100, weights = NULL, attributes = c("default", "all", "none") ) with_sugiyama(...)
layout_with_sugiyama( graph, layers = NULL, hgap = 1, vgap = 1, maxiter = 100, weights = NULL, attributes = c("default", "all", "none") ) with_sugiyama(...)
graph |
The input graph. |
layers |
A numeric vector or |
hgap |
Real scalar, the minimum horizontal gap between vertices in the same layer. |
vgap |
Real scalar, the distance between layers. |
maxiter |
Integer scalar, the maximum number of iterations in the crossing minimization stage. 100 is a reasonable default; if you feel that you have too many edge crossings, increase this. |
weights |
Optional edge weight vector. If |
attributes |
Which graph/vertex/edge attributes to keep in the extended graph. ‘default’ keeps the ‘size’, ‘size2’, ‘shape’, ‘label’ and ‘color’ vertex attributes and the ‘arrow.mode’ and ‘arrow.size’ edge attributes. ‘all’ keep all graph, vertex and edge attributes, ‘none’ keeps none of them. |
... |
Passed to |
This layout algorithm is designed for directed acyclic graphs where each vertex is assigned to a layer. Layers are indexed from zero, and vertices of the same layer will be placed on the same horizontal line. The X coordinates of vertices within each layer are decided by the heuristic proposed by Sugiyama et al. to minimize edge crossings.
You can also try to lay out undirected graphs, graphs containing cycles, or graphs without an a priori layered assignment with this algorithm. igraph will try to eliminate cycles and assign vertices to layers, but there is no guarantee on the quality of the layout in such cases.
The Sugiyama layout may introduce “bends” on the edges in order to obtain a visually more pleasing layout. This is achieved by adding dummy nodes to edges spanning more than one layer. The resulting layout assigns coordinates not only to the nodes of the original graph but also to the dummy nodes. The layout algorithm will also return the extended graph with the dummy nodes.
For more details, see the reference below.
A list with the components:
layout |
The layout, a two-column matrix, for the original graph vertices. |
layout.dummy |
The layout for the dummy vertices, a two column matrix. |
extd_graph |
The original graph, extended with dummy vertices. The ‘dummy’ vertex attribute is set on this graph, it is a logical attributes, and it tells you whether the vertex is a dummy vertex. The ‘layout’ graph attribute is also set, and it is the layout matrix for all (original and dummy) vertices. |
Tamas Nepusz [email protected]
K. Sugiyama, S. Tagawa and M. Toda, "Methods for Visual Understanding of Hierarchical Systems". IEEE Transactions on Systems, Man and Cybernetics 11(2):109-125, 1981.
Other graph layouts:
add_layout_()
,
component_wise()
,
layout_()
,
layout_as_bipartite()
,
layout_as_star()
,
layout_as_tree()
,
layout_in_circle()
,
layout_nicely()
,
layout_on_grid()
,
layout_on_sphere()
,
layout_randomly()
,
layout_with_dh()
,
layout_with_fr()
,
layout_with_gem()
,
layout_with_graphopt()
,
layout_with_kk()
,
layout_with_lgl()
,
layout_with_mds()
,
merge_coords()
,
norm_coords()
,
normalize()
## Data taken from http://tehnick-8.narod.ru/dc_clients/ DC <- graph_from_literal( "DC++" -+ "LinuxDC++":"BCDC++":"EiskaltDC++":"StrongDC++":"DiCe!++", "LinuxDC++" -+ "FreeDC++", "BCDC++" -+ "StrongDC++", "FreeDC++" -+ "BMDC++":"EiskaltDC++", "StrongDC++" -+ "AirDC++":"zK++":"ApexDC++":"TkDC++", "StrongDC++" -+ "StrongDC++ SQLite":"RSX++", "ApexDC++" -+ "FlylinkDC++ ver <= 4xx", "ApexDC++" -+ "ApexDC++ Speed-Mod":"DiCe!++", "StrongDC++ SQLite" -+ "FlylinkDC++ ver >= 5xx", "ApexDC++ Speed-Mod" -+ "FlylinkDC++ ver <= 4xx", "ApexDC++ Speed-Mod" -+ "GreylinkDC++", "FlylinkDC++ ver <= 4xx" -+ "FlylinkDC++ ver >= 5xx", "FlylinkDC++ ver <= 4xx" -+ AvaLink, "GreylinkDC++" -+ AvaLink:"RayLinkDC++":"SparkDC++":PeLink ) ## Use edge types E(DC)$lty <- 1 E(DC)["BCDC++" %->% "StrongDC++"]$lty <- 2 E(DC)["FreeDC++" %->% "EiskaltDC++"]$lty <- 2 E(DC)["ApexDC++" %->% "FlylinkDC++ ver <= 4xx"]$lty <- 2 E(DC)["ApexDC++" %->% "DiCe!++"]$lty <- 2 E(DC)["StrongDC++ SQLite" %->% "FlylinkDC++ ver >= 5xx"]$lty <- 2 E(DC)["GreylinkDC++" %->% "AvaLink"]$lty <- 2 ## Layers, as on the plot layers <- list( c("DC++"), c("LinuxDC++", "BCDC++"), c("FreeDC++", "StrongDC++"), c( "BMDC++", "EiskaltDC++", "AirDC++", "zK++", "ApexDC++", "TkDC++", "RSX++" ), c("StrongDC++ SQLite", "ApexDC++ Speed-Mod", "DiCe!++"), c("FlylinkDC++ ver <= 4xx", "GreylinkDC++"), c( "FlylinkDC++ ver >= 5xx", "AvaLink", "RayLinkDC++", "SparkDC++", "PeLink" ) ) ## Check that we have all nodes all(sort(unlist(layers)) == sort(V(DC)$name)) ## Add some graphical parameters V(DC)$color <- "white" V(DC)$shape <- "rectangle" V(DC)$size <- 20 V(DC)$size2 <- 10 V(DC)$label <- lapply(V(DC)$name, function(x) { paste(strwrap(x, 12), collapse = "\n") }) E(DC)$arrow.size <- 0.5 ## Create a similar layout using the predefined layers lay1 <- layout_with_sugiyama(DC, layers = apply(sapply( layers, function(x) V(DC)$name %in% x ), 1, which)) ## Simple plot, not very nice par(mar = rep(.1, 4)) plot(DC, layout = lay1$layout, vertex.label.cex = 0.5) ## Sugiyama plot plot(lay1$extd_graph, vertex.label.cex = 0.5) ## The same with automatic layer calculation ## Keep vertex/edge attributes in the extended graph lay2 <- layout_with_sugiyama(DC, attributes = "all") plot(lay2$extd_graph, vertex.label.cex = 0.5) ## Another example, from the following paper: ## Markus Eiglsperger, Martin Siebenhaller, Michael Kaufmann: ## An Efficient Implementation of Sugiyama's Algorithm for ## Layered Graph Drawing, Journal of Graph Algorithms and ## Applications 9, 305--325 (2005). ex <- graph_from_literal( 0 -+ 29:6:5:20:4, 1 -+ 12, 2 -+ 23:8, 3 -+ 4, 4, 5 -+ 2:10:14:26:4:3, 6 -+ 9:29:25:21:13, 7, 8 -+ 20:16, 9 -+ 28:4, 10 -+ 27, 11 -+ 9:16, 12 -+ 9:19, 13 -+ 20, 14 -+ 10, 15 -+ 16:27, 16 -+ 27, 17 -+ 3, 18 -+ 13, 19 -+ 9, 20 -+ 4, 21 -+ 22, 22 -+ 8:9, 23 -+ 9:24, 24 -+ 12:15:28, 25 -+ 11, 26 -+ 18, 27 -+ 13:19, 28 -+ 7, 29 -+ 25 ) layers <- list( 0, c(5, 17), c(2, 14, 26, 3), c(23, 10, 18), c(1, 24), 12, 6, c(29, 21), c(25, 22), c(11, 8, 15), 16, 27, c(13, 19), c(9, 20), c(4, 28), 7 ) layex <- layout_with_sugiyama(ex, layers = apply( sapply( layers, function(x) V(ex)$name %in% as.character(x) ), 1, which )) origvert <- c(rep(TRUE, vcount(ex)), rep(FALSE, nrow(layex$layout.dummy))) realedge <- as_edgelist(layex$extd_graph)[, 2] <= vcount(ex) plot(layex$extd_graph, vertex.label.cex = 0.5, edge.arrow.size = .5, vertex.size = ifelse(origvert, 5, 0), vertex.shape = ifelse(origvert, "square", "none"), vertex.label = ifelse(origvert, V(ex)$name, ""), edge.arrow.mode = ifelse(realedge, 2, 0) )
## Data taken from http://tehnick-8.narod.ru/dc_clients/ DC <- graph_from_literal( "DC++" -+ "LinuxDC++":"BCDC++":"EiskaltDC++":"StrongDC++":"DiCe!++", "LinuxDC++" -+ "FreeDC++", "BCDC++" -+ "StrongDC++", "FreeDC++" -+ "BMDC++":"EiskaltDC++", "StrongDC++" -+ "AirDC++":"zK++":"ApexDC++":"TkDC++", "StrongDC++" -+ "StrongDC++ SQLite":"RSX++", "ApexDC++" -+ "FlylinkDC++ ver <= 4xx", "ApexDC++" -+ "ApexDC++ Speed-Mod":"DiCe!++", "StrongDC++ SQLite" -+ "FlylinkDC++ ver >= 5xx", "ApexDC++ Speed-Mod" -+ "FlylinkDC++ ver <= 4xx", "ApexDC++ Speed-Mod" -+ "GreylinkDC++", "FlylinkDC++ ver <= 4xx" -+ "FlylinkDC++ ver >= 5xx", "FlylinkDC++ ver <= 4xx" -+ AvaLink, "GreylinkDC++" -+ AvaLink:"RayLinkDC++":"SparkDC++":PeLink ) ## Use edge types E(DC)$lty <- 1 E(DC)["BCDC++" %->% "StrongDC++"]$lty <- 2 E(DC)["FreeDC++" %->% "EiskaltDC++"]$lty <- 2 E(DC)["ApexDC++" %->% "FlylinkDC++ ver <= 4xx"]$lty <- 2 E(DC)["ApexDC++" %->% "DiCe!++"]$lty <- 2 E(DC)["StrongDC++ SQLite" %->% "FlylinkDC++ ver >= 5xx"]$lty <- 2 E(DC)["GreylinkDC++" %->% "AvaLink"]$lty <- 2 ## Layers, as on the plot layers <- list( c("DC++"), c("LinuxDC++", "BCDC++"), c("FreeDC++", "StrongDC++"), c( "BMDC++", "EiskaltDC++", "AirDC++", "zK++", "ApexDC++", "TkDC++", "RSX++" ), c("StrongDC++ SQLite", "ApexDC++ Speed-Mod", "DiCe!++"), c("FlylinkDC++ ver <= 4xx", "GreylinkDC++"), c( "FlylinkDC++ ver >= 5xx", "AvaLink", "RayLinkDC++", "SparkDC++", "PeLink" ) ) ## Check that we have all nodes all(sort(unlist(layers)) == sort(V(DC)$name)) ## Add some graphical parameters V(DC)$color <- "white" V(DC)$shape <- "rectangle" V(DC)$size <- 20 V(DC)$size2 <- 10 V(DC)$label <- lapply(V(DC)$name, function(x) { paste(strwrap(x, 12), collapse = "\n") }) E(DC)$arrow.size <- 0.5 ## Create a similar layout using the predefined layers lay1 <- layout_with_sugiyama(DC, layers = apply(sapply( layers, function(x) V(DC)$name %in% x ), 1, which)) ## Simple plot, not very nice par(mar = rep(.1, 4)) plot(DC, layout = lay1$layout, vertex.label.cex = 0.5) ## Sugiyama plot plot(lay1$extd_graph, vertex.label.cex = 0.5) ## The same with automatic layer calculation ## Keep vertex/edge attributes in the extended graph lay2 <- layout_with_sugiyama(DC, attributes = "all") plot(lay2$extd_graph, vertex.label.cex = 0.5) ## Another example, from the following paper: ## Markus Eiglsperger, Martin Siebenhaller, Michael Kaufmann: ## An Efficient Implementation of Sugiyama's Algorithm for ## Layered Graph Drawing, Journal of Graph Algorithms and ## Applications 9, 305--325 (2005). ex <- graph_from_literal( 0 -+ 29:6:5:20:4, 1 -+ 12, 2 -+ 23:8, 3 -+ 4, 4, 5 -+ 2:10:14:26:4:3, 6 -+ 9:29:25:21:13, 7, 8 -+ 20:16, 9 -+ 28:4, 10 -+ 27, 11 -+ 9:16, 12 -+ 9:19, 13 -+ 20, 14 -+ 10, 15 -+ 16:27, 16 -+ 27, 17 -+ 3, 18 -+ 13, 19 -+ 9, 20 -+ 4, 21 -+ 22, 22 -+ 8:9, 23 -+ 9:24, 24 -+ 12:15:28, 25 -+ 11, 26 -+ 18, 27 -+ 13:19, 28 -+ 7, 29 -+ 25 ) layers <- list( 0, c(5, 17), c(2, 14, 26, 3), c(23, 10, 18), c(1, 24), 12, 6, c(29, 21), c(25, 22), c(11, 8, 15), 16, 27, c(13, 19), c(9, 20), c(4, 28), 7 ) layex <- layout_with_sugiyama(ex, layers = apply( sapply( layers, function(x) V(ex)$name %in% as.character(x) ), 1, which )) origvert <- c(rep(TRUE, vcount(ex)), rep(FALSE, nrow(layex$layout.dummy))) realedge <- as_edgelist(layex$extd_graph)[, 2] <= vcount(ex) plot(layex$extd_graph, vertex.label.cex = 0.5, edge.arrow.size = .5, vertex.size = ifelse(origvert, 5, 0), vertex.shape = ifelse(origvert, "square", "none"), vertex.label = ifelse(origvert, V(ex)$name, ""), edge.arrow.mode = ifelse(realedge, 2, 0) )
The scan statistic is a summary of the locality statistics that is
computed from the local neighborhood of each vertex. The
local_scan()
function computes the local statistics for each vertex
for a given neighborhood size and the statistic function.
local_scan( graph.us, graph.them = NULL, k = 1, FUN = NULL, weighted = FALSE, mode = c("out", "in", "all"), neighborhoods = NULL, ... )
local_scan( graph.us, graph.them = NULL, k = 1, FUN = NULL, weighted = FALSE, mode = c("out", "in", "all"), neighborhoods = NULL, ... )
graph.us , graph
|
An igraph object, the graph for which the scan statistics will be computed |
graph.them |
An igraph object or |
k |
An integer scalar, the size of the local neighborhood for each vertex. Should be non-negative. |
FUN |
Character, a function name, or a function object itself, for
computing the local statistic in each neighborhood. If |
weighted |
Logical scalar, TRUE if the edge weights should be used
for computation of the scan statistic. If TRUE, the graph should be
weighted. Note that this argument is ignored if |
mode |
Character scalar, the kind of neighborhoods to use for the
calculation. One of ‘ |
neighborhoods |
A list of neighborhoods, one for each vertex, or
In theory this could be useful if the same |
... |
Arguments passed to |
See the given reference below for the details on the local scan statistics.
local_scan()
calculates exact local scan statistics.
If graph.them
is NULL
, then local_scan()
computes the
‘us’ variant of the scan statistics. Otherwise,
graph.them
should be an igraph object and the ‘them’
variant is computed using graph.us
to extract the neighborhood
information, and applying FUN
on these neighborhoods in
graph.them
.
For local_scan()
typically a numeric vector containing the
computed local statistics for each vertex. In general a list or vector
of objects, as returned by FUN
.
Priebe, C. E., Conroy, J. M., Marchette, D. J., Park, Y. (2005). Scan Statistics on Enron Graphs. Computational and Mathematical Organization Theory.
Other scan statistics:
scan_stat()
pair <- sample_correlated_gnp_pair(n = 10^3, corr = 0.8, p = 0.1) local_0_us <- local_scan(graph.us = pair$graph1, k = 0) local_1_us <- local_scan(graph.us = pair$graph1, k = 1) local_0_them <- local_scan( graph.us = pair$graph1, graph.them = pair$graph2, k = 0 ) local_1_them <- local_scan( graph.us = pair$graph1, graph.them = pair$graph2, k = 1 ) Neigh_1 <- neighborhood(pair$graph1, order = 1) local_1_them_nhood <- local_scan( graph.us = pair$graph1, graph.them = pair$graph2, neighborhoods = Neigh_1 )
pair <- sample_correlated_gnp_pair(n = 10^3, corr = 0.8, p = 0.1) local_0_us <- local_scan(graph.us = pair$graph1, k = 0) local_1_us <- local_scan(graph.us = pair$graph1, k = 1) local_0_them <- local_scan( graph.us = pair$graph1, graph.them = pair$graph2, k = 0 ) local_1_them <- local_scan( graph.us = pair$graph1, graph.them = pair$graph2, k = 1 ) Neigh_1 <- neighborhood(pair$graph1, order = 1) local_1_them_nhood <- local_scan( graph.us = pair$graph1, graph.them = pair$graph2, neighborhoods = Neigh_1 )
This is a generic function for creating graphs.
make_(...)
make_(...)
... |
Parameters, see details below. |
make_()
is a generic function for creating graphs.
For every graph constructor in igraph that has a make_
prefix,
there is a corresponding function without the prefix: e.g.
for make_ring()
there is also ring()
, etc.
The same is true for the random graph samplers, i.e. for each
constructor with a sample_
prefix, there is a corresponding
function without that prefix.
These shorter forms can be used together with make_()
.
The advantage of this form is that the user can specify constructor
modifiers which work with all constructors. E.g. the
with_vertex_()
modifier adds vertex attributes
to the newly created graphs.
See the examples and the various constructor modifiers below.
Other deterministic constructors:
graph_from_atlas()
,
graph_from_edgelist()
,
graph_from_literal()
,
make_chordal_ring()
,
make_empty_graph()
,
make_full_citation_graph()
,
make_full_graph()
,
make_graph()
,
make_lattice()
,
make_ring()
,
make_star()
,
make_tree()
Constructor modifiers (and related functions)
sample_()
,
simplified()
,
with_edge_()
,
with_graph_()
,
with_vertex_()
,
without_attr()
,
without_loops()
,
without_multiples()
r <- make_(ring(10)) l <- make_(lattice(c(3, 3, 3))) r2 <- make_(ring(10), with_vertex_(color = "red", name = LETTERS[1:10])) l2 <- make_(lattice(c(3, 3, 3)), with_edge_(weight = 2)) ran <- sample_(degseq(c(3, 3, 3, 3, 3, 3), method = "configuration"), simplified()) degree(ran) is_simple(ran)
r <- make_(ring(10)) l <- make_(lattice(c(3, 3, 3))) r2 <- make_(ring(10), with_vertex_(color = "red", name = LETTERS[1:10])) l2 <- make_(lattice(c(3, 3, 3)), with_edge_(weight = 2)) ran <- sample_(degseq(c(3, 3, 3, 3, 3, 3), method = "configuration"), simplified()) degree(ran) is_simple(ran)
A bipartite graph has two kinds of vertices and connections are only allowed between different kinds.
make_bipartite_graph(types, edges, directed = FALSE) bipartite_graph(...)
make_bipartite_graph(types, edges, directed = FALSE) bipartite_graph(...)
types |
A vector giving the vertex types. It will be coerced into
boolean. The length of the vector gives the number of vertices in the graph.
When the vector is a named vector, the names will be attached to the graph
as the |
edges |
A vector giving the edges of the graph, the same way as for the
regular |
directed |
Whether to create a directed graph, boolean constant. Note that by default undirected graphs are created, as this is more common for bipartite graphs. |
... |
Passed to |
Bipartite graphs have a type
vertex attribute in igraph, this is
boolean and FALSE
for the vertices of the first kind and TRUE
for vertices of the second kind.
make_bipartite_graph()
basically does three things. First it checks the
edges
vector against the vertex types
. Then it creates a graph
using the edges
vector and finally it adds the types
vector as
a vertex attribute called type
. edges
may contain strings as
vertex names; in this case, types
must be a named vector that specifies
the type for each vertex name that occurs in edges
.
make_bipartite_graph()
returns a bipartite igraph graph. In other
words, an igraph graph that has a vertex attribute named type
.
is_bipartite()
returns a logical scalar.
Gabor Csardi [email protected]
make_graph()
to create one-mode networks
Bipartite graphs
bipartite_mapping()
,
bipartite_projection()
,
is_bipartite()
g <- make_bipartite_graph(rep(0:1, length.out = 10), c(1:10)) print(g, v = TRUE)
g <- make_bipartite_graph(rep(0:1, length.out = 10), c(1:10)) print(g, v = TRUE)
make_chordal_ring()
creates an extended chordal ring.
An extended chordal ring is regular graph, each node has the same
degree. It can be obtained from a simple ring by adding some extra
edges specified by a matrix. Let p denote the number of columns in
the ‘W
’ matrix. The extra edges of vertex i
are added according to column i mod p
in
‘W
’. The number of extra edges is the number
of rows in ‘W
’: for each row j
an edge
i->i+w[ij]
is added if i+w[ij]
is less than the number
of total nodes. See also Kotsis, G: Interconnection Topologies for
Parallel Processing Systems, PARS Mitteilungen 11, 1-6, 1993.
make_chordal_ring(n, w, directed = FALSE) chordal_ring(...)
make_chordal_ring(n, w, directed = FALSE) chordal_ring(...)
n |
The number of vertices. |
w |
A matrix which specifies the extended chordal ring. See details below. |
directed |
Logical scalar, whether or not to create a directed graph. |
... |
Passed to |
An igraph graph.
Other deterministic constructors:
graph_from_atlas()
,
graph_from_edgelist()
,
graph_from_literal()
,
make_()
,
make_empty_graph()
,
make_full_citation_graph()
,
make_full_graph()
,
make_graph()
,
make_lattice()
,
make_ring()
,
make_star()
,
make_tree()
chord <- make_chordal_ring( 15, matrix(c(3, 12, 4, 7, 8, 11), nr = 2) )
chord <- make_chordal_ring( 15, matrix(c(3, 12, 4, 7, 8, 11), nr = 2) )
This is useful to integrate the results of community finding algorithms that are not included in igraph.
make_clusters( graph, membership = NULL, algorithm = NULL, merges = NULL, modularity = TRUE )
make_clusters( graph, membership = NULL, algorithm = NULL, merges = NULL, modularity = TRUE )
graph |
The graph of the community structure. |
membership |
The membership vector of the community structure, a
numeric vector denoting the id of the community for each vertex. It
might be |
algorithm |
Character string, the algorithm that generated the community structure, it can be arbitrary. |
merges |
A merge matrix, for hierarchical community structures (or
|
modularity |
Modularity value of the community structure. If this
is |
A communities
object.
Community detection
as_membership()
,
cluster_edge_betweenness()
,
cluster_fast_greedy()
,
cluster_fluid_communities()
,
cluster_infomap()
,
cluster_label_prop()
,
cluster_leading_eigen()
,
cluster_leiden()
,
cluster_louvain()
,
cluster_optimal()
,
cluster_spinglass()
,
cluster_walktrap()
,
compare()
,
groups()
,
membership()
,
modularity.igraph()
,
plot_dendrogram()
,
split_join_distance()
,
voronoi_cells()
De Bruijn graphs are labeled graphs representing the overlap of strings.
make_de_bruijn_graph(m, n) de_bruijn_graph(...)
make_de_bruijn_graph(m, n) de_bruijn_graph(...)
m |
Integer scalar, the size of the alphabet. See details below. |
n |
Integer scalar, the length of the labels. See details below. |
... |
Passed to |
A de Bruijn graph represents relationships between strings. An alphabet of
m
letters are used and strings of length n
are considered. A
vertex corresponds to every possible string and there is a directed edge
from vertex v
to vertex w
if the string of v
can be
transformed into the string of w
by removing its first letter and
appending a letter to it.
Please note that the graph will have m
to the power n
vertices
and even more edges, so probably you don't want to supply too big numbers
for m
and n
.
De Bruijn graphs have some interesting properties, please see another source, e.g. Wikipedia for details.
A graph object.
Gabor Csardi [email protected]
make_kautz_graph()
, make_line_graph()
# de Bruijn graphs can be created recursively by line graphs as well g <- make_de_bruijn_graph(2, 1) make_de_bruijn_graph(2, 2) make_line_graph(g)
# de Bruijn graphs can be created recursively by line graphs as well g <- make_de_bruijn_graph(2, 1) make_de_bruijn_graph(2, 2) make_line_graph(g)
A graph with no edges
make_empty_graph(n = 0, directed = TRUE) empty_graph(...)
make_empty_graph(n = 0, directed = TRUE) empty_graph(...)
n |
Number of vertices. |
directed |
Whether to create a directed graph. |
... |
Passed to |
An igraph graph.
Other deterministic constructors:
graph_from_atlas()
,
graph_from_edgelist()
,
graph_from_literal()
,
make_()
,
make_chordal_ring()
,
make_full_citation_graph()
,
make_full_graph()
,
make_graph()
,
make_lattice()
,
make_ring()
,
make_star()
,
make_tree()
make_empty_graph(n = 10) make_empty_graph(n = 5, directed = FALSE)
make_empty_graph(n = 10) make_empty_graph(n = 5, directed = FALSE)
make_from_prufer()
creates an undirected tree graph from its Prüfer
sequence.
make_from_prufer(prufer) from_prufer(...)
make_from_prufer(prufer) from_prufer(...)
prufer |
The Prüfer sequence to convert into a graph |
... |
Passed to |
The Prüfer sequence of a tree graph with n labeled vertices is a sequence of n-2 numbers, constructed as follows. If the graph has more than two vertices, find a vertex with degree one, remove it from the tree and add the label of the vertex that it was connected to to the sequence. Repeat until there are only two vertices in the remaining graph.
A graph object.
to_prufer()
to convert a graph into its Prüfer sequence
Other trees:
is_forest()
,
is_tree()
,
sample_spanning_tree()
,
to_prufer()
g <- make_tree(13, 3) to_prufer(g)
g <- make_tree(13, 3) to_prufer(g)
Bipartite graphs are also called two-mode by some. This function creates a bipartite graph in which every possible edge is present.
make_full_bipartite_graph( n1, n2, directed = FALSE, mode = c("all", "out", "in") ) full_bipartite_graph(...)
make_full_bipartite_graph( n1, n2, directed = FALSE, mode = c("all", "out", "in") ) full_bipartite_graph(...)
n1 |
The number of vertices of the first kind. |
n2 |
The number of vertices of the second kind. |
directed |
Logical scalar, whether the graphs is directed. |
mode |
Scalar giving the kind of edges to create for directed graphs.
If this is ‘ |
... |
Passed to |
Bipartite graphs have a ‘type
’ vertex attribute in igraph,
this is boolean and FALSE
for the vertices of the first kind and
TRUE
for vertices of the second kind.
An igraph graph, with the ‘type
’ vertex attribute set.
Gabor Csardi [email protected]
make_full_graph()
for creating one-mode full graphs
g <- make_full_bipartite_graph(2, 3) g2 <- make_full_bipartite_graph(2, 3, directed = TRUE) g3 <- make_full_bipartite_graph(2, 3, directed = TRUE, mode = "in") g4 <- make_full_bipartite_graph(2, 3, directed = TRUE, mode = "all")
g <- make_full_bipartite_graph(2, 3) g2 <- make_full_bipartite_graph(2, 3, directed = TRUE) g3 <- make_full_bipartite_graph(2, 3, directed = TRUE, mode = "in") g4 <- make_full_bipartite_graph(2, 3, directed = TRUE, mode = "all")
make_full_citation_graph()
creates a full citation graph. This is a
directed graph, where every i->j
edge is present if and only if
. If
directed=FALSE
then the graph is just a full graph.
make_full_citation_graph(n, directed = TRUE) full_citation_graph(...)
make_full_citation_graph(n, directed = TRUE) full_citation_graph(...)
n |
The number of vertices. |
directed |
Whether to create a directed graph. |
... |
Passed to |
An igraph graph.
Other deterministic constructors:
graph_from_atlas()
,
graph_from_edgelist()
,
graph_from_literal()
,
make_()
,
make_chordal_ring()
,
make_empty_graph()
,
make_full_graph()
,
make_graph()
,
make_lattice()
,
make_ring()
,
make_star()
,
make_tree()
print_all(make_full_citation_graph(10))
print_all(make_full_citation_graph(10))
Create a full graph
make_full_graph(n, directed = FALSE, loops = FALSE) full_graph(...)
make_full_graph(n, directed = FALSE, loops = FALSE) full_graph(...)
n |
Number of vertices. |
directed |
Whether to create a directed graph. |
loops |
Whether to add self-loops to the graph. |
... |
Passed to |
An igraph graph
Other deterministic constructors:
graph_from_atlas()
,
graph_from_edgelist()
,
graph_from_literal()
,
make_()
,
make_chordal_ring()
,
make_empty_graph()
,
make_full_citation_graph()
,
make_graph()
,
make_lattice()
,
make_ring()
,
make_star()
,
make_tree()
make_full_graph(5) print_all(make_full_graph(4, directed = TRUE))
make_full_graph(5) print_all(make_full_graph(4, directed = TRUE))
Create an igraph graph from a list of edges, or a notable graph
make_graph( edges, ..., n = max(edges), isolates = NULL, directed = TRUE, dir = directed, simplify = TRUE ) make_directed_graph(edges, n = max(edges)) make_undirected_graph(edges, n = max(edges)) directed_graph(...) undirected_graph(...)
make_graph( edges, ..., n = max(edges), isolates = NULL, directed = TRUE, dir = directed, simplify = TRUE ) make_directed_graph(edges, n = max(edges)) make_undirected_graph(edges, n = max(edges)) directed_graph(...) undirected_graph(...)
edges |
A vector defining the edges, the first edge points from the first element to the second, the second edge from the third to the fourth, etc. For a numeric vector, these are interpreted as internal vertex ids. For character vectors, they are interpreted as vertex names. Alternatively, this can be a character scalar, the name of a notable graph. See Notable graphs below. The name is case insensitive. Starting from igraph 0.8.0, you can also include literals here,
via igraph's formula notation (see |
... |
For |
n |
The number of vertices in the graph. This argument is
ignored (with a warning) if |
isolates |
Character vector, names of isolate vertices, for symbolic edge lists. It is ignored for numeric edge lists. |
directed |
Whether to create a directed graph. |
dir |
It is the same as |
simplify |
For graph literals, whether to simplify the graph. |
An igraph graph.
make_graph()
can create some notable graphs. The name of the
graph (case insensitive), a character scalar must be supplied as
the edges
argument, and other arguments are ignored. (A warning
is given is they are specified.)
make_graph()
knows the following graphs:
The bull graph, 5 vertices, 5 edges, resembles to the head of a bull if drawn properly.
This is the smallest triangle-free graph that is both 4-chromatic and 4-regular. According to the Grunbaum conjecture there exists an m-regular, m-chromatic graph with n vertices for every m>1 and n>2. The Chvatal graph is an example for m=4 and n=12. It has 24 edges.
A non-Hamiltonian cubic symmetric graph with 28 vertices and 42 edges.
The Platonic graph of the cube. A convex regular polyhedron with 8 vertices and 12 edges.
A graph with 4 vertices and 5 edges, resembles to a schematic diamond if drawn properly.
Another Platonic solid with 20 vertices and 30 edges.
The semisymmetric graph with minimum number of vertices, 20 and 40 edges. A semisymmetric graph is regular, edge transitive and not vertex transitive.
This is a graph whose embedding to the Klein bottle can be colored with six colors, it is a counterexample to the necessity of the Heawood conjecture on a Klein bottle. It has 12 vertices and 18 edges.
The Frucht Graph is the smallest cubical graph whose automorphism group consists only of the identity element. It has 12 vertices and 18 edges.
The Groetzsch graph is a triangle-free graph with 11 vertices, 20 edges, and chromatic number 4. It is named after German mathematician Herbert Groetzsch, and its existence demonstrates that the assumption of planarity is necessary in Groetzsch's theorem that every triangle-free planar graph is 3-colorable.
The Heawood graph is an undirected graph with 14 vertices and 21 edges. The graph is cubic, and all cycles in the graph have six or more edges. Every smaller cubic graph has shorter cycles, so this graph is the 6-cage, the smallest cubic graph of girth 6.
The Herschel graph is the smallest nonhamiltonian polyhedral graph. It is the unique such graph on 11 nodes, and has 18 edges.
The house graph is a 5-vertex, 6-edge graph, the schematic draw of a house if drawn properly, basicly a triangle of the top of a square.
The same as the house graph with an X in the square. 5 vertices and 8 edges.
A Platonic solid with 12 vertices and 30 edges.
A social network with 10 vertices and 18 edges. Krackhardt, D. Assessing the Political Landscape: Structure, Cognition, and Power in Organizations. Admin. Sci. Quart. 35, 342-369, 1990.
The graph is a 4-arc transitive cubic graph, it has 30 vertices and 45 edges.
The McGee graph is the unique 3-regular 7-cage graph, it has 24 vertices and 36 edges.
The Meredith graph is a quartic graph on 70 nodes and 140 edges that is a counterexample to the conjecture that every 4-regular 4-connected graph is Hamiltonian.
A connected graph with 16 vertices and 27 edges containing no perfect matching. A matching in a graph is a set of pairwise non-adjacent edges; that is, no two edges share a common vertex. A perfect matching is a matching which covers all vertices of the graph.
A graph whose connected components are the 9 graphs whose presence as a vertex-induced subgraph in a graph makes a nonline graph. It has 50 vertices and 72 edges.
Platonic solid with 6 vertices and 12 edges.
A 3-regular graph with 10 vertices and 15 edges. It is the smallest hypohamiltonian graph, i.e. it is non-hamiltonian but removing any single vertex from it makes it Hamiltonian.
The unique (4,5)-cage graph, i.e. a 4-regular graph of girth 5. It has 19 vertices and 38 edges.
A smallest nontrivial graph whose automorphism group is cyclic. It has 9 vertices and 15 edges.
Platonic solid with 4 vertices and 6 edges.
The smallest hypotraceable graph, on 34 vertices and 52 edges. A hypotraceable graph does not contain a Hamiltonian path but after removing any single vertex from it the remainder always contains a Hamiltonian path. A graph containing a Hamiltonian path is called traceable.
Tait's Hamiltonian graph conjecture states that every 3-connected 3-regular planar graph is Hamiltonian. This graph is a counterexample. It has 46 vertices and 69 edges.
Returns a 12-vertex, triangle-free graph with chromatic number 3 that is uniquely 3-colorable.
An identity graph with 25 vertices and 31 edges. An identity graph has a single graph automorphism, the trivial one.
Social network of friendships between 34 members of a karate club at a US university in the 1970s. See W. W. Zachary, An information flow model for conflict and fission in small groups, Journal of Anthropological Research 33, 452-473 (1977).
Other deterministic constructors:
graph_from_atlas()
,
graph_from_edgelist()
,
graph_from_literal()
,
make_()
,
make_chordal_ring()
,
make_empty_graph()
,
make_full_citation_graph()
,
make_full_graph()
,
make_lattice()
,
make_ring()
,
make_star()
,
make_tree()
make_graph(c(1, 2, 2, 3, 3, 4, 5, 6), directed = FALSE) make_graph(c("A", "B", "B", "C", "C", "D"), directed = FALSE) solids <- list( make_graph("Tetrahedron"), make_graph("Cubical"), make_graph("Octahedron"), make_graph("Dodecahedron"), make_graph("Icosahedron") ) graph <- make_graph( ~ A - B - C - D - A, E - A:B:C:D, F - G - H - I - F, J - F:G:H:I, K - L - M - N - K, O - K:L:M:N, P - Q - R - S - P, T - P:Q:R:S, B - F, E - J, C - I, L - T, O - T, M - S, C - P, C - L, I - L, I - P )
make_graph(c(1, 2, 2, 3, 3, 4, 5, 6), directed = FALSE) make_graph(c("A", "B", "B", "C", "C", "D"), directed = FALSE) solids <- list( make_graph("Tetrahedron"), make_graph("Cubical"), make_graph("Octahedron"), make_graph("Dodecahedron"), make_graph("Icosahedron") ) graph <- make_graph( ~ A - B - C - D - A, E - A:B:C:D, F - G - H - I - F, J - F:G:H:I, K - L - M - N - K, O - K:L:M:N, P - Q - R - S - P, T - P:Q:R:S, B - F, E - J, C - I, L - T, O - T, M - S, C - P, C - L, I - L, I - P )
Kautz graphs are labeled graphs representing the overlap of strings.
make_kautz_graph(m, n) kautz_graph(...)
make_kautz_graph(m, n) kautz_graph(...)
m |
Integer scalar, the size of the alphabet. See details below. |
n |
Integer scalar, the length of the labels. See details below. |
... |
Passed to |
A Kautz graph is a labeled graph, vertices are labeled by strings of length
n+1
above an alphabet with m+1
letters, with the restriction
that every two consecutive letters in the string must be different. There is
a directed edge from a vertex v
to another vertex w
if it is
possible to transform the string of v
into the string of w
by
removing the first letter and appending a letter to it.
Kautz graphs have some interesting properties, see e.g. Wikipedia for details.
A graph object.
Gabor Csardi [email protected], the first version in R was written by Vincent Matossian.
make_de_bruijn_graph()
, make_line_graph()
make_line_graph(make_kautz_graph(2, 1)) make_kautz_graph(2, 2)
make_line_graph(make_kautz_graph(2, 1)) make_kautz_graph(2, 2)
make_lattice()
is a flexible function, it can create lattices of
arbitrary dimensions, periodic or aperiodic ones. It has two
forms. In the first form you only supply dimvector
, but not
length
and dim
. In the second form you omit
dimvector
and supply length
and dim
.
make_lattice( dimvector = NULL, length = NULL, dim = NULL, nei = 1, directed = FALSE, mutual = FALSE, periodic = FALSE, circular = deprecated() ) lattice(...)
make_lattice( dimvector = NULL, length = NULL, dim = NULL, nei = 1, directed = FALSE, mutual = FALSE, periodic = FALSE, circular = deprecated() ) lattice(...)
dimvector |
A vector giving the size of the lattice in each dimension. |
length |
Integer constant, for regular lattices, the size of the lattice in each dimension. |
dim |
Integer constant, the dimension of the lattice. |
nei |
The distance within which (inclusive) the neighbors on the lattice will be connected. This parameter is not used right now. |
directed |
Whether to create a directed lattice. |
mutual |
Logical, if |
periodic |
Logical vector, Boolean vector, defines whether the generated lattice is periodic along each dimension. This parameter may also be scalar boolen value which will be extended to boolean vector with dimvector length. |
circular |
Deprecated, use |
... |
Passed to |
An igraph graph.
Other deterministic constructors:
graph_from_atlas()
,
graph_from_edgelist()
,
graph_from_literal()
,
make_()
,
make_chordal_ring()
,
make_empty_graph()
,
make_full_citation_graph()
,
make_full_graph()
,
make_graph()
,
make_ring()
,
make_star()
,
make_tree()
make_lattice(c(5, 5, 5)) make_lattice(length = 5, dim = 3)
make_lattice(c(5, 5, 5)) make_lattice(length = 5, dim = 3)
This function calculates the line graph of another graph.
make_line_graph(graph) line_graph(...)
make_line_graph(graph) line_graph(...)
graph |
The input graph, it can be directed or undirected. |
... |
Passed to |
The line graph L(G)
of a G
undirected graph is defined as
follows. L(G)
has one vertex for each edge in G
and two
vertices in L(G)
are connected by an edge if their corresponding
edges share an end point.
The line graph L(G)
of a G
directed graph is slightly
different, L(G)
has one vertex for each edge in G
and two
vertices in L(G)
are connected by a directed edge if the target of
the first vertex's corresponding edge is the same as the source of the
second vertex's corresponding edge.
A new graph object.
Gabor Csardi [email protected], the first version of the C code was written by Vincent Matossian.
# generate the first De-Bruijn graphs g <- make_full_graph(2, directed = TRUE, loops = TRUE) make_line_graph(g) make_line_graph(make_line_graph(g)) make_line_graph(make_line_graph(make_line_graph(g)))
# generate the first De-Bruijn graphs g <- make_full_graph(2, directed = TRUE, loops = TRUE) make_line_graph(g) make_line_graph(make_line_graph(g)) make_line_graph(make_line_graph(make_line_graph(g)))
A ring is a one-dimensional lattice and this function is a special case
of make_lattice()
.
make_ring(n, directed = FALSE, mutual = FALSE, circular = TRUE) ring(...)
make_ring(n, directed = FALSE, mutual = FALSE, circular = TRUE) ring(...)
n |
Number of vertices. |
directed |
Whether the graph is directed. |
mutual |
Whether directed edges are mutual. It is ignored in undirected graphs. |
circular |
Whether to create a circular ring. A non-circular ring is essentially a “line”: a tree where every non-leaf vertex has one child. |
... |
Passed to |
An igraph graph.
Other deterministic constructors:
graph_from_atlas()
,
graph_from_edgelist()
,
graph_from_literal()
,
make_()
,
make_chordal_ring()
,
make_empty_graph()
,
make_full_citation_graph()
,
make_full_graph()
,
make_graph()
,
make_lattice()
,
make_star()
,
make_tree()
print_all(make_ring(10)) print_all(make_ring(10, directed = TRUE, mutual = TRUE))
print_all(make_ring(10)) print_all(make_ring(10, directed = TRUE, mutual = TRUE))
star()
creates a star graph, in this every single vertex is
connected to the center vertex and nobody else.
make_star(n, mode = c("in", "out", "mutual", "undirected"), center = 1) star(...)
make_star(n, mode = c("in", "out", "mutual", "undirected"), center = 1) star(...)
n |
Number of vertices. |
mode |
It defines the direction of the
edges, |
center |
ID of the center vertex. |
... |
Passed to |
An igraph graph.
Other deterministic constructors:
graph_from_atlas()
,
graph_from_edgelist()
,
graph_from_literal()
,
make_()
,
make_chordal_ring()
,
make_empty_graph()
,
make_full_citation_graph()
,
make_full_graph()
,
make_graph()
,
make_lattice()
,
make_ring()
,
make_tree()
make_star(10, mode = "out") make_star(5, mode = "undirected")
make_star(10, mode = "out") make_star(5, mode = "undirected")
Create a k-ary tree graph, where almost all vertices other than the leaves have the same number of children.
make_tree(n, children = 2, mode = c("out", "in", "undirected")) tree(...)
make_tree(n, children = 2, mode = c("out", "in", "undirected")) tree(...)
n |
Number of vertices. |
children |
Integer scalar, the number of children of a vertex (except for leafs) |
mode |
Defines the direction of the
edges. |
... |
Passed to |
An igraph graph
Other deterministic constructors:
graph_from_atlas()
,
graph_from_edgelist()
,
graph_from_literal()
,
make_()
,
make_chordal_ring()
,
make_empty_graph()
,
make_full_citation_graph()
,
make_full_graph()
,
make_graph()
,
make_lattice()
,
make_ring()
,
make_star()
make_tree(10, 2) make_tree(10, 3, mode = "undirected")
make_tree(10, 2) make_tree(10, 3, mode = "undirected")
Given two adjacency matrices A
and B
of the same size, match
the two graphs with the help of m
seed vertex pairs which correspond
to the first m
rows (and columns) of the adjacency matrices.
match_vertices(A, B, m, start, iteration)
match_vertices(A, B, m, start, iteration)
A |
a numeric matrix, the adjacency matrix of the first graph |
B |
a numeric matrix, the adjacency matrix of the second graph |
m |
The number of seeds. The first |
start |
a numeric matrix, the permutation matrix estimate is
initialized with |
iteration |
The number of iterations for the Frank-Wolfe algorithm |
The approximate graph matching problem is to find a bijection between the vertices of two graphs , such that the number of edge disagreements between the corresponding vertex pairs is minimized. For seeded graph matching, part of the bijection that consist of known correspondences (the seeds) is known and the problem task is to complete the bijection by estimating the permutation matrix that permutes the rows and columns of the adjacency matrix of the second graph.
It is assumed that for the two supplied adjacency matrices A
and
B
, both of size , the first
rows(and
columns) of
A
and B
correspond to the same vertices in both
graphs. That is, the permutation matrix that defines
the bijection is
for a
permutation matrix
and
times
identity matrix
. The function
match_vertices()
estimates
the permutation matrix via an optimization algorithm based on the
Frank-Wolfe algorithm.
See references for further details.
A numeric matrix which is the permutation matrix that determines the
bijection between the graphs of A
and B
Vince Lyzinski https://www.ams.jhu.edu/~lyzinski/
Vogelstein, J. T., Conroy, J. M., Podrazik, L. J., Kratzer, S. G., Harley, E. T., Fishkind, D. E.,Vogelstein, R. J., Priebe, C. E. (2011). Fast Approximate Quadratic Programming for Large (Brain) Graph Matching. Online: https://arxiv.org/abs/1112.5507
Fishkind, D. E., Adali, S., Priebe, C. E. (2012). Seeded Graph Matching Online: https://arxiv.org/abs/1209.0367
sample_correlated_gnp()
,sample_correlated_gnp_pair()
# require(Matrix) g1 <- sample_gnp(10, 0.1) randperm <- c(1:3, 3 + sample(7)) g2 <- sample_correlated_gnp(g1, corr = 1, p = g1$p, permutation = randperm) A <- as_adjacency_matrix(g1) B <- as_adjacency_matrix(g2) P <- match_vertices(A, B, m = 3, start = diag(rep(1, nrow(A) - 3)), 20) P
# require(Matrix) g1 <- sample_gnp(10, 0.1) randperm <- c(1:3, 3 + sample(7)) g2 <- sample_correlated_gnp(g1, corr = 1, p = g1$p, permutation = randperm) A <- as_adjacency_matrix(g1) B <- as_adjacency_matrix(g2) P <- match_vertices(A, B, m = 3, start = diag(rep(1, nrow(A) - 3)), 20) P
Maximum cardinality search is a simple ordering a vertices that is useful in determining the chordality of a graph.
max_cardinality(graph)
max_cardinality(graph)
graph |
The input graph. It may be directed, but edge directions are ignored, as the algorithm is defined for undirected graphs. |
Maximum cardinality search visits the vertices in such an order that every time the vertex with the most already visited neighbors is visited. Ties are broken randomly.
The algorithm provides a simple basis for deciding whether a graph is
chordal, see References below, and also is_chordal()
.
A list with two components:
alpha |
Numeric vector. The 1-based rank of each vertex in the graph such that the vertex with rank 1 is visited first, the vertex with rank 2 is visited second and so on. |
alpham1 |
Numeric vector. The inverse of |
igraph_maximum_cardinality_search()
.
Gabor Csardi [email protected]
Robert E Tarjan and Mihalis Yannakakis. (1984). Simple linear-time algorithms to test chordality of graphs, test acyclicity of hypergraphs, and selectively reduce acyclic hypergraphs. SIAM Journal of Computation 13, 566–579.
Other chordal:
is_chordal()
## The examples from the Tarjan-Yannakakis paper g1 <- graph_from_literal( A - B:C:I, B - A:C:D, C - A:B:E:H, D - B:E:F, E - C:D:F:H, F - D:E:G, G - F:H, H - C:E:G:I, I - A:H ) max_cardinality(g1) is_chordal(g1, fillin = TRUE) g2 <- graph_from_literal( A - B:E, B - A:E:F:D, C - E:D:G, D - B:F:E:C:G, E - A:B:C:D:F, F - B:D:E, G - C:D:H:I, H - G:I:J, I - G:H:J, J - H:I ) max_cardinality(g2) is_chordal(g2, fillin = TRUE)
## The examples from the Tarjan-Yannakakis paper g1 <- graph_from_literal( A - B:C:I, B - A:C:D, C - A:B:E:H, D - B:E:F, E - C:D:F:H, F - D:E:G, G - F:H, H - C:E:G:I, I - A:H ) max_cardinality(g1) is_chordal(g1, fillin = TRUE) g2 <- graph_from_literal( A - B:E, B - A:E:F:D, C - E:D:G, D - B:F:E:C:G, E - A:B:C:D:F, F - B:D:E, G - C:D:H:I, H - G:I:J, I - G:H:J, J - H:I ) max_cardinality(g2) is_chordal(g2, fillin = TRUE)
In a graph where each edge has a given flow capacity the maximal flow between two vertices is calculated.
max_flow(graph, source, target, capacity = NULL)
max_flow(graph, source, target, capacity = NULL)
graph |
The input graph. |
source |
The id of the source vertex. |
target |
The id of the target vertex (sometimes also called sink). |
capacity |
Vector giving the capacity of the edges. If this is
|
max_flow()
calculates the maximum flow between two vertices in a
weighted (i.e. valued) graph. A 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 (the capacity
parameter or edge attribute), (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
vertex. The maximum flow
is the flow of maximum value.
A named list with components:
value |
A numeric scalar, the value of the maximum flow. |
flow |
A numeric vector, the flow itself, one entry for each edge. For undirected graphs this entry is bit trickier, since for these the flow direction is not predetermined by the edge direction. For these graphs the elements of the this vector can be negative, this means that the flow goes from the bigger vertex id to the smaller one. Positive values mean that the flow goes from the smaller vertex id to the bigger one. |
cut |
A numeric vector of edge ids, the minimum cut corresponding to the maximum flow. |
partition1 |
A numeric vector of vertex ids, the vertices in the first partition of the minimum cut corresponding to the maximum flow. |
partition2 |
A numeric vector of vertex ids, the vertices in the second partition of the minimum cut corresponding to the maximum flow. |
stats |
A list with some statistics from the push-relabel
algorithm. Five integer values currently: |
A. V. Goldberg and R. E. Tarjan: A New Approach to the Maximum Flow Problem Journal of the ACM 35:921-940, 1988.
Other flow:
dominator_tree()
,
edge_connectivity()
,
is_min_separator()
,
is_separator()
,
min_cut()
,
min_separators()
,
min_st_separators()
,
st_cuts()
,
st_min_cuts()
,
vertex_connectivity()
E <- rbind(c(1, 3, 3), c(3, 4, 1), c(4, 2, 2), c(1, 5, 1), c(5, 6, 2), c(6, 2, 10)) colnames(E) <- c("from", "to", "capacity") g1 <- graph_from_data_frame(as.data.frame(E)) max_flow(g1, source = V(g1)["1"], target = V(g1)["2"])
E <- rbind(c(1, 3, 3), c(3, 4, 1), c(4, 2, 2), c(1, 5, 1), c(5, 6, 2), c(6, 2, 10)) colnames(E) <- c("from", "to", "capacity") g1 <- graph_from_data_frame(as.data.frame(E)) max_flow(g1, source = V(g1)["1"], target = V(g1)["2"])
igraph community detection functions return their results as an object from
the communities
class. This manual page describes the operations of
this class.
membership(communities) ## S3 method for class 'communities' print(x, ...) ## S3 method for class 'communities' modularity(x, ...) ## S3 method for class 'communities' length(x) sizes(communities) algorithm(communities) merges(communities) crossing(communities, graph) code_len(communities) is_hierarchical(communities) ## S3 method for class 'communities' as.dendrogram(object, hang = -1, use.modularity = FALSE, ...) ## S3 method for class 'communities' as.hclust(x, hang = -1, use.modularity = FALSE, ...) cut_at(communities, no, steps) show_trace(communities) ## S3 method for class 'communities' plot( x, y, col = membership(x), mark.groups = communities(x), edge.color = c("black", "red")[crossing(x, y) + 1], ... ) communities(x)
membership(communities) ## S3 method for class 'communities' print(x, ...) ## S3 method for class 'communities' modularity(x, ...) ## S3 method for class 'communities' length(x) sizes(communities) algorithm(communities) merges(communities) crossing(communities, graph) code_len(communities) is_hierarchical(communities) ## S3 method for class 'communities' as.dendrogram(object, hang = -1, use.modularity = FALSE, ...) ## S3 method for class 'communities' as.hclust(x, hang = -1, use.modularity = FALSE, ...) cut_at(communities, no, steps) show_trace(communities) ## S3 method for class 'communities' plot( x, y, col = membership(x), mark.groups = communities(x), edge.color = c("black", "red")[crossing(x, y) + 1], ... ) communities(x)
communities , x , object
|
A |
... |
Additional arguments. |
graph |
An igraph graph object, corresponding to |
hang |
Numeric scalar indicating how the height of leaves should be
computed from the heights of their parents; see |
use.modularity |
Logical scalar, whether to use the modularity values to define the height of the branches. |
no |
Integer scalar, the desired number of communities. If too low or
two high, then an error message is given. Exactly one of |
steps |
The number of merge operations to perform to produce the
communities. Exactly one of |
y |
An igraph graph object, corresponding to the communities in
|
col |
A vector of colors, in any format that is accepted by the regular R plotting methods. This vector gives the colors of the vertices explicitly. |
mark.groups |
A list of numeric vectors. The communities can be
highlighted using colored polygons. The groups for which the polygons are
drawn are given here. The default is to use the groups given by the
communities. Supply |
edge.color |
The colors of the edges. By default the edges within communities are colored green and other edges are red. |
membership |
Numeric vector, one value for each vertex, the membership
vector of the community structure. Might also be |
algorithm |
If not |
merges |
If not |
modularity |
Numeric scalar or vector, the modularity value of the
community structure. It can also be |
Community structure detection algorithms try to find dense subgraphs in directed or undirected graphs, by optimizing some criteria, and usually using heuristics.
igraph implements a number of community detection methods (see them below),
all of which return an object of the class communities
. Because the
community structure detection algorithms are different, communities
objects do not always have the same structure. Nevertheless, they have some
common operations, these are documented here.
The print()
generic function is defined for communities
, it
prints a short summary.
The length
generic function call be called on communities
and
returns the number of communities.
The sizes()
function returns the community sizes, in the order of their
ids.
membership()
gives the division of the vertices, into communities. It
returns a numeric vector, one value for each vertex, the id of its
community. Community ids start from one. Note that some algorithms calculate
the complete (or incomplete) hierarchical structure of the communities, and
not just a single partitioning. For these algorithms typically the
membership for the highest modularity value is returned, but see also the
manual pages of the individual algorithms.
communities()
is also the name of a function, that returns a list of
communities, each identified by their vertices. The vertices will have
symbolic names if the add.vertex.names
igraph option is set, and the
graph itself was named. Otherwise numeric vertex ids are used.
modularity()
gives the modularity score of the partitioning. (See
modularity.igraph()
for details. For algorithms that do not
result a single partitioning, the highest modularity value is returned.
algorithm()
gives the name of the algorithm that was used to calculate
the community structure.
crossing()
returns a logical vector, with one value for each edge,
ordered according to the edge ids. The value is TRUE
iff the edge
connects two different communities, according to the (best) membership
vector, as returned by membership()
.
is_hierarchical()
checks whether a hierarchical algorithm was used to
find the community structure. Some functions only make sense for
hierarchical methods (e.g. merges()
, cut_at()
and
as.dendrogram()
).
merges()
returns the merge matrix for hierarchical methods. An error
message is given, if a non-hierarchical method was used to find the
community structure. You can check this by calling is_hierarchical()
on
the communities
object.
cut_at()
cuts the merge tree of a hierarchical community finding method,
at the desired place and returns a membership vector. The desired place can
be expressed as the desired number of communities or as the number of merge
steps to make. The function gives an error message, if called with a
non-hierarchical method.
as.dendrogram()
converts a hierarchical community structure to a
dendrogram
object. It only works for hierarchical methods, and gives
an error message to others. See stats::dendrogram()
for details.
stats::as.hclust()
is similar to as.dendrogram()
, but converts a
hierarchical community structure to a hclust
object.
ape::as.phylo()
converts a hierarchical community structure to a phylo
object, you will need the ape
package for this.
show_trace()
works (currently) only for communities found by the leading
eigenvector method (cluster_leading_eigen()
), and
returns a character vector that gives the steps performed by the algorithm
while finding the communities.
code_len()
is defined for the InfoMAP method
(cluster_infomap()
and returns the code length of the
partition.
It is possibly to call the plot()
function on communities
objects. This will plot the graph (and uses plot.igraph()
internally), with the communities shown. By default it colores the vertices
according to their communities, and also marks the vertex groups
corresponding to the communities. It passes additional arguments to
plot.igraph()
, please see that and also
igraph.plotting on how to change the plot.
print()
returns the communities
object itself,
invisibly.
length
returns an integer scalar.
sizes()
returns a numeric vector.
membership()
returns a numeric vector, one number for each vertex in
the graph that was the input of the community detection.
modularity()
returns a numeric scalar.
algorithm()
returns a character scalar.
crossing()
returns a logical vector.
is_hierarchical()
returns a logical scalar.
merges()
returns a two-column numeric matrix.
cut_at()
returns a numeric vector, the membership vector of the
vertices.
as.dendrogram()
returns a dendrogram object.
show_trace()
returns a character vector.
code_len()
returns a numeric scalar for communities found with the
InfoMAP method and NULL
for other methods.
plot()
for communities
objects returns NULL
, invisibly.
Gabor Csardi [email protected]
See plot_dendrogram()
for plotting community structure
dendrograms.
See compare()
for comparing two community structures
on the same graph.
Community detection
as_membership()
,
cluster_edge_betweenness()
,
cluster_fast_greedy()
,
cluster_fluid_communities()
,
cluster_infomap()
,
cluster_label_prop()
,
cluster_leading_eigen()
,
cluster_leiden()
,
cluster_louvain()
,
cluster_optimal()
,
cluster_spinglass()
,
cluster_walktrap()
,
compare()
,
groups()
,
make_clusters()
,
modularity.igraph()
,
plot_dendrogram()
,
split_join_distance()
,
voronoi_cells()
karate <- make_graph("Zachary") wc <- cluster_walktrap(karate) modularity(wc) membership(wc) plot(wc, karate)
karate <- make_graph("Zachary") wc <- cluster_walktrap(karate) modularity(wc) membership(wc) plot(wc, karate)
Place several graphs on the same layout
merge_coords(graphs, layouts, method = "dla") layout_components(graph, layout = layout_with_kk, ...)
merge_coords(graphs, layouts, method = "dla") layout_components(graph, layout = layout_with_kk, ...)
graphs |
A list of graph objects. |
layouts |
A list of two-column matrices. |
method |
Character constant giving the method to use. Right now only
|
graph |
The input graph. |
layout |
A function object, the layout function to use. |
... |
Additional arguments to pass to the |
merge_coords()
takes a list of graphs and a list of coordinates and
places the graphs in a common layout. The method to use is chosen via the
method
parameter, although right now only the dla
method is
implemented.
The dla
method covers the graph with circles. Then it sorts the
graphs based on the number of vertices first and places the largest graph at
the center of the layout. Then the other graphs are placed in decreasing
order via a DLA (diffision limited aggregation) algorithm: the graph is
placed randomly on a circle far away from the center and a random walk is
conducted until the graph walks into the larger graphs already placed or
walks too far from the center of the layout.
The layout_components()
function disassembles the graph first into
maximal connected components and calls the supplied layout
function
for each component separately. Finally it merges the layouts via calling
merge_coords()
.
A matrix with two columns and as many lines as the total number of vertices in the graphs.
Gabor Csardi [email protected]
plot.igraph()
, tkplot()
,
layout()
, disjoint_union()
Other graph layouts:
add_layout_()
,
component_wise()
,
layout_()
,
layout_as_bipartite()
,
layout_as_star()
,
layout_as_tree()
,
layout_in_circle()
,
layout_nicely()
,
layout_on_grid()
,
layout_on_sphere()
,
layout_randomly()
,
layout_with_dh()
,
layout_with_fr()
,
layout_with_gem()
,
layout_with_graphopt()
,
layout_with_kk()
,
layout_with_lgl()
,
layout_with_mds()
,
layout_with_sugiyama()
,
norm_coords()
,
normalize()
# create 20 scale-free graphs and place them in a common layout graphs <- lapply(sample(5:20, 20, replace = TRUE), barabasi.game, directed = FALSE ) layouts <- lapply(graphs, layout_with_kk) lay <- merge_coords(graphs, layouts) g <- disjoint_union(graphs) plot(g, layout = lay, vertex.size = 3, labels = NA, edge.color = "black")
# create 20 scale-free graphs and place them in a common layout graphs <- lapply(sample(5:20, 20, replace = TRUE), barabasi.game, directed = FALSE ) layouts <- lapply(graphs, layout_with_kk) lay <- merge_coords(graphs, layouts) g <- disjoint_union(graphs) plot(g, layout = lay, vertex.size = 3, labels = NA, edge.color = "black")
min_cut()
calculates the minimum st-cut between two vertices in a graph
(if the source
and target
arguments are given) or the minimum
cut of the graph (if both source
and target
are NULL
).
min_cut( graph, source = NULL, target = NULL, capacity = NULL, value.only = TRUE )
min_cut( graph, source = NULL, target = NULL, capacity = NULL, value.only = TRUE )
graph |
The input graph. |
source |
The id of the source vertex. |
target |
The id of the target vertex (sometimes also called sink). |
capacity |
Vector giving the capacity of the edges. If this is
|
value.only |
Logical scalar, if |
The minimum st-cut between source
and target
is the minimum
total weight of edges needed to remove to eliminate all paths from
source
to target
.
The minimum cut of a graph is the minimum total weight of the edges needed to remove to separate the graph into (at least) two components. (Which is to make the graph not strongly connected in the directed case.)
The maximum flow between two vertices in a graph is the same as the minimum
st-cut, so max_flow()
and min_cut()
essentially calculate the same
quantity, the only difference is that min_cut()
can be invoked without
giving the source
and target
arguments and then minimum of all
possible minimum cuts is calculated.
For undirected graphs the Stoer-Wagner algorithm (see reference below) is used to calculate the minimum cut.
For min_cut()
a nuieric constant, the value of the minimum
cut, except if value.only = FALSE
. In this case a named list with
components:
value |
Numeric scalar, the cut value. |
cut |
Numeric vector, the edges in the cut. |
partition1 |
The vertices in the first partition after the cut edges are removed. Note that these vertices might be actually in different components (after the cut edges are removed), as the graph may fall apart into more than two components. |
partition2 |
The vertices in the second partition after the cut edges are removed. Note that these vertices might be actually in different components (after the cut edges are removed), as the graph may fall apart into more than two components. |
M. Stoer and F. Wagner: A simple min-cut algorithm, Journal of the ACM, 44 585-591, 1997.
Other flow:
dominator_tree()
,
edge_connectivity()
,
is_min_separator()
,
is_separator()
,
max_flow()
,
min_separators()
,
min_st_separators()
,
st_cuts()
,
st_min_cuts()
,
vertex_connectivity()
g <- make_ring(100) min_cut(g, capacity = rep(1, vcount(g))) min_cut(g, value.only = FALSE, capacity = rep(1, vcount(g))) g2 <- make_graph(c(1, 2, 2, 3, 3, 4, 1, 6, 6, 5, 5, 4, 4, 1)) E(g2)$capacity <- c(3, 1, 2, 10, 1, 3, 2) min_cut(g2, value.only = FALSE)
g <- make_ring(100) min_cut(g, capacity = rep(1, vcount(g))) min_cut(g, value.only = FALSE, capacity = rep(1, vcount(g))) g2 <- make_graph(c(1, 2, 2, 3, 3, 4, 1, 6, 6, 5, 5, 4, 4, 1)) E(g2)$capacity <- c(3, 1, 2, 10, 1, 3, 2) min_cut(g2, value.only = FALSE)
Find all vertex sets of minimal size whose removal separates the graph into more components
min_separators(graph)
min_separators(graph)
graph |
The input graph. It may be directed, but edge directions are ignored. |
This function implements the Kanevsky algorithm for finding all minimal-size vertex separators in an undirected graph. See the reference below for the details.
In the special case of a fully connected input graph with vertices,
all subsets of size
are listed as the result.
A list of numeric vectors. Each numeric vector is a vertex separator.
igraph_minimum_size_separators()
.
Arkady Kanevsky: Finding all minimum-size separating vertex sets in a graph. Networks 23 533–541, 1993.
JS Provan and DR Shier: A Paradigm for listing (s,t)-cuts in graphs, Algorithmica 15, 351–372, 1996.
J. Moody and D. R. White. Structural cohesion and embeddedness: A hierarchical concept of social groups. American Sociological Review, 68 103–127, Feb 2003.
Other flow:
dominator_tree()
,
edge_connectivity()
,
is_min_separator()
,
is_separator()
,
max_flow()
,
min_cut()
,
min_st_separators()
,
st_cuts()
,
st_min_cuts()
,
vertex_connectivity()
# The graph from the Moody-White paper mw <- graph_from_literal( 1 - 2:3:4:5:6, 2 - 3:4:5:7, 3 - 4:6:7, 4 - 5:6:7, 5 - 6:7:21, 6 - 7, 7 - 8:11:14:19, 8 - 9:11:14, 9 - 10, 10 - 12:13, 11 - 12:14, 12 - 16, 13 - 16, 14 - 15, 15 - 16, 17 - 18:19:20, 18 - 20:21, 19 - 20:22:23, 20 - 21, 21 - 22:23, 22 - 23 ) # Cohesive subgraphs mw1 <- induced_subgraph(mw, as.character(c(1:7, 17:23))) mw2 <- induced_subgraph(mw, as.character(7:16)) mw3 <- induced_subgraph(mw, as.character(17:23)) mw4 <- induced_subgraph(mw, as.character(c(7, 8, 11, 14))) mw5 <- induced_subgraph(mw, as.character(1:7)) min_separators(mw) min_separators(mw1) min_separators(mw2) min_separators(mw3) min_separators(mw4) min_separators(mw5) # Another example, the science camp network camp <- graph_from_literal( Harry:Steve:Don:Bert - Harry:Steve:Don:Bert, Pam:Brazey:Carol:Pat - Pam:Brazey:Carol:Pat, Holly - Carol:Pat:Pam:Jennie:Bill, Bill - Pauline:Michael:Lee:Holly, Pauline - Bill:Jennie:Ann, Jennie - Holly:Michael:Lee:Ann:Pauline, Michael - Bill:Jennie:Ann:Lee:John, Ann - Michael:Jennie:Pauline, Lee - Michael:Bill:Jennie, Gery - Pat:Steve:Russ:John, Russ - Steve:Bert:Gery:John, John - Gery:Russ:Michael ) min_separators(camp)
# The graph from the Moody-White paper mw <- graph_from_literal( 1 - 2:3:4:5:6, 2 - 3:4:5:7, 3 - 4:6:7, 4 - 5:6:7, 5 - 6:7:21, 6 - 7, 7 - 8:11:14:19, 8 - 9:11:14, 9 - 10, 10 - 12:13, 11 - 12:14, 12 - 16, 13 - 16, 14 - 15, 15 - 16, 17 - 18:19:20, 18 - 20:21, 19 - 20:22:23, 20 - 21, 21 - 22:23, 22 - 23 ) # Cohesive subgraphs mw1 <- induced_subgraph(mw, as.character(c(1:7, 17:23))) mw2 <- induced_subgraph(mw, as.character(7:16)) mw3 <- induced_subgraph(mw, as.character(17:23)) mw4 <- induced_subgraph(mw, as.character(c(7, 8, 11, 14))) mw5 <- induced_subgraph(mw, as.character(1:7)) min_separators(mw) min_separators(mw1) min_separators(mw2) min_separators(mw3) min_separators(mw4) min_separators(mw5) # Another example, the science camp network camp <- graph_from_literal( Harry:Steve:Don:Bert - Harry:Steve:Don:Bert, Pam:Brazey:Carol:Pat - Pam:Brazey:Carol:Pat, Holly - Carol:Pat:Pam:Jennie:Bill, Bill - Pauline:Michael:Lee:Holly, Pauline - Bill:Jennie:Ann, Jennie - Holly:Michael:Lee:Ann:Pauline, Michael - Bill:Jennie:Ann:Lee:John, Ann - Michael:Jennie:Pauline, Lee - Michael:Bill:Jennie, Gery - Pat:Steve:Russ:John, Russ - Steve:Bert:Gery:John, John - Gery:Russ:Michael ) min_separators(camp)
List all vertex sets that are minimal separators for some
and
, in an undirected graph.
min_st_separators(graph)
min_st_separators(graph)
graph |
The input graph. It may be directed, but edge directions are ignored. |
A vertex separator is a set of vertices, such that after their
removal from the graph, there is no path between
and
in the
graph.
A vertex separator is minimal if none of its proper subsets is
an
vertex separator for the same
and
.
A list of numeric vectors. Each vector contains a vertex set
(defined by vertex ids), each vector is an (s,t) separator of the input
graph, for some and
.
Note that the code below returns {1, 3}
despite its subset {1}
being a
separator as well. This is because {1, 3}
is minimal with respect to
separating vertices 2 and 4.
g <- make_graph(~ 0-1-2-3-4-1) min_st_separators(g)
#> [[1]] #> + 1/5 vertex, named: #> [1] 1 #> #> [[2]] #> + 2/5 vertices, named: #> [1] 2 4 #> #> [[3]] #> + 2/5 vertices, named: #> [1] 1 3
igraph_all_minimal_st_separators()
.
Gabor Csardi [email protected]
Anne Berry, Jean-Paul Bordat and Olivier Cogis: Generating All the Minimal Separators of a Graph, In: Peter Widmayer, Gabriele Neyer and Stephan Eidenbenz (editors): Graph-theoretic concepts in computer science, 1665, 167–172, 1999. Springer.
Other flow:
dominator_tree()
,
edge_connectivity()
,
is_min_separator()
,
is_separator()
,
max_flow()
,
min_cut()
,
min_separators()
,
st_cuts()
,
st_min_cuts()
,
vertex_connectivity()
ring <- make_ring(4) min_st_separators(ring) chvatal <- make_graph("chvatal") min_st_separators(chvatal) # https://github.com/r-lib/roxygen2/issues/1092
ring <- make_ring(4) min_st_separators(ring) chvatal <- make_graph("chvatal") min_st_separators(chvatal) # https://github.com/r-lib/roxygen2/issues/1092
This function calculates how modular is a given division of a graph into subgraphs.
## S3 method for class 'igraph' modularity(x, membership, weights = NULL, resolution = 1, directed = TRUE, ...) modularity_matrix( graph, membership = lifecycle::deprecated(), weights = NULL, resolution = 1, directed = TRUE )
## S3 method for class 'igraph' modularity(x, membership, weights = NULL, resolution = 1, directed = TRUE, ...) modularity_matrix( graph, membership = lifecycle::deprecated(), weights = NULL, resolution = 1, directed = TRUE )
x , graph
|
The input graph. |
membership |
Numeric vector, one value for each vertex, the membership vector of the community structure. |
weights |
If not |
resolution |
The resolution parameter. Must be greater than or equal to 0. Set it to 1 to use the classical definition of modularity. |
directed |
Whether to use the directed or undirected version of modularity. Ignored for undirected graphs. |
... |
Additional arguments, none currently. |
modularity()
calculates the modularity of a graph with respect to the
given membership
vector.
The modularity of a graph with respect to some division (or vertex types) measures how good the division is, or how separated are the different vertex types from each other. It defined as
here is the number of edges,
is the element of the
adjacency matrix in row
and column
,
is the degree of
,
is the degree
of
,
is the type (or component) of
,
that of
, the sum goes over all
and
pairs of vertices, and
is 1 if
and 0
otherwise. For directed graphs, it is defined as
The resolution parameter allows weighting the random
null model, which might be useful when finding partitions with a high
modularity. Maximizing modularity with higher values of the resolution
parameter typically results in more, smaller clusters when finding
partitions with a high modularity. Lower values typically results in fewer,
larger clusters. The original definition of modularity is retrieved when
setting
to 1.
If edge weights are given, then these are considered as the element of the
adjacency matrix, and
is the sum of weights of
adjacent edges for vertex
.
modularity_matrix()
calculates the modularity matrix. This is a dense matrix,
and it is defined as the difference of the adjacency matrix and the
configuration model null model matrix. In other words element
is given as
, where
is the (possibly
weighted) adjacency matrix,
is the degree of vertex
,
and
is the number of edges (or the total weights in the graph, if it
is weighed).
For modularity()
a numeric scalar, the modularity score of the
given configuration.
For modularity_matrix()
a numeric square matrix, its order is the number of
vertices in the graph.
Gabor Csardi [email protected]
Clauset, A.; Newman, M. E. J. & Moore, C. Finding community structure in very large networks, Physical Review E 2004, 70, 066111
cluster_walktrap()
,
cluster_edge_betweenness()
,
cluster_fast_greedy()
, cluster_spinglass()
,
cluster_louvain()
and cluster_leiden()
for
various community detection methods.
Community detection
as_membership()
,
cluster_edge_betweenness()
,
cluster_fast_greedy()
,
cluster_fluid_communities()
,
cluster_infomap()
,
cluster_label_prop()
,
cluster_leading_eigen()
,
cluster_leiden()
,
cluster_louvain()
,
cluster_optimal()
,
cluster_spinglass()
,
cluster_walktrap()
,
compare()
,
groups()
,
make_clusters()
,
membership()
,
plot_dendrogram()
,
split_join_distance()
,
voronoi_cells()
g <- make_full_graph(5) %du% make_full_graph(5) %du% make_full_graph(5) g <- add_edges(g, c(1, 6, 1, 11, 6, 11)) wtc <- cluster_walktrap(g) modularity(wtc) modularity(g, membership(wtc))
g <- make_full_graph(5) %du% make_full_graph(5) %du% make_full_graph(5) g <- add_edges(g, c(1, 6, 1, 11, 6, 11)) wtc <- cluster_walktrap(g) modularity(wtc) modularity(g, membership(wtc))
Graph motifs are small connected induced subgraphs with a well-defined structure. These functions search a graph for various motifs.
motifs(graph, size = 3, cut.prob = rep(0, size))
motifs(graph, size = 3, cut.prob = rep(0, size))
graph |
Graph object, the input graph. |
size |
The size of the motif, currently sizes 3 and 4 are supported in directed graphs and sizes 3-6 in undirected graphs. |
cut.prob |
Numeric vector giving the probabilities that the search
graph is cut at a certain level. Its length should be the same as the size
of the motif (the |
motifs()
searches a graph for motifs of a given size and returns a
numeric vector containing the number of different motifs. The order of
the motifs is defined by their isomorphism class, see
isomorphism_class()
.
motifs()
returns a numeric vector, the number of occurrences of
each motif in the graph. The motifs are ordered by their isomorphism
classes. Note that for unconnected subgraphs, which are not considered to be
motifs, the result will be NA
.
Other graph motifs:
count_motifs()
,
dyad_census()
,
sample_motifs()
g <- sample_pa(100) motifs(g, 3) count_motifs(g, 3) sample_motifs(g, 3)
g <- sample_pa(100) motifs(g, 3) count_motifs(g, 3) sample_motifs(g, 3)
A spanning tree of a connected graph is a connected subgraph with the smallest number of edges that includes all vertices of the graph. A graph will have many spanning trees. Among these, the minimum spanning tree will have the smallest sum of edge weights.
mst(graph, weights = NULL, algorithm = NULL, ...)
mst(graph, weights = NULL, algorithm = NULL, ...)
graph |
The graph object to analyze. |
weights |
Numeric vector giving the weights of the edges in the
graph. The order is determined by the edge ids. This is ignored if the
|
algorithm |
The algorithm to use for calculation. |
... |
Additional arguments, unused. |
The minimum spanning forest of a disconnected graph is the collection of minimum spanning trees of all of its components.
If the graph is not connected a minimum spanning forest is returned.
A graph object with the minimum spanning forest. To check whether it
is a tree, check that the number of its edges is vcount(graph)-1
.
The edge and vertex attributes of the original graph are preserved in the
result.
Gabor Csardi [email protected]
Prim, R.C. 1957. Shortest connection networks and some generalizations Bell System Technical Journal, 37 1389–1401.
g <- sample_gnp(100, 3 / 100) g_mst <- mst(g)
g <- sample_gnp(100, 3 / 100) g_mst <- mst(g)
A vertex is a neighbor of another one (in other words, the two vertices are adjacent), if they are incident to the same edge.
neighbors(graph, v, mode = c("out", "in", "all", "total"))
neighbors(graph, v, mode = c("out", "in", "all", "total"))
graph |
The input graph. |
v |
The vertex of which the adjacent vertices are queried. |
mode |
Whether to query outgoing (‘out’), incoming (‘in’) edges, or both types (‘all’). This is ignored for undirected graphs. |
A vertex sequence containing the neighbors of the input vertex.
Other structural queries:
[.igraph()
,
[[.igraph()
,
adjacent_vertices()
,
are_adjacent()
,
ends()
,
get_edge_ids()
,
gorder()
,
gsize()
,
head_of()
,
incident()
,
incident_edges()
,
is_directed()
,
tail_of()
g <- make_graph("Zachary") n1 <- neighbors(g, 1) n34 <- neighbors(g, 34) intersection(n1, n34)
g <- make_graph("Zachary") n1 <- neighbors(g, 1) n34 <- neighbors(g, 34) intersection(n1, n34)
Rescale coordinates linearly to be within given bounds.
norm_coords( layout, xmin = -1, xmax = 1, ymin = -1, ymax = 1, zmin = -1, zmax = 1 )
norm_coords( layout, xmin = -1, xmax = 1, ymin = -1, ymax = 1, zmin = -1, zmax = 1 )
layout |
A matrix with two or three columns, the layout to normalize. |
xmin , xmax
|
The limits for the first coordinate, if one of them or both
are |
ymin , ymax
|
The limits for the second coordinate, if one of them or
both are |
zmin , zmax
|
The limits for the third coordinate, if one of them or both
are |
norm_coords()
normalizes a layout, it linearly transforms each
coordinate separately to fit into the given limits.
A numeric matrix with at the same dimension as layout
.
Gabor Csardi [email protected]
Other graph layouts:
add_layout_()
,
component_wise()
,
layout_()
,
layout_as_bipartite()
,
layout_as_star()
,
layout_as_tree()
,
layout_in_circle()
,
layout_nicely()
,
layout_on_grid()
,
layout_on_sphere()
,
layout_randomly()
,
layout_with_dh()
,
layout_with_fr()
,
layout_with_gem()
,
layout_with_graphopt()
,
layout_with_kk()
,
layout_with_lgl()
,
layout_with_mds()
,
layout_with_sugiyama()
,
merge_coords()
,
normalize()
Scale coordinates of a layout.
normalize( xmin = -1, xmax = 1, ymin = xmin, ymax = xmax, zmin = xmin, zmax = xmax )
normalize( xmin = -1, xmax = 1, ymin = xmin, ymax = xmax, zmin = xmin, zmax = xmax )
xmin , xmax
|
Minimum and maximum for x coordinates. |
ymin , ymax
|
Minimum and maximum for y coordinates. |
zmin , zmax
|
Minimum and maximum for z coordinates. |
Other layout modifiers:
component_wise()
Other graph layouts:
add_layout_()
,
component_wise()
,
layout_()
,
layout_as_bipartite()
,
layout_as_star()
,
layout_as_tree()
,
layout_in_circle()
,
layout_nicely()
,
layout_on_grid()
,
layout_on_sphere()
,
layout_randomly()
,
layout_with_dh()
,
layout_with_fr()
,
layout_with_gem()
,
layout_with_graphopt()
,
layout_with_kk()
,
layout_with_lgl()
,
layout_with_mds()
,
layout_with_sugiyama()
,
merge_coords()
,
norm_coords()
layout_(make_ring(10), with_fr(), normalize())
layout_(make_ring(10), with_fr(), normalize())
Calculates the Google PageRank for the specified vertices.
page_rank( graph, algo = c("prpack", "arpack"), vids = V(graph), directed = TRUE, damping = 0.85, personalized = NULL, weights = NULL, options = NULL )
page_rank( graph, algo = c("prpack", "arpack"), vids = V(graph), directed = TRUE, damping = 0.85, personalized = NULL, weights = NULL, options = NULL )
graph |
The graph object. |
algo |
Character scalar, which implementation to use to carry out the
calculation. The default is |
vids |
The vertices of interest. |
directed |
Logical, if true directed paths will be considered for directed graphs. It is ignored for undirected graphs. |
damping |
The damping factor (‘d’ in the original paper). |
personalized |
Optional vector giving a probability distribution to calculate personalized PageRank. For personalized PageRank, the probability of jumping to a node when abandoning the random walk is not uniform, but it is given by this vector. The vector should contains an entry for each vertex and it will be rescaled to sum up to one. |
weights |
A numerical vector or |
options |
A named list, to override some ARPACK options. See
|
For the explanation of the PageRank algorithm, see the following webpage: http://infolab.stanford.edu/~backrub/google.html, or the following reference:
Sergey Brin and Larry Page: The Anatomy of a Large-Scale Hypertextual Web Search Engine. Proceedings of the 7th World-Wide Web Conference, Brisbane, Australia, April 1998.
The page_rank()
function can use either the PRPACK library or ARPACK
(see arpack()
) to perform the calculation.
Please note that the PageRank of a given vertex depends on the PageRank of all other vertices, so even if you want to calculate the PageRank for only some of the vertices, all of them must be calculated. Requesting the PageRank for only some of the vertices does not result in any performance increase at all.
A named list with entries:
vector |
A numeric vector with the PageRank scores. |
value |
When using the ARPACK method, the eigenvalue corresponding to the eigenvector with the PageRank scores is returned here. It is expected to be exactly one, and can be used to check that ARPACK has successfully converged to the expected eingevector. When using the PRPACK method, it is always set to 1.0. |
options |
Some information
about the underlying ARPACK calculation. See |
igraph_personalized_pagerank()
.
Tamas Nepusz [email protected] and Gabor Csardi [email protected]
Sergey Brin and Larry Page: The Anatomy of a Large-Scale Hypertextual Web Search Engine. Proceedings of the 7th World-Wide Web Conference, Brisbane, Australia, April 1998.
Other centrality scores: closeness()
,
betweenness()
, degree()
Centrality measures
alpha_centrality()
,
authority_score()
,
betweenness()
,
closeness()
,
diversity()
,
eigen_centrality()
,
harmonic_centrality()
,
hits_scores()
,
power_centrality()
,
spectrum()
,
strength()
,
subgraph_centrality()
g <- sample_gnp(20, 5 / 20, directed = TRUE) page_rank(g)$vector g2 <- make_star(10) page_rank(g2)$vector # Personalized PageRank g3 <- make_ring(10) page_rank(g3)$vector reset <- seq(vcount(g3)) page_rank(g3, personalized = reset)$vector
g <- sample_gnp(20, 5 / 20, directed = TRUE) page_rank(g)$vector g2 <- make_star(10) page_rank(g2)$vector # Personalized PageRank g3 <- make_ring(10) page_rank(g3)$vector reset <- seq(vcount(g3)) page_rank(g3, personalized = reset)$vector
This function can be used to add or delete edges that form a path.
path(...)
path(...)
... |
See details below. |
When adding edges via +
, all unnamed arguments are
concatenated, and each element of a final vector is interpreted
as a vertex in the graph. For a vector of length ,
edges are then added, from vertex 1 to vertex 2, from vertex 2 to vertex
3, etc. Named arguments will be used as edge attributes for the new
edges.
When deleting edges, all attributes are concatenated and then passed
to delete_edges()
.
A special object that can be used together with igraph graphs and the plus and minus operators.
Other functions for manipulating graph structure:
+.igraph()
,
add_edges()
,
add_vertices()
,
complementer()
,
compose()
,
connect()
,
contract()
,
delete_edges()
,
delete_vertices()
,
difference()
,
difference.igraph()
,
disjoint_union()
,
edge()
,
igraph-minus
,
intersection()
,
intersection.igraph()
,
permute()
,
rep.igraph()
,
reverse_edges()
,
simplify()
,
union()
,
union.igraph()
,
vertex()
# Create a (directed) wheel g <- make_star(11, center = 1) + path(2:11, 2) plot(g) g <- make_empty_graph(directed = FALSE, n = 10) %>% set_vertex_attr("name", value = letters[1:10]) g2 <- g + path("a", "b", "c", "d") plot(g2) g3 <- g2 + path("e", "f", "g", weight = 1:2, color = "red") E(g3)[[]] g4 <- g3 + path(c("f", "c", "j", "d"), width = 1:3, color = "green") E(g4)[[]]
# Create a (directed) wheel g <- make_star(11, center = 1) + path(2:11, 2) plot(g) g <- make_empty_graph(directed = FALSE, n = 10) %>% set_vertex_attr("name", value = letters[1:10]) g2 <- g + path("a", "b", "c", "d") plot(g2) g3 <- g2 + path("e", "f", "g", weight = 1:2, color = "red") E(g3)[[]] g4 <- g3 + path(c("f", "c", "j", "d"), width = 1:3, color = "green") E(g4)[[]]
Create a new graph, by permuting vertex ids.
permute(graph, permutation)
permute(graph, permutation)
graph |
The input graph, it can directed or undirected. |
permutation |
A numeric vector giving the permutation to apply. The
first element is the new id of vertex 1, etc. Every number between one and
|
This function creates a new graph from the input graph by permuting its
vertices according to the specified mapping. Call this function with the
output of canonical_permutation()
to create the canonical form
of a graph.
permute()
keeps all graph, vertex and edge attributes of the graph.
A new graph object.
Gabor Csardi [email protected]
Other functions for manipulating graph structure:
+.igraph()
,
add_edges()
,
add_vertices()
,
complementer()
,
compose()
,
connect()
,
contract()
,
delete_edges()
,
delete_vertices()
,
difference()
,
difference.igraph()
,
disjoint_union()
,
edge()
,
igraph-minus
,
intersection()
,
intersection.igraph()
,
path()
,
rep.igraph()
,
reverse_edges()
,
simplify()
,
union()
,
union.igraph()
,
vertex()
# Random permutation of a random graph g <- sample_gnm(20, 50) g2 <- permute(g, sample(vcount(g))) graph.isomorphic(g, g2) # Permutation keeps all attributes g$name <- "Random graph, Gnm, 20, 50" V(g)$name <- letters[1:vcount(g)] E(g)$weight <- sample(1:5, ecount(g), replace = TRUE) g2 <- permute(g, sample(vcount(g))) graph.isomorphic(g, g2) g2$name V(g2)$name E(g2)$weight all(sort(E(g2)$weight) == sort(E(g)$weight))
# Random permutation of a random graph g <- sample_gnm(20, 50) g2 <- permute(g, sample(vcount(g))) graph.isomorphic(g, g2) # Permutation keeps all attributes g$name <- "Random graph, Gnm, 20, 50" V(g)$name <- letters[1:vcount(g)] E(g)$weight <- sample(1:5, ecount(g), replace = TRUE) g2 <- permute(g, sample(vcount(g))) graph.isomorphic(g, g2) g2$name V(g2)$name E(g2)$weight all(sort(E(g2)$weight) == sort(E(g)$weight))
More complex vertex images can be used to express addtional information about vertices. E.g. pie charts can be used as vertices, to denote vertex classes, fuzzy classification of vertices, etc.
The vertex shape ‘pie’ makes igraph draw a pie chart for every vertex. There are some extra graphical vertex parameters that specify how the pie charts will look like:
Numeric vector, gives the sizes of the pie slices.
A list of color vectors to use for the pies. If it is a list of a single vector, then this is used for all pies. It the color vector is shorter than the number of areas in a pie, then it is recycled.
The slope of shading lines, given as an angle in degrees (counter-clockwise).
The density of the shading lines, in lines per inch. Non-positive values inhibit the drawing of shading lines.
The line type of the border of the slices.
Gabor Csardi [email protected]
g <- make_ring(10) values <- lapply(1:10, function(x) sample(1:10,3)) if (interactive()) { plot(g, vertex.shape="pie", vertex.pie=values, vertex.pie.color=list(heat.colors(5)), vertex.size=seq(10,30,length.out=10), vertex.label=NA) }
g <- make_ring(10) values <- lapply(1:10, function(x) sample(1:10,3)) if (interactive()) { plot(g, vertex.shape="pie", vertex.pie=values, vertex.pie.color=list(heat.colors(5)), vertex.size=seq(10,30,length.out=10), vertex.label=NA) }
Plot a hierarchical community structure as a dendrogram.
plot_dendrogram(x, mode = igraph_opt("dend.plot.type"), ...) ## S3 method for class 'communities' plot_dendrogram( x, mode = igraph_opt("dend.plot.type"), ..., use.modularity = FALSE, palette = categorical_pal(8) )
plot_dendrogram(x, mode = igraph_opt("dend.plot.type"), ...) ## S3 method for class 'communities' plot_dendrogram( x, mode = igraph_opt("dend.plot.type"), ..., use.modularity = FALSE, palette = categorical_pal(8) )
x |
An object containing the community structure of a graph. See
|
mode |
Which dendrogram plotting function to use. See details below. |
... |
Additional arguments to supply to the dendrogram plotting function. |
use.modularity |
Logical scalar, whether to use the modularity values to define the height of the branches. |
palette |
The color palette to use for colored plots. |
plot_dendrogram()
supports three different plotting functions, selected via
the mode
argument. By default the plotting function is taken from the
dend.plot.type
igraph option, and it has for possible values:
auto
Choose automatically between the plotting
functions. As plot.phylo
is the most sophisticated, that is choosen,
whenever the ape
package is available. Otherwise plot.hclust
is used.
phylo
Use plot.phylo
from the ape
package.
hclust
Use plot.hclust
from the stats
package.
dendrogram
Use plot.dendrogram
from the
stats
package.
The different plotting functions take different sets of arguments. When
using plot.phylo
(mode="phylo"
), we have the following syntax:
plot_dendrogram(x, mode="phylo", colbar = palette(), edge.color = NULL, use.edge.length = FALSE, \dots)
The extra arguments not documented above:
colbar
Color bar for the edges.
edge.color
Edge colors. If NULL
, then the
colbar
argument is used.
use.edge.length
Passed to plot.phylo
.
dots
Attitional arguments to pass to plot.phylo
.
The syntax for plot.hclust
(mode="hclust"
):
plot_dendrogram(x, mode="hclust", rect = 0, colbar = palette(), hang = 0.01, ann = FALSE, main = "", sub = "", xlab = "", ylab = "", \dots)
The extra arguments not documented above:
rect
A numeric scalar, the number of groups to mark on
the dendrogram. The dendrogram is cut into exactly rect
groups and they are marked via the rect.hclust
command. Set
this to zero if you don't want to mark any groups.
colbar
The colors of the rectangles that mark the
vertex groups via the rect
argument.
hang
Where to put the leaf nodes, this corresponds to the
hang
argument of plot.hclust
.
ann
Whether to annotate the plot, the ann
argument of plot.hclust
.
main
The main title of the plot, the main
argument
of plot.hclust
.
sub
The sub-title of the plot, the sub
argument of
plot.hclust
.
xlab
The label on the horizontal axis, passed to
plot.hclust
.
ylab
The label on the vertical axis, passed to
plot.hclust
.
dots
Attitional arguments to pass to plot.hclust
.
The syntax for plot.dendrogram
(mode="dendrogram"
):
plot_dendrogram(x, \dots)
The extra arguments are simply passed to as.dendrogram()
.
Returns whatever the return value was from the plotting function,
plot.phylo
, plot.dendrogram
or plot.hclust
.
Gabor Csardi [email protected]
Community detection
as_membership()
,
cluster_edge_betweenness()
,
cluster_fast_greedy()
,
cluster_fluid_communities()
,
cluster_infomap()
,
cluster_label_prop()
,
cluster_leading_eigen()
,
cluster_leiden()
,
cluster_louvain()
,
cluster_optimal()
,
cluster_spinglass()
,
cluster_walktrap()
,
compare()
,
groups()
,
make_clusters()
,
membership()
,
modularity.igraph()
,
split_join_distance()
,
voronoi_cells()
karate <- make_graph("Zachary") fc <- cluster_fast_greedy(karate) plot_dendrogram(fc)
karate <- make_graph("Zachary") fc <- cluster_fast_greedy(karate) plot_dendrogram(fc)
Plot a hierarchical random graph as a dendrogram.
## S3 method for class 'igraphHRG' plot_dendrogram(x, mode = igraph_opt("dend.plot.type"), ...)
## S3 method for class 'igraphHRG' plot_dendrogram(x, mode = igraph_opt("dend.plot.type"), ...)
x |
An |
mode |
Which dendrogram plotting function to use. See details below. |
... |
Additional arguments to supply to the dendrogram plotting function. |
plot_dendrogram()
supports three different plotting functions, selected via
the mode
argument. By default the plotting function is taken from the
dend.plot.type
igraph option, and it has for possible values:
auto
Choose automatically between the plotting
functions. As plot.phylo
is the most sophisticated, that is choosen,
whenever the ape
package is available. Otherwise plot.hclust
is used.
phylo
Use plot.phylo
from the ape
package.
hclust
Use plot.hclust
from the stats
package.
dendrogram
Use plot.dendrogram
from the
stats
package.
The different plotting functions take different sets of arguments. When
using plot.phylo
(mode="phylo"
), we have the following syntax:
plot_dendrogram(x, mode="phylo", colbar = rainbow(11, start=0.7, end=0.1), edge.color = NULL, use.edge.length = FALSE, \dots)
The extra arguments not documented above:
colbar
Color bar for the edges.
edge.color
Edge colors. If NULL
, then the
colbar
argument is used.
use.edge.length
Passed to plot.phylo
.
dots
Attitional arguments to pass to plot.phylo
.
The syntax for plot.hclust
(mode="hclust"
):
plot_dendrogram(x, mode="hclust", rect = 0, colbar = rainbow(rect), hang = 0.01, ann = FALSE, main = "", sub = "", xlab = "", ylab = "", \dots)
The extra arguments not documented above:
rect
A numeric scalar, the number of groups to mark on
the dendrogram. The dendrogram is cut into exactly rect
groups and they are marked via the rect.hclust
command. Set
this to zero if you don't want to mark any groups.
colbar
The colors of the rectangles that mark the
vertex groups via the rect
argument.
hang
Where to put the leaf nodes, this corresponds to the
hang
argument of plot.hclust
.
ann
Whether to annotate the plot, the ann
argument
of plot.hclust
.
main
The main title of the plot, the main
argument
of plot.hclust
.
sub
The sub-title of the plot, the sub
argument of
plot.hclust
.
xlab
The label on the horizontal axis, passed to
plot.hclust
.
ylab
The label on the vertical axis, passed to
plot.hclust
.
dots
Attitional arguments to pass to plot.hclust
.
The syntax for plot.dendrogram
(mode="dendrogram"
):
plot_dendrogram(x, \dots)
The extra arguments are simply passed to as.dendrogram()
.
Returns whatever the return value was from the plotting function,
plot.phylo
, plot.dendrogram
or plot.hclust
.
Gabor Csardi [email protected]
g <- make_full_graph(5) + make_full_graph(5) hrg <- fit_hrg(g) plot_dendrogram(hrg)
g <- make_full_graph(5) + make_full_graph(5) hrg <- fit_hrg(g) plot_dendrogram(hrg)
plot.igraph()
is able to plot graphs to any R device. It is the
non-interactive companion of the tkplot()
function.
## S3 method for class 'igraph' plot( x, axes = FALSE, add = FALSE, xlim = c(-1, 1), ylim = c(-1, 1), mark.groups = list(), mark.shape = 1/2, mark.col = rainbow(length(mark.groups), alpha = 0.3), mark.border = rainbow(length(mark.groups), alpha = 1), mark.expand = 15, loop.size = 1, ... )
## S3 method for class 'igraph' plot( x, axes = FALSE, add = FALSE, xlim = c(-1, 1), ylim = c(-1, 1), mark.groups = list(), mark.shape = 1/2, mark.col = rainbow(length(mark.groups), alpha = 0.3), mark.border = rainbow(length(mark.groups), alpha = 1), mark.expand = 15, loop.size = 1, ... )
x |
The graph to plot. |
axes |
Logical, whether to plot axes, defaults to FALSE. |
add |
Logical scalar, whether to add the plot to the current device, or delete the device's current contents first. |
xlim |
The limits for the horizontal axis, it is unlikely that you want to modify this. |
ylim |
The limits for the vertical axis, it is unlikely that you want to modify this. |
mark.groups |
A list of vertex id vectors. It is interpreted as a set of vertex groups. Each vertex group is highlighted, by plotting a colored smoothed polygon around and “under” it. See the arguments below to control the look of the polygons. |
mark.shape |
A numeric scalar or vector. Controls the smoothness of the
vertex group marking polygons. This is basically the ‘shape’
parameter of the |
mark.col |
A scalar or vector giving the colors of marking the
polygons, in any format accepted by |
mark.border |
A scalar or vector giving the colors of the borders of
the vertex group marking polygons. If it is |
mark.expand |
A numeric scalar or vector, the size of the border around the marked vertex groups. It is in the same units as the vertex sizes. If a vector is given, then different values are used for the different vertex groups. |
loop.size |
A numeric scalar that allows the user to scale the loop edges of the network. The default loop size is 1. Larger values will produce larger loops. |
... |
Additional plotting parameters. See igraph.plotting for the complete list. |
One convenient way to plot graphs is to plot with tkplot()
first, handtune the placement of the vertices, query the coordinates by the
tk_coords()
function and use them with plot()
to
plot the graph to any R device.
Returns NULL
, invisibly.
Gabor Csardi [email protected]
layout()
for different layouts,
igraph.plotting for the detailed description of the plotting
parameters and tkplot()
and rglplot()
for other
graph plotting functions.
Other plot:
rglplot()
g <- make_ring(10) plot(g, layout = layout_with_kk, vertex.color = "green")
g <- make_ring(10) plot(g, layout = layout_with_kk, vertex.color = "green")
This function can conveniently plot the results of multiple SIR model simulations.
## S3 method for class 'sir' plot( x, comp = c("NI", "NS", "NR"), median = TRUE, quantiles = c(0.1, 0.9), color = NULL, median_color = NULL, quantile_color = NULL, lwd.median = 2, lwd.quantile = 2, lty.quantile = 3, xlim = NULL, ylim = NULL, xlab = "Time", ylab = NULL, ... )
## S3 method for class 'sir' plot( x, comp = c("NI", "NS", "NR"), median = TRUE, quantiles = c(0.1, 0.9), color = NULL, median_color = NULL, quantile_color = NULL, lwd.median = 2, lwd.quantile = 2, lty.quantile = 3, xlim = NULL, ylim = NULL, xlab = "Time", ylab = NULL, ... )
x |
The output of the SIR simulation, coming from the |
comp |
Character scalar, which component to plot. Either ‘NI’ (infected, default), ‘NS’ (susceptible) or ‘NR’ (recovered). |
median |
Logical scalar, whether to plot the (binned) median. |
quantiles |
A vector of (binned) quantiles to plot. |
color |
Color of the individual simulation curves. |
median_color |
Color of the median curve. |
quantile_color |
Color(s) of the quantile curves. (It is recycled if needed and non-needed entries are ignored if too long.) |
lwd.median |
Line width of the median. |
lwd.quantile |
Line width of the quantile curves. |
lty.quantile |
Line type of the quantile curves. |
xlim |
The x limits, a two-element numeric vector. If |
ylim |
The y limits, a two-element numeric vector. If |
xlab |
The x label. |
ylab |
The y label. If |
... |
Additional arguments are passed to |
The number of susceptible/infected/recovered individuals is plotted over time, for multiple simulations.
Nothing.
Eric Kolaczyk (http://math.bu.edu/people/kolaczyk/) and Gabor Csardi [email protected].
Bailey, Norman T. J. (1975). The mathematical theory of infectious diseases and its applications (2nd ed.). London: Griffin.
sir()
for running the actual simulation.
Processes on graphs
time_bins()
g <- sample_gnm(100, 100) sm <- sir(g, beta = 5, gamma = 1) plot(sm)
g <- sample_gnm(100, 100) sm <- sir(g, beta = 5, gamma = 1) plot(sm)
power_centrality()
takes a graph (dat
) and returns the Boncich power
centralities of positions (selected by nodes
). The decay rate for
power contributions is specified by exponent
(1 by default).
power_centrality( graph, nodes = V(graph), loops = FALSE, exponent = 1, rescale = FALSE, tol = 1e-07, sparse = TRUE )
power_centrality( graph, nodes = V(graph), loops = FALSE, exponent = 1, rescale = FALSE, tol = 1e-07, sparse = TRUE )
graph |
the input graph. |
nodes |
vertex sequence indicating which vertices are to be included in the calculation. By default, all vertices are included. |
loops |
boolean indicating whether or not the diagonal should be
treated as valid data. Set this true if and only if the data can contain
loops. |
exponent |
exponent (decay rate) for the Bonacich power centrality score; can be negative |
rescale |
if true, centrality scores are rescaled such that they sum to 1. |
tol |
tolerance for near-singularities during matrix inversion (see
|
sparse |
Logical scalar, whether to use sparse matrices for the calculation. The ‘Matrix’ package is required for sparse matrix support |
Bonacich's power centrality measure is defined by
, where
is an attenuation parameter (set
here by
exponent
) and is the graph adjacency
matrix. (The coefficient
acts as a scaling parameter,
and is set here (following Bonacich (1987)) such that the sum of squared
scores is equal to the number of vertices. This allows 1 to be used as a
reference value for the “middle” of the centrality range.) When
(the reciprocal of the largest
eigenvalue of
), this is to within a constant multiple of
the familiar eigenvector centrality score; for other values of
,
the behavior of the measure is quite different. In particular,
gives positive and negative weight to even and odd walks, respectively, as
can be seen from the series expansion
which converges so long as
.
The magnitude of
controls the influence of distant actors
on ego's centrality score, with larger magnitudes indicating slower rates of
decay. (High rates, hence, imply a greater sensitivity to edge effects.)
Interpretively, the Bonacich power measure corresponds to the notion that the power of a vertex is recursively defined by the sum of the power of its alters. The nature of the recursion involved is then controlled by the power exponent: positive values imply that vertices become more powerful as their alters become more powerful (as occurs in cooperative relations), while negative values imply that vertices become more powerful only as their alters become weaker (as occurs in competitive or antagonistic relations). The magnitude of the exponent indicates the tendency of the effect to decay across long walks; higher magnitudes imply slower decay. One interesting feature of this measure is its relative instability to changes in exponent magnitude (particularly in the negative case). If your theory motivates use of this measure, you should be very careful to choose a decay parameter on a non-ad hoc basis.
For directed networks, the Bonacich power measure can be understood as similar to status in the network where higher status nodes have more edges that point from them to others with status. Node A's centrality depends on the centrality of all the nodes that A points toward, and their centrality depends on the nodes they point toward, etc. Note, this means that a node with an out-degree of 0 will have a Bonacich power centrality of 0 as they do not point towards anyone. When using this with directed network it is important to think about the edge direction and what it represents.
A vector, containing the centrality scores.
Singular adjacency matrices cause no end of headaches for this algorithm; thus, the routine may fail in certain cases. This will be fixed when we get a better algorithm.
This function was ported (i.e. copied) from the SNA package.
Carter T. Butts (http://www.faculty.uci.edu/profile.cfm?faculty_id=5057), ported to igraph by Gabor Csardi [email protected]
Bonacich, P. (1972). “Factoring and Weighting Approaches to Status Scores and Clique Identification.” Journal of Mathematical Sociology, 2, 113-120.
Bonacich, P. (1987). “Power and Centrality: A Family of Measures.” American Journal of Sociology, 92, 1170-1182.
eigen_centrality()
and alpha_centrality()
Centrality measures
alpha_centrality()
,
authority_score()
,
betweenness()
,
closeness()
,
diversity()
,
eigen_centrality()
,
harmonic_centrality()
,
hits_scores()
,
page_rank()
,
spectrum()
,
strength()
,
subgraph_centrality()
# Generate some test data from Bonacich, 1987: g.c <- make_graph(c(1, 2, 1, 3, 2, 4, 3, 5), dir = FALSE) g.d <- make_graph(c(1, 2, 1, 3, 1, 4, 2, 5, 3, 6, 4, 7), dir = FALSE) g.e <- make_graph(c(1, 2, 1, 3, 1, 4, 2, 5, 2, 6, 3, 7, 3, 8, 4, 9, 4, 10), dir = FALSE) g.f <- make_graph( c(1, 2, 1, 3, 1, 4, 2, 5, 2, 6, 2, 7, 3, 8, 3, 9, 3, 10, 4, 11, 4, 12, 4, 13), dir = FALSE ) # Compute power centrality scores for (e in seq(-0.5, .5, by = 0.1)) { print(round(power_centrality(g.c, exp = e)[c(1, 2, 4)], 2)) } for (e in seq(-0.4, .4, by = 0.1)) { print(round(power_centrality(g.d, exp = e)[c(1, 2, 5)], 2)) } for (e in seq(-0.4, .4, by = 0.1)) { print(round(power_centrality(g.e, exp = e)[c(1, 2, 5)], 2)) } for (e in seq(-0.4, .4, by = 0.1)) { print(round(power_centrality(g.f, exp = e)[c(1, 2, 5)], 2)) }
# Generate some test data from Bonacich, 1987: g.c <- make_graph(c(1, 2, 1, 3, 2, 4, 3, 5), dir = FALSE) g.d <- make_graph(c(1, 2, 1, 3, 1, 4, 2, 5, 3, 6, 4, 7), dir = FALSE) g.e <- make_graph(c(1, 2, 1, 3, 1, 4, 2, 5, 2, 6, 3, 7, 3, 8, 4, 9, 4, 10), dir = FALSE) g.f <- make_graph( c(1, 2, 1, 3, 1, 4, 2, 5, 2, 6, 2, 7, 3, 8, 3, 9, 3, 10, 4, 11, 4, 12, 4, 13), dir = FALSE ) # Compute power centrality scores for (e in seq(-0.5, .5, by = 0.1)) { print(round(power_centrality(g.c, exp = e)[c(1, 2, 4)], 2)) } for (e in seq(-0.4, .4, by = 0.1)) { print(round(power_centrality(g.d, exp = e)[c(1, 2, 5)], 2)) } for (e in seq(-0.4, .4, by = 0.1)) { print(round(power_centrality(g.e, exp = e)[c(1, 2, 5)], 2)) } for (e in seq(-0.4, .4, by = 0.1)) { print(round(power_centrality(g.f, exp = e)[c(1, 2, 5)], 2)) }
predict_edges()
uses a hierarchical random graph model to predict
missing edges from a network. This is done by sampling hierarchical models
around the optimum model, proportionally to their likelihood. The MCMC
sampling is stated from hrg()
, if it is given and the start
argument is set to TRUE
. Otherwise a HRG is fitted to the graph
first.
predict_edges( graph, hrg = NULL, start = FALSE, num.samples = 10000, num.bins = 25 )
predict_edges( graph, hrg = NULL, start = FALSE, num.samples = 10000, num.bins = 25 )
graph |
The graph to fit the model to. Edge directions are ignored in directed graphs. |
hrg |
A hierarchical random graph model, in the form of an
|
start |
Logical, whether to start the fitting/sampling from the
supplied |
num.samples |
Number of samples to use for consensus generation or missing edge prediction. |
num.bins |
Number of bins for the edge probabilities. Give a higher number for a more accurate prediction. |
A list with entries:
edges |
The predicted edges, in a two-column matrix of vertex ids. |
prob |
Probabilities of these edges, according to the fitted model. |
hrg |
The (supplied or fitted) hierarchical random graph model. |
A. Clauset, C. Moore, and M.E.J. Newman. Hierarchical structure and the prediction of missing links in networks. Nature 453, 98–101 (2008);
A. Clauset, C. Moore, and M.E.J. Newman. Structural Inference of Hierarchies in Networks. In E. M. Airoldi et al. (Eds.): ICML 2006 Ws, Lecture Notes in Computer Science 4503, 1–13. Springer-Verlag, Berlin Heidelberg (2007).
Other hierarchical random graph functions:
consensus_tree()
,
fit_hrg()
,
hrg()
,
hrg-methods
,
hrg_tree()
,
print.igraphHRG()
,
print.igraphHRGConsensus()
,
sample_hrg()
## A graph with two dense groups g <- sample_gnp(10, p = 1 / 2) + sample_gnp(10, p = 1 / 2) hrg <- fit_hrg(g) hrg ## The consensus tree for it consensus_tree(g, hrg = hrg, start = TRUE) ## Prediction of missing edges g2 <- make_full_graph(4) + (make_full_graph(4) - path(1, 2)) predict_edges(g2)
## A graph with two dense groups g <- sample_gnp(10, p = 1 / 2) + sample_gnp(10, p = 1 / 2) hrg <- fit_hrg(g) hrg ## The consensus tree for it consensus_tree(g, hrg = hrg, start = TRUE) ## Prediction of missing edges g2 <- make_full_graph(4) + (make_full_graph(4) - path(1, 2)) predict_edges(g2)
These functions attempt to print a graph to the terminal in a human readable form.
## S3 method for class 'igraph' print( x, full = igraph_opt("print.full"), graph.attributes = igraph_opt("print.graph.attributes"), vertex.attributes = igraph_opt("print.vertex.attributes"), edge.attributes = igraph_opt("print.edge.attributes"), names = TRUE, max.lines = igraph_opt("auto.print.lines"), id = igraph_opt("print.id"), ... ) ## S3 method for class 'igraph' summary(object, ...)
## S3 method for class 'igraph' print( x, full = igraph_opt("print.full"), graph.attributes = igraph_opt("print.graph.attributes"), vertex.attributes = igraph_opt("print.vertex.attributes"), edge.attributes = igraph_opt("print.edge.attributes"), names = TRUE, max.lines = igraph_opt("auto.print.lines"), id = igraph_opt("print.id"), ... ) ## S3 method for class 'igraph' summary(object, ...)
x |
The graph to print. |
full |
Logical scalar, whether to print the graph structure itself as well. |
graph.attributes |
Logical constant, whether to print graph attributes. |
vertex.attributes |
Logical constant, whether to print vertex attributes. |
edge.attributes |
Logical constant, whether to print edge attributes. |
names |
Logical constant, whether to print symbolic vertex names (i.e.
the |
max.lines |
The maximum number of lines to use. The rest of the output will be truncated. |
id |
Whether to print the graph ID. |
... |
Additional agruments. |
object |
The graph of which the summary will be printed. |
summary.igraph
prints the number of vertices, edges and whether the
graph is directed.
print_all()
prints the same information, and also lists the edges, and
optionally graph, vertex and/or edge attributes.
print.igraph()
behaves either as summary.igraph
or
print_all()
depending on the full
argument. See also the
‘print.full’ igraph option and igraph_opt()
.
The graph summary printed by summary.igraph
(and print.igraph()
and print_all()
) consists of one or more lines. The first line contains
the basic properties of the graph, and the rest contains its attributes.
Here is an example, a small star graph with weighted directed edges and named
vertices:
IGRAPH badcafe DNW- 10 9 -- In-star + attr: name (g/c), mode (g/c), center (g/n), name (v/c), weight (e/n)
The first line always
starts with IGRAPH
, showing you that the object is an igraph graph.
Then a seven character code is printed, this the first seven characters
of the unique id of the graph. See graph_id()
for more.
Then a four letter long code string is printed. The first letter
distinguishes between directed (‘D
’) and undirected
(‘U
’) graphs. The second letter is ‘N
’ for named
graphs, i.e. graphs with the name
vertex attribute set. The third
letter is ‘W
’ for weighted graphs, i.e. graphs with the
weight
edge attribute set. The fourth letter is ‘B
’ for
bipartite graphs, i.e. for graphs with the type
vertex attribute set.
This is followed by the number of vertices and edges, then two dashes.
Finally, after two dashes, the name of the graph is printed, if it has one,
i.e. if the name
graph attribute is set.
From the second line, the attributes of the graph are listed, separated by a
comma. After the attribute names, the kind of the attribute – graph
(‘g
’), vertex (‘v
’) or edge (‘e
’)
– is denoted, and the type of the attribute as well, character
(‘c
’), numeric (‘n
’), logical
(‘l
’), or other (‘x
’).
As of igraph 0.4 print_all()
and print.igraph()
use the
max.print
option, see base::options()
for details.
As of igraph 1.1.1, the str.igraph
function is defunct, use
print_all()
.
All these functions return the graph invisibly.
Gabor Csardi [email protected]
g <- make_ring(10) g summary(g)
g <- make_ring(10) g summary(g)
For long edge sequences, the printing is truncated to fit to the
screen. Use print()
explicitly and the full
argument to
see the full sequence.
## S3 method for class 'igraph.es' print(x, full = igraph_opt("print.full"), id = igraph_opt("print.id"), ...)
## S3 method for class 'igraph.es' print(x, full = igraph_opt("print.full"), id = igraph_opt("print.id"), ...)
x |
An edge sequence. |
full |
Whether to show the full sequence, or truncate the output to the screen size. |
id |
Whether to print the graph ID. |
... |
Currently ignored. |
Edge sequences created with the double bracket operator are printed differently, together with all attributes of the edges in the sequence, as a table.
The edge sequence, invisibly.
Other vertex and edge sequences:
E()
,
V()
,
as_ids()
,
igraph-es-attributes
,
igraph-es-indexing
,
igraph-es-indexing2
,
igraph-vs-attributes
,
igraph-vs-indexing
,
igraph-vs-indexing2
,
print.igraph.vs()
# Unnamed graphs g <- make_ring(10) E(g) # Named graphs g2 <- make_ring(10) %>% set_vertex_attr("name", value = LETTERS[1:10]) E(g2) # All edges in a long sequence g3 <- make_ring(200) E(g3) E(g3) %>% print(full = TRUE) # Metadata g4 <- make_ring(10) %>% set_vertex_attr("name", value = LETTERS[1:10]) %>% set_edge_attr("weight", value = 1:10) %>% set_edge_attr("color", value = "green") E(g4) E(g4)[[]] E(g4)[[1:5]]
# Unnamed graphs g <- make_ring(10) E(g) # Named graphs g2 <- make_ring(10) %>% set_vertex_attr("name", value = LETTERS[1:10]) E(g2) # All edges in a long sequence g3 <- make_ring(200) E(g3) E(g3) %>% print(full = TRUE) # Metadata g4 <- make_ring(10) %>% set_vertex_attr("name", value = LETTERS[1:10]) %>% set_edge_attr("weight", value = 1:10) %>% set_edge_attr("color", value = "green") E(g4) E(g4)[[]] E(g4)[[1:5]]
For long vertex sequences, the printing is truncated to fit to the
screen. Use print()
explicitly and the full
argument to
see the full sequence.
## S3 method for class 'igraph.vs' print(x, full = igraph_opt("print.full"), id = igraph_opt("print.id"), ...)
## S3 method for class 'igraph.vs' print(x, full = igraph_opt("print.full"), id = igraph_opt("print.id"), ...)
x |
A vertex sequence. |
full |
Whether to show the full sequence, or truncate the output to the screen size. |
id |
Whether to print the graph ID. |
... |
These arguments are currently ignored. |
Vertex sequence created with the double bracket operator are printed differently, together with all attributes of the vertices in the sequence, as a table.
The vertex sequence, invisibly.
Other vertex and edge sequences:
E()
,
V()
,
as_ids()
,
igraph-es-attributes
,
igraph-es-indexing
,
igraph-es-indexing2
,
igraph-vs-attributes
,
igraph-vs-indexing
,
igraph-vs-indexing2
,
print.igraph.es()
# Unnamed graphs g <- make_ring(10) V(g) # Named graphs g2 <- make_ring(10) %>% set_vertex_attr("name", value = LETTERS[1:10]) V(g2) # All vertices in the sequence g3 <- make_ring(1000) V(g3) print(V(g3), full = TRUE) # Metadata g4 <- make_ring(10) %>% set_vertex_attr("name", value = LETTERS[1:10]) %>% set_vertex_attr("color", value = "red") V(g4)[[]] V(g4)[[2:5, 7:8]]
# Unnamed graphs g <- make_ring(10) V(g) # Named graphs g2 <- make_ring(10) %>% set_vertex_attr("name", value = LETTERS[1:10]) V(g2) # All vertices in the sequence g3 <- make_ring(1000) V(g3) print(V(g3), full = TRUE) # Metadata g4 <- make_ring(10) %>% set_vertex_attr("name", value = LETTERS[1:10]) %>% set_vertex_attr("color", value = "red") V(g4)[[]] V(g4)[[2:5, 7:8]]
igraphHRG
objects can be printed to the screen in two forms: as
a tree or as a list, depending on the type
argument of the
print function. By default the auto
type is used, which selects
tree
for small graphs and simple
(=list) for bigger
ones. The tree
format looks like
this:
Hierarchical random graph, at level 3: g1 p= 0 '- g15 p=0.33 1 '- g13 p=0.88 6 3 9 4 2 10 7 5 8 '- g8 p= 0.5 '- g16 p= 0.2 20 14 17 19 11 15 16 13 '- g5 p= 0 12 18
This is a graph with 20 vertices, and the
top three levels of the fitted hierarchical random graph are
printed. The root node of the HRG is always vertex group #1
(‘g1
’ in the the printout). Vertex pairs in the left
subtree of g1
connect to vertices in the right subtree with
probability zero, according to the fitted model. g1
has two
subgroups, g15
and g8
. g15
has a subgroup of a
single vertex (vertex 1), and another larger subgroup that contains
vertices 6, 3, etc. on lower levels, etc.
The plain
printing is simpler and faster to produce, but less
visual:
Hierarchical random graph: g1 p=0.0 -> g12 g10 g2 p=1.0 -> 7 10 g3 p=1.0 -> g18 14 g4 p=1.0 -> g17 15 g5 p=0.4 -> g15 17 g6 p=0.0 -> 1 4 g7 p=1.0 -> 11 16 g8 p=0.1 -> g9 3 g9 p=0.3 -> g11 g16 g10 p=0.2 -> g4 g5 g11 p=1.0 -> g6 5 g12 p=0.8 -> g8 8 g13 p=0.0 -> g14 9 g14 p=1.0 -> 2 6 g15 p=0.2 -> g19 18 g16 p=1.0 -> g13 g2 g17 p=0.5 -> g7 13 g18 p=1.0 -> 12 19 g19 p=0.7 -> g3 20
It lists the two subgroups of each internal node, in as many columns as the screen width allows.
## S3 method for class 'igraphHRG' print(x, type = c("auto", "tree", "plain"), level = 3, ...)
## S3 method for class 'igraphHRG' print(x, type = c("auto", "tree", "plain"), level = 3, ...)
x |
|
type |
How to print the dendrogram, see details below. |
level |
The number of top levels to print from the dendrogram. |
... |
Additional arguments, not used currently. |
The hierarchical random graph model itself, invisibly.
Other hierarchical random graph functions:
consensus_tree()
,
fit_hrg()
,
hrg()
,
hrg-methods
,
hrg_tree()
,
predict_edges()
,
print.igraphHRGConsensus()
,
sample_hrg()
Consensus dendrograms (igraphHRGConsensus
objects) are printed
simply by listing the children of each internal node of the
dendrogram:
HRG consensus tree: g1 -> 11 12 13 14 15 16 17 18 19 20 g2 -> 1 2 3 4 5 6 7 8 9 10 g3 -> g1 g2
The root of the dendrogram is g3
(because it has no incoming
edges), and it has two subgroups, g1
and g2
.
## S3 method for class 'igraphHRGConsensus' print(x, ...)
## S3 method for class 'igraphHRGConsensus' print(x, ...)
x |
|
... |
Ignored. |
The input object, invisibly, to allow method chaining.
Other hierarchical random graph functions:
consensus_tree()
,
fit_hrg()
,
hrg()
,
hrg-methods
,
hrg_tree()
,
predict_edges()
,
print.igraphHRG()
,
sample_hrg()
A printer callback function is a function can performs the actual
printing. It has a number of subcommands, that are called by
the printer
package, in a form
printer_callback("subcommand", argument1, argument2, ...)
See the examples below.
printer_callback(fun)
printer_callback(fun)
fun |
The function to use as a printer callback function. |
The subcommands:
length
The length of the data to print, the number of items, in natural units. E.g. for a list of objects, it is the number of objects.
min_width
TODO
width
Width of one item, if no
items will be
printed. TODO
print
Argument: no
. Do the actual printing,
print no
items.
done
TODO
Other printer callbacks:
is_printer_callback()
This is the default R palette, to be able to reproduce the colors of older igraph versions. Its colors are appropriate for categories, but they are not very attractive.
r_pal(n)
r_pal(n)
n |
The number of colors to use, the maximum is eight. |
A character vector of color names.
Other palettes:
categorical_pal()
,
diverging_pal()
,
sequential_pal()
The eccentricity of a vertex is its distance from the farthest other node in the graph. The smallest eccentricity in a graph is called its radius.
radius(graph, ..., weights = NULL, mode = c("all", "out", "in", "total"))
radius(graph, ..., weights = NULL, mode = c("all", "out", "in", "total"))
graph |
The input graph, it can be directed or undirected. |
... |
These dots are for future extensions and must be empty. |
weights |
Possibly a numeric vector giving edge weights. If this is
|
mode |
Character constant, gives whether the shortest paths to or from
the given vertices should be calculated for directed graphs. If |
The eccentricity of a vertex is calculated by measuring the shortest distance from (or to) the vertex, to (or from) all vertices in the graph, and taking the maximum.
This implementation ignores vertex pairs that are in different components. Isolated vertices have eccentricity zero.
A numeric scalar, the radius of the graph.
Harary, F. Graph Theory. Reading, MA: Addison-Wesley, p. 35, 1994.
eccentricity()
for the underlying
calculations, distances for general shortest path
calculations.
Other paths:
all_simple_paths()
,
diameter()
,
distance_table()
,
eccentricity()
,
graph_center()
g <- make_star(10, mode = "undirected") eccentricity(g) radius(g)
g <- make_star(10, mode = "undirected") eccentricity(g) radius(g)
random_walk()
performs a random walk on the graph and returns the
vertices that the random walk passed through. random_edge_walk()
is the same but returns the edges that that random walk passed through.
random_walk( graph, start, steps, weights = NULL, mode = c("out", "in", "all", "total"), stuck = c("return", "error") ) random_edge_walk( graph, start, steps, weights = NULL, mode = c("out", "in", "all", "total"), stuck = c("return", "error") )
random_walk( graph, start, steps, weights = NULL, mode = c("out", "in", "all", "total"), stuck = c("return", "error") ) random_edge_walk( graph, start, steps, weights = NULL, mode = c("out", "in", "all", "total"), stuck = c("return", "error") )
graph |
The input graph, might be undirected or directed. |
start |
The start vertex. |
steps |
The number of steps to make. |
weights |
The edge weights. Larger edge weights increase the
probability that an edge is selected by the random walker. In other
words, larger edge weights correspond to stronger connections. The
‘weight’ edge attribute is used if present. Supply
‘ |
mode |
How to follow directed edges. |
stuck |
What to do if the random walk gets stuck. |
Do a random walk. From the given start vertex, take the given number of
steps, choosing an edge from the actual vertex uniformly randomly. Edge
directions are observed in directed graphs (see the mode
argument
as well). Multiple and loop edges are also observed.
For igraph < 1.6.0, random_walk()
counted steps differently,
and returned a sequence of length steps
instead of steps + 1
.
This has changed to improve consistency with the underlying C library.
For random_walk()
, a vertex sequence of length steps + 1
containing the vertices along the walk, starting with start
.
For random_edge_walk()
, an edge sequence of length steps
containing
the edges along the walk.
## Stationary distribution of a Markov chain g <- make_ring(10, directed = TRUE) %u% make_star(11, center = 11) + edge(11, 1) ec <- eigen_centrality(g, directed = TRUE)$vector pg <- page_rank(g, damping = 0.999)$vector w <- random_walk(g, start = 1, steps = 10000) ## These are similar, but not exactly the same cor(table(w), ec) ## But these are (almost) the same cor(table(w), pg)
## Stationary distribution of a Markov chain g <- make_ring(10, directed = TRUE) %u% make_star(11, center = 11) + edge(11, 1) ec <- eigen_centrality(g, directed = TRUE)$vector pg <- page_rank(g, damping = 0.999)$vector w <- random_walk(g, start = 1, steps = 10000) ## These are similar, but not exactly the same cor(table(w), ec) ## But these are (almost) the same cor(table(w), pg)
The read_graph()
function is able to read graphs in various
representations from a file, or from a http connection. Various formats
are supported.
read_graph( file, format = c("edgelist", "pajek", "ncol", "lgl", "graphml", "dimacs", "graphdb", "gml", "dl"), ... )
read_graph( file, format = c("edgelist", "pajek", "ncol", "lgl", "graphml", "dimacs", "graphdb", "gml", "dl"), ... )
file |
The connection to read from. This can be a local file, or a
|
format |
Character constant giving the file format. Right now
|
... |
Additional arguments, see below. |
The read_graph()
function may have additional arguments depending on
the file format (the format
argument). See the details separately for
each file format, below.
A graph object.
This format is a simple text file with numeric vertex IDs defining the edges. There is no need to have newline characters between the edges, a simple space will also do. Vertex IDs contained in the file are assumed to start at zero.
Additional arguments:
The number of vertices in the graph. If it is smaller than or equal to the largest integer in the file, then it is ignored; so it is safe to set it to zero (the default).
Logical scalar, whether to create a directed graph. The
default value is TRUE
.
Currently igraph only supports Pajek network
files, with a .net
extension, but not Pajek project files with
a .paj
extension. Only network data is supported; permutations,
hierarchies, clusters and vectors are not.
igraph_read_graph_dimacs_flow()
, igraph_read_graph_dl()
, igraph_read_graph_edgelist()
, igraph_read_graph_gml()
, igraph_read_graph_graphdb()
, igraph_read_graph_graphml()
, igraph_read_graph_lgl()
, igraph_read_graph_ncol()
, igraph_read_graph_pajek()
.
Gabor Csardi [email protected]
Foreign format readers
graph_from_graphdb()
,
write_graph()
Constructs a bipartite graph from the degree sequences of its partitions, if one exists. This function uses a Havel-Hakimi style construction algorithm.
realize_bipartite_degseq( degrees1, degrees2, ..., allowed.edge.types = c("simple", "multiple"), method = c("smallest", "largest", "index") )
realize_bipartite_degseq( degrees1, degrees2, ..., allowed.edge.types = c("simple", "multiple"), method = c("smallest", "largest", "index") )
degrees1 |
The degrees of the first partition. |
degrees2 |
The degrees of the second partition. |
... |
These dots are for future extensions and must be empty. |
allowed.edge.types |
Character, specifies the types of allowed edges. “simple” allows simple graphs only (no multiple edges). “multiple” allows multiple edges. |
method |
Character, the method for generating the graph; see below. |
The ‘method’ argument controls in which order the vertices are selected during the course of the algorithm.
The “smallest” method selects the vertex with the smallest remaining degree, from either partition. The result is usually a graph with high negative degree assortativity. In the undirected case, this method is guaranteed to generate a connected graph, regardless of whether multi-edges are allowed, provided that a connected realization exists. This is the default method.
The “largest” method selects the vertex with the largest remaining degree. The result is usually a graph with high positive degree assortativity, and is often disconnected.
The “index” method selects the vertices in order of their index.
The new graph object.
igraph_realize_bipartite_degree_sequence()
.
realize_degseq()
to create a not necessarily bipartite graph.
g <- realize_bipartite_degseq(c(3, 3, 2, 1, 1), c(2, 2, 2, 2, 2)) degree(g)
g <- realize_bipartite_degseq(c(3, 3, 2, 1, 1), c(2, 2, 2, 2, 2)) degree(g)
It is often useful to create a graph with given vertex degrees. This function creates such a graph in a deterministic manner.
realize_degseq( out.deg, in.deg = NULL, allowed.edge.types = c("simple", "loops", "multi", "all"), method = c("smallest", "largest", "index") )
realize_degseq( out.deg, in.deg = NULL, allowed.edge.types = c("simple", "loops", "multi", "all"), method = c("smallest", "largest", "index") )
out.deg |
Numeric vector, the sequence of degrees (for undirected
graphs) or out-degrees (for directed graphs). For undirected graphs its sum
should be even. For directed graphs its sum should be the same as the sum of
|
in.deg |
For directed graph, the in-degree sequence. By default this is
|
allowed.edge.types |
Character, specifies the types of allowed edges. “simple” allows simple graphs only (no loops, no multiple edges). “multiple” allows multiple edges but disallows loop. “loops” allows loop edges but disallows multiple edges (currently unimplemented). “all” allows all types of edges. The default is “simple”. |
method |
Character, the method for generating the graph; see below. |
Simple undirected graphs are constructed using the Havel-Hakimi algorithm (undirected case), or the analogous Kleitman-Wang algorithm (directed case). These algorithms work by choosing an arbitrary vertex and connecting all its stubs to other vertices. This step is repeated until all degrees have been connected up.
The ‘method’ argument controls in which order the vertices are selected during the course of the algorithm.
The “smallest” method selects the vertex with the smallest remaining degree. The result is usually a graph with high negative degree assortativity. In the undirected case, this method is guaranteed to generate a connected graph, regardless of whether multi-edges are allowed, provided that a connected realization exists. See Horvát and Modes (2021) for details. In the directed case it tends to generate weakly connected graphs, but this is not guaranteed. This is the default method.
The “largest” method selects the vertex with the largest remaining degree. The result is usually a graph with high positive degree assortativity, and is often disconnected.
The “index” method selects the vertices in order of their index.
The new graph object.
igraph_realize_degree_sequence()
.
V. Havel, Poznámka o existenci konečných grafů (A remark on the existence of finite graphs), Časopis pro pěstování matematiky 80, 477-480 (1955). https://eudml.org/doc/19050
S. L. Hakimi, On Realizability of a Set of Integers as Degrees of the Vertices of a Linear Graph, Journal of the SIAM 10, 3 (1962). doi:10.1137/0111010
D. J. Kleitman and D. L. Wang, Algorithms for Constructing Graphs and Digraphs with Given Valences and Factors, Discrete Mathematics 6, 1 (1973). doi:10.1016/0012-365X(73)90037-X
Sz. Horvát and C. D. Modes, Connectedness matters: construction and exact random sampling of connected networks (2021). doi:10.1088/2632-072X/abced5
sample_degseq()
for a randomized variant that samples
from graphs with the given degree sequence.
g <- realize_degseq(rep(2, 100)) degree(g) is_simple(g) ## Exponential degree distribution, with high positive assortativity. ## Loop and multiple edges are explicitly allowed. ## Note that we correct the degree sequence if its sum is odd. degs <- sample(1:100, 100, replace = TRUE, prob = exp(-0.5 * (1:100))) if (sum(degs) %% 2 != 0) { degs[1] <- degs[1] + 1 } g4 <- realize_degseq(degs, method = "largest", allowed.edge.types = "all") all(degree(g4) == degs) ## Power-law degree distribution, no loops allowed but multiple edges ## are okay. ## Note that we correct the degree sequence if its sum is odd. degs <- sample(1:100, 100, replace = TRUE, prob = (1:100)^-2) if (sum(degs) %% 2 != 0) { degs[1] <- degs[1] + 1 } g5 <- realize_degseq(degs, allowed.edge.types = "multi") all(degree(g5) == degs)
g <- realize_degseq(rep(2, 100)) degree(g) is_simple(g) ## Exponential degree distribution, with high positive assortativity. ## Loop and multiple edges are explicitly allowed. ## Note that we correct the degree sequence if its sum is odd. degs <- sample(1:100, 100, replace = TRUE, prob = exp(-0.5 * (1:100))) if (sum(degs) %% 2 != 0) { degs[1] <- degs[1] + 1 } g4 <- realize_degseq(degs, method = "largest", allowed.edge.types = "all") all(degree(g4) == degs) ## Power-law degree distribution, no loops allowed but multiple edges ## are okay. ## Note that we correct the degree sequence if its sum is odd. degs <- sample(1:100, 100, replace = TRUE, prob = (1:100)^-2) if (sum(degs) %% 2 != 0) { degs[1] <- degs[1] + 1 } g5 <- realize_degseq(degs, allowed.edge.types = "multi") all(degree(g5) == degs)
Calculates the reciprocity of a directed graph.
reciprocity(graph, ignore.loops = TRUE, mode = c("default", "ratio"))
reciprocity(graph, ignore.loops = TRUE, mode = c("default", "ratio"))
graph |
The graph object. |
ignore.loops |
Logical constant, whether to ignore loop edges. |
mode |
See below. |
The measure of 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. Or in
adjacency matrix notation:
.
This measure is calculated if the
mode
argument is default
.
Prior to igraph version 0.6, another measure was implemented, defined as the
probability of mutual connection between a vertex pair, if we know that
there is a (possibly non-mutual) connection between them. In other words,
(unordered) vertex pairs are classified into three groups: (1)
not-connected, (2) non-reciprocally connected, (3) reciprocally connected.
The result is the size of group (3), divided by the sum of group sizes
(2)+(3). This measure is calculated if mode
is ratio
.
A numeric scalar between zero and one.
Tamas Nepusz [email protected] and Gabor Csardi [email protected]
Other structural.properties:
bfs()
,
component_distribution()
,
connect()
,
constraint()
,
coreness()
,
degree()
,
dfs()
,
distance_table()
,
edge_density()
,
feedback_arc_set()
,
girth()
,
is_acyclic()
,
is_dag()
,
is_matching()
,
k_shortest_paths()
,
knn()
,
subcomponent()
,
subgraph()
,
topo_sort()
,
transitivity()
,
unfold_tree()
,
which_multiple()
,
which_mutual()
g <- sample_gnp(20, 5 / 20, directed = TRUE) reciprocity(g)
g <- sample_gnp(20, 5 / 20, directed = TRUE) reciprocity(g)
The new graph will contain the input graph the given number of times, as unconnected components.
## S3 method for class 'igraph' rep(x, n, mark = TRUE, ...) ## S3 method for class 'igraph' x * n
## S3 method for class 'igraph' rep(x, n, mark = TRUE, ...) ## S3 method for class 'igraph' x * n
x |
The input graph. |
n |
Number of times to replicate it. |
mark |
Whether to mark the vertices with a |
... |
Additional arguments to satisfy S3 requirements, currently ignored. |
Other functions for manipulating graph structure:
+.igraph()
,
add_edges()
,
add_vertices()
,
complementer()
,
compose()
,
connect()
,
contract()
,
delete_edges()
,
delete_vertices()
,
difference()
,
difference.igraph()
,
disjoint_union()
,
edge()
,
igraph-minus
,
intersection()
,
intersection.igraph()
,
path()
,
permute()
,
reverse_edges()
,
simplify()
,
union()
,
union.igraph()
,
vertex()
rings <- make_ring(5) * 5
rings <- make_ring(5) * 5
Reverse the order in an edge sequence
## S3 method for class 'igraph.es' rev(x)
## S3 method for class 'igraph.es' rev(x)
x |
The edge sequence to reverse. |
The reversed edge sequence.
Other vertex and edge sequence operations:
c.igraph.es()
,
c.igraph.vs()
,
difference.igraph.es()
,
difference.igraph.vs()
,
igraph-es-indexing
,
igraph-es-indexing2
,
igraph-vs-indexing
,
igraph-vs-indexing2
,
intersection.igraph.es()
,
intersection.igraph.vs()
,
rev.igraph.vs()
,
union.igraph.es()
,
union.igraph.vs()
,
unique.igraph.es()
,
unique.igraph.vs()
g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) E(g) E(g) %>% rev()
g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) E(g) E(g) %>% rev()
Reverse the order in a vertex sequence
## S3 method for class 'igraph.vs' rev(x)
## S3 method for class 'igraph.vs' rev(x)
x |
The vertex sequence to reverse. |
The reversed vertex sequence.
Other vertex and edge sequence operations:
c.igraph.es()
,
c.igraph.vs()
,
difference.igraph.es()
,
difference.igraph.vs()
,
igraph-es-indexing
,
igraph-es-indexing2
,
igraph-vs-indexing
,
igraph-vs-indexing2
,
intersection.igraph.es()
,
intersection.igraph.vs()
,
rev.igraph.es()
,
union.igraph.es()
,
union.igraph.vs()
,
unique.igraph.es()
,
unique.igraph.vs()
g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) V(g) %>% rev()
g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) V(g) %>% rev()
The new graph will contain the same vertices, edges and attributes as
the original graph, except that the direction of the edges selected by
their edge IDs in the eids
argument will be reversed. When reversing
all edges, this operation is also known as graph transpose.
reverse_edges(graph, eids = E(graph)) ## S3 method for class 'igraph' t(x)
reverse_edges(graph, eids = E(graph)) ## S3 method for class 'igraph' t(x)
graph |
The input graph. |
eids |
The edge IDs of the edges to reverse. |
x |
The input graph. |
The result graph where the direction of the edges with the given IDs are reversed
Other functions for manipulating graph structure:
+.igraph()
,
add_edges()
,
add_vertices()
,
complementer()
,
compose()
,
connect()
,
contract()
,
delete_edges()
,
delete_vertices()
,
difference()
,
difference.igraph()
,
disjoint_union()
,
edge()
,
igraph-minus
,
intersection()
,
intersection.igraph()
,
path()
,
permute()
,
rep.igraph()
,
simplify()
,
union()
,
union.igraph()
,
vertex()
g <- make_graph(~ 1 -+ 2, 2 -+ 3, 3 -+ 4) reverse_edges(g, 2)
g <- make_graph(~ 1 -+ 2, 2 -+ 3, 3 -+ 4) reverse_edges(g, 2)
See the links below for the implemented rewiring methods.
rewire(graph, with)
rewire(graph, with)
graph |
The graph to rewire |
with |
A function call to one of the rewiring methods, see details below. |
The rewired graph.
Other rewiring functions:
each_edge()
,
keeping_degseq()
g <- make_ring(10) g %>% rewire(each_edge(p = .1, loops = FALSE)) %>% plot(layout = layout_in_circle) print_all(rewire(g, with = keeping_degseq(niter = vcount(g) * 10)))
g <- make_ring(10) g %>% rewire(each_edge(p = .1, loops = FALSE)) %>% plot(layout = layout_in_circle) print_all(rewire(g, with = keeping_degseq(niter = vcount(g) * 10)))
Using the rgl
package, rglplot()
plots a graph in 3D. The plot
can be zoomed, rotated, shifted, etc. but the coordinates of the vertices is
fixed.
rglplot(x, ...)
rglplot(x, ...)
x |
The graph to plot. |
... |
Additional arguments, see igraph.plotting for the details |
Note that rglplot()
is considered to be highly experimental. It is not
very useful either. See igraph.plotting for the possible
arguments.
NULL
, invisibly.
Gabor Csardi [email protected]
igraph.plotting, plot.igraph()
for the 2D
version, tkplot()
for interactive graph drawing in 2D.
Other plot:
plot.igraph()
g <- make_lattice(c(5, 5, 5)) coords <- layout_with_fr(g, dim = 3) if (interactive() && requireNamespace("rgl", quietly = TRUE)) { rglplot(g, layout = coords) }
g <- make_lattice(c(5, 5, 5)) coords <- layout_with_fr(g, dim = 3) if (interactive() && requireNamespace("rgl", quietly = TRUE)) { rglplot(g, layout = coords) }
running_mean()
calculates the running mean in a vector with the given
bin width.
running_mean(v, binwidth)
running_mean(v, binwidth)
v |
The numeric vector. |
binwidth |
Numeric constant, the size of the bin, should be meaningful,
i.e. smaller than the length of |
The running mean of v
is a w
vector of length
length(v)-binwidth+1
. The first element of w
id the average of
the first binwidth
elements of v
, the second element of
w
is the average of elements 2:(binwidth+1)
, etc.
A numeric vector of length length(v)-binwidth+1
Gabor Csardi [email protected]
Other other:
convex_hull()
,
sample_seq()
running_mean(1:100, 10)
running_mean(1:100, 10)
Generic function for sampling from network models.
sample_(...)
sample_(...)
... |
Parameters, see details below. |
sample_()
is a generic function for creating graphs.
For every graph constructor in igraph that has a sample_
prefix,
there is a corresponding function without the prefix: e.g.
for sample_pa()
there is also pa()
, etc.
The same is true for the deterministic graph samplers, i.e. for each
constructor with a make_
prefix, there is a corresponding
function without that prefix.
These shorter forms can be used together with sample_()
.
The advantage of this form is that the user can specify constructor
modifiers which work with all constructors. E.g. the
with_vertex_()
modifier adds vertex attributes
to the newly created graphs.
See the examples and the various constructor modifiers below.
Random graph models (games)
erdos.renyi.game()
,
sample_bipartite()
,
sample_chung_lu()
,
sample_correlated_gnp()
,
sample_correlated_gnp_pair()
,
sample_degseq()
,
sample_dot_product()
,
sample_fitness()
,
sample_fitness_pl()
,
sample_forestfire()
,
sample_gnm()
,
sample_gnp()
,
sample_grg()
,
sample_growing()
,
sample_hierarchical_sbm()
,
sample_islands()
,
sample_k_regular()
,
sample_last_cit()
,
sample_pa()
,
sample_pa_age()
,
sample_pref()
,
sample_sbm()
,
sample_smallworld()
,
sample_traits_callaway()
,
sample_tree()
Constructor modifiers (and related functions)
make_()
,
simplified()
,
with_edge_()
,
with_graph_()
,
with_vertex_()
,
without_attr()
,
without_loops()
,
without_multiples()
pref_matrix <- cbind(c(0.8, 0.1), c(0.1, 0.7)) blocky <- sample_(sbm( n = 20, pref.matrix = pref_matrix, block.sizes = c(10, 10) )) blocky2 <- pref_matrix %>% sample_sbm(n = 20, block.sizes = c(10, 10)) ## Arguments are passed on from sample_ to sample_sbm blocky3 <- pref_matrix %>% sample_(sbm(), n = 20, block.sizes = c(10, 10))
pref_matrix <- cbind(c(0.8, 0.1), c(0.1, 0.7)) blocky <- sample_(sbm( n = 20, pref.matrix = pref_matrix, block.sizes = c(10, 10) )) blocky2 <- pref_matrix %>% sample_sbm(n = 20, block.sizes = c(10, 10)) ## Arguments are passed on from sample_ to sample_sbm blocky3 <- pref_matrix %>% sample_(sbm(), n = 20, block.sizes = c(10, 10))
Generate bipartite graphs using the Erdős-Rényi model
sample_bipartite( n1, n2, type = c("gnp", "gnm"), p, m, directed = FALSE, mode = c("out", "in", "all") ) bipartite(...)
sample_bipartite( n1, n2, type = c("gnp", "gnm"), p, m, directed = FALSE, mode = c("out", "in", "all") ) bipartite(...)
n1 |
Integer scalar, the number of bottom vertices. |
n2 |
Integer scalar, the number of top vertices. |
type |
Character scalar, the type of the graph, ‘gnp’ creates a
|
p |
Real scalar, connection probability for |
m |
Integer scalar, the number of edges for |
directed |
Logical scalar, whether to create a directed graph. See also
the |
mode |
Character scalar, specifies how to direct the edges in directed graphs. If it is ‘out’, then directed edges point from bottom vertices to top vertices. If it is ‘in’, edges point from top vertices to bottom vertices. ‘out’ and ‘in’ do not generate mutual edges. If this argument is ‘all’, then each edge direction is considered independently and mutual edges might be generated. This argument is ignored for undirected graphs. |
... |
Passed to |
Similarly to unipartite (one-mode) networks, we can define the , and
graph classes for bipartite graphs, via their generating process.
In
every possible edge between top and bottom vertices is realized
with probability
, independently of the rest of the edges. In
, we
uniformly choose
edges to realize.
A bipartite igraph graph.
Gabor Csardi [email protected]
Random graph models (games)
erdos.renyi.game()
,
sample_()
,
sample_chung_lu()
,
sample_correlated_gnp()
,
sample_correlated_gnp_pair()
,
sample_degseq()
,
sample_dot_product()
,
sample_fitness()
,
sample_fitness_pl()
,
sample_forestfire()
,
sample_gnm()
,
sample_gnp()
,
sample_grg()
,
sample_growing()
,
sample_hierarchical_sbm()
,
sample_islands()
,
sample_k_regular()
,
sample_last_cit()
,
sample_pa()
,
sample_pa_age()
,
sample_pref()
,
sample_sbm()
,
sample_smallworld()
,
sample_traits_callaway()
,
sample_tree()
## empty graph sample_bipartite(10, 5, p = 0) ## full graph sample_bipartite(10, 5, p = 1) ## random bipartite graph sample_bipartite(10, 5, p = .1) ## directed bipartite graph, G(n,m) sample_bipartite(10, 5, type = "Gnm", m = 20, directed = TRUE, mode = "all")
## empty graph sample_bipartite(10, 5, p = 0) ## full graph sample_bipartite(10, 5, p = 1) ## random bipartite graph sample_bipartite(10, 5, p = .1) ## directed bipartite graph, G(n,m) sample_bipartite(10, 5, type = "Gnm", m = 20, directed = TRUE, mode = "all")
The Chung-Lu model is useful for generating random graphs with fixed expected degrees. This function implements both the original model of Chung and Lu, as well as some additional variants with useful properties.
sample_chung_lu( out.weights, in.weights = NULL, ..., loops = TRUE, variant = c("original", "maxent", "nr") ) chung_lu( out.weights, in.weights = NULL, ..., loops = TRUE, variant = c("original", "maxent", "nr") )
sample_chung_lu( out.weights, in.weights = NULL, ..., loops = TRUE, variant = c("original", "maxent", "nr") ) chung_lu( out.weights, in.weights = NULL, ..., loops = TRUE, variant = c("original", "maxent", "nr") )
out.weights |
A vector of non-negative vertex weights (or out-weights). In sparse graphs, these will be approximately equal to the expected (out-)degrees. |
in.weights |
A vector of non-negative in-weights, approximately equal to
the expected in-degrees in sparse graphs. May be set to |
... |
These dots are for future extensions and must be empty. |
loops |
Logical, whether to allow the creation of self-loops. Since
vertex pairs are connected independently, setting this to |
variant |
The model variant to sample from, with different definitions
of the connection probability between vertices
|
In the original Chung-Lu model, each pair of vertices and
is
connected with independent probability
where is a weight associated with vertex
and
is the sum of weights. In the directed variant, vertices have both
out-weights, , and in-weights,
, with equal sums,
The connection probability between and
is
This model is commonly used to create random graphs with a fixed
expected degree sequence. The expected degree of vertex is
approximately equal to the weight
. Specifically, if the graph is
directed and self-loops are allowed, then the expected out- and in-degrees
are precisely
and
. If
self-loops are disallowed, then the expected out- and in-degrees are
and
,
respectively. If the graph is undirected, then the expected degrees with and
without self-loops are
and
,
respectively.
A limitation of the original Chung-Lu model is that when some of the weights
are large, the formula for yields values larger than 1.
Chung
and Lu's original paper excludes the use of such weights. When
, this function simply issues a warning and creates
a connection between
and
. However, in this case the expected
degrees will no longer relate to the weights in the manner stated above. Thus,
the original Chung-Lu model cannot produce certain (large) expected degrees.
To overcome this limitation, this function implements additional variants of
the model, with modified expressions for the connection probability
between vertices
and
. Let
, or
in the directed case. All model variants become equivalent in the limit of sparse
graphs where
approaches zero. In the original Chung-Lu model,
selectable by setting
variant
to “original”, . The “maxent” variant,
sometimes referred to as the generalized random graph, uses
, and is equivalent to a
maximum entropy model (i.e., exponential random graph model) with a
constraint on expected degrees;
see Park and Newman (2004), Section B, setting
. This model is also discussed
by Britton, Deijfen, and Martin-Löf (2006). By virtue of being a
degree-constrained maximum entropy model, it generates graphs with the same
degree sequence with the same probability. A third variant can be requested
with “nr”, and uses
. This is the underlying simple graph of a multigraph model
introduced by Norros and Reittu (2006). For a discussion of these three model
variants, see Section 16.4 of Bollobás, Janson, Riordan (2007), as well as
Van Der Hofstad (2013).
An igraph graph.
Chung, F., and Lu, L. (2002). Connected components in a random graph with given degree sequences. Annals of Combinatorics, 6, 125-145. doi:10.1007/PL00012580
Miller, J. C., and Hagberg, A. (2011). Efficient Generation of Networks with Given Expected Degrees. doi:10.1007/978-3-642-21286-4_10
Park, J., and Newman, M. E. J. (2004). Statistical mechanics of networks. Physical Review E, 70, 066117. doi:10.1103/PhysRevE.70.066117
Britton, T., Deijfen, M., and Martin-Löf, A. (2006). Generating Simple Random Graphs with Prescribed Degree Distribution. Journal of Statistical Physics, 124, 1377-1397. doi:10.1007/s10955-006-9168-x
Norros, I., and Reittu, H. (2006). On a conditionally Poissonian graph process. Advances in Applied Probability, 38, 59-75. doi:10.1239/aap/1143936140
Bollobás, B., Janson, S., and Riordan, O. (2007). The phase transition in inhomogeneous random graphs. Random Structures & Algorithms, 31, 3-122. doi:10.1002/rsa.20168
Van Der Hofstad, R. (2013). Critical behavior in inhomogeneous random graphs. Random Structures & Algorithms, 42, 480-508. doi:10.1002/rsa.20450
sample_fitness()
implements a similar model with a sharp
constraint on the number of edges. sample_degseq()
samples random graphs
with sharply specified degrees. sample_gnp()
creates random graphs with a
fixed connection probability between all vertex pairs.
Random graph models (games)
erdos.renyi.game()
,
sample_()
,
sample_bipartite()
,
sample_correlated_gnp()
,
sample_correlated_gnp_pair()
,
sample_degseq()
,
sample_dot_product()
,
sample_fitness()
,
sample_fitness_pl()
,
sample_forestfire()
,
sample_gnm()
,
sample_gnp()
,
sample_grg()
,
sample_growing()
,
sample_hierarchical_sbm()
,
sample_islands()
,
sample_k_regular()
,
sample_last_cit()
,
sample_pa()
,
sample_pa_age()
,
sample_pref()
,
sample_sbm()
,
sample_smallworld()
,
sample_traits_callaway()
,
sample_tree()
g <- sample_chung_lu(c(3, 3, 2, 2, 2, 1, 1)) rowMeans(replicate( 100, degree(sample_chung_lu(c(1, 3, 2, 1), c(2, 1, 2, 2)), mode = "out") )) rowMeans(replicate( 100, degree(sample_chung_lu(c(1, 3, 2, 1), c(2, 1, 2, 2), variant = "maxent"), mode='out') ))
g <- sample_chung_lu(c(3, 3, 2, 2, 2, 1, 1)) rowMeans(replicate( 100, degree(sample_chung_lu(c(1, 3, 2, 1), c(2, 1, 2, 2)), mode = "out") )) rowMeans(replicate( 100, degree(sample_chung_lu(c(1, 3, 2, 1), c(2, 1, 2, 2), variant = "maxent"), mode='out') ))
It is often useful to create a graph with given vertex degrees. This function creates such a graph in a randomized manner.
sample_degseq( out.deg, in.deg = NULL, method = c("configuration", "vl", "fast.heur.simple", "configuration.simple", "edge.switching.simple") ) degseq(..., deterministic = FALSE)
sample_degseq( out.deg, in.deg = NULL, method = c("configuration", "vl", "fast.heur.simple", "configuration.simple", "edge.switching.simple") ) degseq(..., deterministic = FALSE)
out.deg |
Numeric vector, the sequence of degrees (for undirected
graphs) or out-degrees (for directed graphs). For undirected graphs its sum
should be even. For directed graphs its sum should be the same as the sum of
|
in.deg |
For directed graph, the in-degree sequence. By default this is
|
method |
Character, the method for generating the graph. See Details. |
... |
Passed to |
deterministic |
Whether the construction should be deterministic |
The “configuration” method (formerly called "simple") implements the
configuration model. For undirected graphs, it puts all vertex IDs in a bag
such that the multiplicity of a vertex in the bag is the same as its degree.
Then it draws pairs from the bag until the bag becomes empty. This method may
generate both loop (self) edges and multiple edges. For directed graphs,
the algorithm is basically the same, but two separate bags are used
for the in- and out-degrees. Undirected graphs are generated
with probability proportional to ,
where A denotes the adjacency matrix and !! denotes the double factorial.
Here A is assumed to have twice the number of self-loops on its diagonal.
The corresponding expression for directed graphs is
.
Thus the probability of all simple graphs
(which only have 0s and 1s in the adjacency matrix)
is the same, while that of non-simple ones depends on their edge and
self-loop multiplicities.
The “fast.heur.simple” method (formerly called "simple.no.multiple") generates simple graphs. It is similar to “configuration” but tries to avoid multiple and loop edges and restarts the generation from scratch if it gets stuck. It can generate all simple realizations of a degree sequence, but it is not guaranteed to sample them uniformly. This method is relatively fast and it will eventually succeed if the provided degree sequence is graphical, but there is no upper bound on the number of iterations.
The “configuration.simple” method (formerly called "simple.no.multiple.uniform") is identical to “configuration”, but if the generated graph is not simple, it rejects it and re-starts the generation. It generates all simple graphs with the same probability.
The “vl” method samples undirected connected graphs approximately uniformly. It is a Monte Carlo method based on degree-preserving edge switches. This generator should be favoured if undirected and connected graphs are to be generated and execution time is not a concern. igraph uses the original implementation of Fabien Viger; for the algorithm, see https://www-complexnetworks.lip6.fr/~latapy/FV/generation.html and the paper https://arxiv.org/abs/cs/0502085.
The “edge.switching.simple” is an MCMC sampler based on degree-preserving edge switches. It generates simple undirected or directed graphs.
The new graph object.
Gabor Csardi [email protected]
simplify()
to get rid of the multiple and/or loops edges,
realize_degseq()
for a deterministic variant.
Random graph models (games)
erdos.renyi.game()
,
sample_()
,
sample_bipartite()
,
sample_chung_lu()
,
sample_correlated_gnp()
,
sample_correlated_gnp_pair()
,
sample_dot_product()
,
sample_fitness()
,
sample_fitness_pl()
,
sample_forestfire()
,
sample_gnm()
,
sample_gnp()
,
sample_grg()
,
sample_growing()
,
sample_hierarchical_sbm()
,
sample_islands()
,
sample_k_regular()
,
sample_last_cit()
,
sample_pa()
,
sample_pa_age()
,
sample_pref()
,
sample_sbm()
,
sample_smallworld()
,
sample_traits_callaway()
,
sample_tree()
## The simple generator undirected_graph <- sample_degseq(rep(2, 100)) degree(undirected_graph) is_simple(undirected_graph) # sometimes TRUE, but can be FALSE directed_graph <- sample_degseq(1:10, 10:1) degree(directed_graph, mode = "out") degree(directed_graph, mode = "in") ## The vl generator vl_graph <- sample_degseq(rep(2, 100), method = "vl") degree(vl_graph) is_simple(vl_graph) # always TRUE ## Exponential degree distribution ## We fix the seed as there's no guarantee ## that randomly picked integers will form a graphical degree sequence ## (i.e. that there's a graph with these degrees) ## withr::with_seed(42, { ## exponential_degrees <- sample(1:100, 100, replace = TRUE, prob = exp(-0.5 * (1:100))) ## }) exponential_degrees <- c( 5L, 6L, 1L, 4L, 3L, 2L, 3L, 1L, 3L, 3L, 2L, 3L, 6L, 1L, 2L, 6L, 8L, 1L, 2L, 2L, 5L, 1L, 10L, 6L, 1L, 2L, 1L, 5L, 2L, 4L, 3L, 4L, 1L, 3L, 1L, 4L, 1L, 1L, 5L, 2L, 1L, 2L, 1L, 8L, 2L, 7L, 5L, 3L, 8L, 2L, 1L, 1L, 2L, 4L, 1L, 3L, 3L, 1L, 1L, 2L, 3L, 9L, 3L, 2L, 4L, 1L, 1L, 4L, 3L, 1L, 1L, 1L, 1L, 2L, 1L, 3L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 3L, 3L, 2L, 1L, 1L, 1L, 1L, 3L, 1L, 1L, 6L, 6L, 3L, 1L, 2L, 3L, 2L ) ## Note, that we'd have to correct the degree sequence if its sum is odd is_exponential_degrees_sum_odd <- (sum(exponential_degrees) %% 2 != 0) if (is_exponential_degrees_sum_odd) { exponential_degrees[1] <- exponential_degrees[1] + 1 } exp_vl_graph <- sample_degseq(exponential_degrees, method = "vl") all(degree(exp_vl_graph) == exponential_degrees) ## An example that does not work ## withr::with_seed(11, { ## exponential_degrees <- sample(1:100, 100, replace = TRUE, prob = exp(-0.5 * (1:100))) ## }) exponential_degrees <- c( 1L, 1L, 2L, 1L, 1L, 7L, 1L, 1L, 5L, 1L, 1L, 2L, 5L, 4L, 3L, 2L, 2L, 1L, 1L, 2L, 1L, 3L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 2L, 1L, 4L, 3L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 3L, 1L, 4L, 3L, 1L, 2L, 4L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 4L, 1L, 2L, 1L, 3L, 1L, 2L, 3L, 1L, 1L, 2L, 1L, 2L, 3L, 2L, 2L, 1L, 6L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 4L, 2L, 1L, 3L, 4L, 1L, 1L, 3L, 1L, 2L, 4L, 1L, 3L, 1L, 2L, 1L ) ## Note, that we'd have to correct the degree sequence if its sum is odd is_exponential_degrees_sum_odd <- (sum(exponential_degrees) %% 2 != 0) if (is_exponential_degrees_sum_odd) { exponential_degrees[1] <- exponential_degrees[1] + 1 } exp_vl_graph <- sample_degseq(exponential_degrees, method = "vl") ## Power-law degree distribution ## We fix the seed as there's no guarantee ## that randomly picked integers will form a graphical degree sequence ## (i.e. that there's a graph with these degrees) ## withr::with_seed(1, { ## powerlaw_degrees <- sample(1:100, 100, replace = TRUE, prob = (1:100)^-2) ## }) powerlaw_degrees <- c( 1L, 1L, 1L, 6L, 1L, 6L, 10L, 2L, 2L, 1L, 1L, 1L, 2L, 1L, 3L, 1L, 2L, 43L, 1L, 3L, 9L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 4L, 1L, 1L, 1L, 1L, 1L, 3L, 2L, 3L, 1L, 2L, 1L, 3L, 2L, 3L, 1L, 1L, 3L, 1L, 1L, 2L, 2L, 1L, 4L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 7L, 1L, 1L, 1L, 2L, 1L, 1L, 3L, 1L, 5L, 1L, 4L, 1L, 1L, 1L, 5L, 4L, 1L, 3L, 13L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 5L, 3L, 3L, 1L, 1L, 3L, 1L ) ## Note, that we correct the degree sequence if its sum is odd is_exponential_degrees_sum_odd <- (sum(powerlaw_degrees) %% 2 != 0) if (is_exponential_degrees_sum_odd) { powerlaw_degrees[1] <- powerlaw_degrees[1] + 1 } powerlaw_vl_graph <- sample_degseq(powerlaw_degrees, method = "vl") all(degree(powerlaw_vl_graph) == powerlaw_degrees) ## An example that does not work ## withr::with_seed(2, { ## powerlaw_degrees <- sample(1:100, 100, replace = TRUE, prob = (1:100)^-2) ## }) powerlaw_degrees <- c( 1L, 2L, 1L, 1L, 10L, 10L, 1L, 4L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 4L, 21L, 1L, 1L, 1L, 2L, 1L, 4L, 1L, 1L, 1L, 1L, 1L, 14L, 1L, 1L, 1L, 3L, 4L, 1L, 2L, 4L, 1L, 2L, 1L, 25L, 1L, 1L, 1L, 10L, 3L, 19L, 1L, 1L, 3L, 1L, 1L, 2L, 8L, 1L, 3L, 3L, 36L, 2L, 2L, 3L, 5L, 2L, 1L, 4L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 4L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 4L, 18L, 1L, 2L, 1L, 21L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L ) ## Note, that we correct the degree sequence if its sum is odd is_exponential_degrees_sum_odd <- (sum(powerlaw_degrees) %% 2 != 0) if (is_exponential_degrees_sum_odd) { powerlaw_degrees[1] <- powerlaw_degrees[1] + 1 } powerlaw_vl_graph <- sample_degseq(powerlaw_degrees, method = "vl") all(degree(powerlaw_vl_graph) == powerlaw_degrees)
## The simple generator undirected_graph <- sample_degseq(rep(2, 100)) degree(undirected_graph) is_simple(undirected_graph) # sometimes TRUE, but can be FALSE directed_graph <- sample_degseq(1:10, 10:1) degree(directed_graph, mode = "out") degree(directed_graph, mode = "in") ## The vl generator vl_graph <- sample_degseq(rep(2, 100), method = "vl") degree(vl_graph) is_simple(vl_graph) # always TRUE ## Exponential degree distribution ## We fix the seed as there's no guarantee ## that randomly picked integers will form a graphical degree sequence ## (i.e. that there's a graph with these degrees) ## withr::with_seed(42, { ## exponential_degrees <- sample(1:100, 100, replace = TRUE, prob = exp(-0.5 * (1:100))) ## }) exponential_degrees <- c( 5L, 6L, 1L, 4L, 3L, 2L, 3L, 1L, 3L, 3L, 2L, 3L, 6L, 1L, 2L, 6L, 8L, 1L, 2L, 2L, 5L, 1L, 10L, 6L, 1L, 2L, 1L, 5L, 2L, 4L, 3L, 4L, 1L, 3L, 1L, 4L, 1L, 1L, 5L, 2L, 1L, 2L, 1L, 8L, 2L, 7L, 5L, 3L, 8L, 2L, 1L, 1L, 2L, 4L, 1L, 3L, 3L, 1L, 1L, 2L, 3L, 9L, 3L, 2L, 4L, 1L, 1L, 4L, 3L, 1L, 1L, 1L, 1L, 2L, 1L, 3L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 3L, 3L, 2L, 1L, 1L, 1L, 1L, 3L, 1L, 1L, 6L, 6L, 3L, 1L, 2L, 3L, 2L ) ## Note, that we'd have to correct the degree sequence if its sum is odd is_exponential_degrees_sum_odd <- (sum(exponential_degrees) %% 2 != 0) if (is_exponential_degrees_sum_odd) { exponential_degrees[1] <- exponential_degrees[1] + 1 } exp_vl_graph <- sample_degseq(exponential_degrees, method = "vl") all(degree(exp_vl_graph) == exponential_degrees) ## An example that does not work ## withr::with_seed(11, { ## exponential_degrees <- sample(1:100, 100, replace = TRUE, prob = exp(-0.5 * (1:100))) ## }) exponential_degrees <- c( 1L, 1L, 2L, 1L, 1L, 7L, 1L, 1L, 5L, 1L, 1L, 2L, 5L, 4L, 3L, 2L, 2L, 1L, 1L, 2L, 1L, 3L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 2L, 1L, 4L, 3L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 3L, 1L, 4L, 3L, 1L, 2L, 4L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 4L, 1L, 2L, 1L, 3L, 1L, 2L, 3L, 1L, 1L, 2L, 1L, 2L, 3L, 2L, 2L, 1L, 6L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 4L, 2L, 1L, 3L, 4L, 1L, 1L, 3L, 1L, 2L, 4L, 1L, 3L, 1L, 2L, 1L ) ## Note, that we'd have to correct the degree sequence if its sum is odd is_exponential_degrees_sum_odd <- (sum(exponential_degrees) %% 2 != 0) if (is_exponential_degrees_sum_odd) { exponential_degrees[1] <- exponential_degrees[1] + 1 } exp_vl_graph <- sample_degseq(exponential_degrees, method = "vl") ## Power-law degree distribution ## We fix the seed as there's no guarantee ## that randomly picked integers will form a graphical degree sequence ## (i.e. that there's a graph with these degrees) ## withr::with_seed(1, { ## powerlaw_degrees <- sample(1:100, 100, replace = TRUE, prob = (1:100)^-2) ## }) powerlaw_degrees <- c( 1L, 1L, 1L, 6L, 1L, 6L, 10L, 2L, 2L, 1L, 1L, 1L, 2L, 1L, 3L, 1L, 2L, 43L, 1L, 3L, 9L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 4L, 1L, 1L, 1L, 1L, 1L, 3L, 2L, 3L, 1L, 2L, 1L, 3L, 2L, 3L, 1L, 1L, 3L, 1L, 1L, 2L, 2L, 1L, 4L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 7L, 1L, 1L, 1L, 2L, 1L, 1L, 3L, 1L, 5L, 1L, 4L, 1L, 1L, 1L, 5L, 4L, 1L, 3L, 13L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 5L, 3L, 3L, 1L, 1L, 3L, 1L ) ## Note, that we correct the degree sequence if its sum is odd is_exponential_degrees_sum_odd <- (sum(powerlaw_degrees) %% 2 != 0) if (is_exponential_degrees_sum_odd) { powerlaw_degrees[1] <- powerlaw_degrees[1] + 1 } powerlaw_vl_graph <- sample_degseq(powerlaw_degrees, method = "vl") all(degree(powerlaw_vl_graph) == powerlaw_degrees) ## An example that does not work ## withr::with_seed(2, { ## powerlaw_degrees <- sample(1:100, 100, replace = TRUE, prob = (1:100)^-2) ## }) powerlaw_degrees <- c( 1L, 2L, 1L, 1L, 10L, 10L, 1L, 4L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 4L, 21L, 1L, 1L, 1L, 2L, 1L, 4L, 1L, 1L, 1L, 1L, 1L, 14L, 1L, 1L, 1L, 3L, 4L, 1L, 2L, 4L, 1L, 2L, 1L, 25L, 1L, 1L, 1L, 10L, 3L, 19L, 1L, 1L, 3L, 1L, 1L, 2L, 8L, 1L, 3L, 3L, 36L, 2L, 2L, 3L, 5L, 2L, 1L, 4L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 4L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 4L, 18L, 1L, 2L, 1L, 21L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L ) ## Note, that we correct the degree sequence if its sum is odd is_exponential_degrees_sum_odd <- (sum(powerlaw_degrees) %% 2 != 0) if (is_exponential_degrees_sum_odd) { powerlaw_degrees[1] <- powerlaw_degrees[1] + 1 } powerlaw_vl_graph <- sample_degseq(powerlaw_degrees, method = "vl") all(degree(powerlaw_vl_graph) == powerlaw_degrees)
Sample finite-dimensional vectors to use as latent position vectors in random dot product graphs
sample_dirichlet(n, alpha)
sample_dirichlet(n, alpha)
n |
Integer scalar, the sample size. |
alpha |
Numeric vector, the vector of |
sample_dirichlet()
generates samples from the Dirichlet distribution
with given parameter. The sample is drawn from
length(alpha)-1
-simplex.
A dim
(length of the alpha
vector for
sample_dirichlet()
) times n
matrix, whose columns are the sample
vectors.
Other latent position vector samplers:
sample_sphere_surface()
,
sample_sphere_volume()
lpvs.dir <- sample_dirichlet(n = 20, alpha = rep(1, 10)) RDP.graph.2 <- sample_dot_product(lpvs.dir) colSums(lpvs.dir)
lpvs.dir <- sample_dirichlet(n = 20, alpha = rep(1, 10)) RDP.graph.2 <- sample_dot_product(lpvs.dir) colSums(lpvs.dir)
In this model, each vertex is represented by a latent position vector. Probability of an edge between two vertices are given by the dot product of their latent position vectors.
sample_dot_product(vecs, directed = FALSE) dot_product(...)
sample_dot_product(vecs, directed = FALSE) dot_product(...)
vecs |
A numeric matrix in which each latent position vector is a column. |
directed |
A logical scalar, TRUE if the generated graph should be directed. |
... |
Passed to |
The dot product of the latent position vectors should be in the [0,1] interval, otherwise a warning is given. For negative dot products, no edges are added; dot products that are larger than one always add an edge.
An igraph graph object which is the generated random dot product graph.
Gabor Csardi [email protected]
Christine Leigh Myers Nickel: Random dot product graphs, a model for social networks. Dissertation, Johns Hopkins University, Maryland, USA, 2006.
sample_dirichlet()
, sample_sphere_surface()
and sample_sphere_volume()
for sampling position vectors.
Random graph models (games)
erdos.renyi.game()
,
sample_()
,
sample_bipartite()
,
sample_chung_lu()
,
sample_correlated_gnp()
,
sample_correlated_gnp_pair()
,
sample_degseq()
,
sample_fitness()
,
sample_fitness_pl()
,
sample_forestfire()
,
sample_gnm()
,
sample_gnp()
,
sample_grg()
,
sample_growing()
,
sample_hierarchical_sbm()
,
sample_islands()
,
sample_k_regular()
,
sample_last_cit()
,
sample_pa()
,
sample_pa_age()
,
sample_pref()
,
sample_sbm()
,
sample_smallworld()
,
sample_traits_callaway()
,
sample_tree()
## A randomly generated graph lpvs <- matrix(rnorm(200), 20, 10) lpvs <- apply(lpvs, 2, function(x) { return(abs(x) / sqrt(sum(x^2))) }) g <- sample_dot_product(lpvs) g ## Sample latent vectors from the surface of the unit sphere lpvs2 <- sample_sphere_surface(dim = 5, n = 20) g2 <- sample_dot_product(lpvs2) g2
## A randomly generated graph lpvs <- matrix(rnorm(200), 20, 10) lpvs <- apply(lpvs, 2, function(x) { return(abs(x) / sqrt(sum(x^2))) }) g <- sample_dot_product(lpvs) g ## Sample latent vectors from the surface of the unit sphere lpvs2 <- sample_sphere_surface(dim = 5, n = 20) g2 <- sample_dot_product(lpvs2) g2
This function generates a non-growing random graph with edge probabilities proportional to node fitness scores.
sample_fitness( no.of.edges, fitness.out, fitness.in = NULL, loops = FALSE, multiple = FALSE )
sample_fitness( no.of.edges, fitness.out, fitness.in = NULL, loops = FALSE, multiple = FALSE )
no.of.edges |
The number of edges in the generated graph. |
fitness.out |
A numeric vector containing the fitness of each vertex. For directed graphs, this specifies the out-fitness of each vertex. |
fitness.in |
If If this argument is not |
loops |
Logical scalar, whether to allow loop edges in the graph. |
multiple |
Logical scalar, whether to allow multiple edges in the graph. |
This game generates a directed or undirected random graph where the
probability of an edge between vertices and
depends on the
fitness scores of the two vertices involved. For undirected graphs, each
vertex has a single fitness score. For directed graphs, each vertex has an
out- and an in-fitness, and the probability of an edge from
to
depends on the out-fitness of vertex
and the in-fitness of
vertex
.
The generation process goes as follows. We start from disconnected
nodes (where
is given by the length of the fitness vector). Then we
randomly select two vertices
and
, with probabilities
proportional to their fitnesses. (When the generated graph is directed,
is selected according to the out-fitnesses and
is selected
according to the in-fitnesses). If the vertices are not connected yet (or if
multiple edges are allowed), we connect them; otherwise we select a new
pair. This is repeated until the desired number of links are created.
It can be shown that the expected degree of each vertex will be
proportional to its fitness, although the actual, observed degree will not
be. If you need to generate a graph with an exact degree sequence, consider
sample_degseq()
instead.
This model is commonly used to generate static scale-free networks. To
achieve this, you have to draw the fitness scores from the desired power-law
distribution. Alternatively, you may use sample_fitness_pl()
which generates the fitnesses for you with a given exponent.
An igraph graph, directed or undirected.
Tamas Nepusz [email protected]
Goh K-I, Kahng B, Kim D: Universal behaviour of load distribution in scale-free networks. Phys Rev Lett 87(27):278701, 2001.
Random graph models (games)
erdos.renyi.game()
,
sample_()
,
sample_bipartite()
,
sample_chung_lu()
,
sample_correlated_gnp()
,
sample_correlated_gnp_pair()
,
sample_degseq()
,
sample_dot_product()
,
sample_fitness_pl()
,
sample_forestfire()
,
sample_gnm()
,
sample_gnp()
,
sample_grg()
,
sample_growing()
,
sample_hierarchical_sbm()
,
sample_islands()
,
sample_k_regular()
,
sample_last_cit()
,
sample_pa()
,
sample_pa_age()
,
sample_pref()
,
sample_sbm()
,
sample_smallworld()
,
sample_traits_callaway()
,
sample_tree()
N <- 10000 g <- sample_fitness(5 * N, sample((1:50)^-2, N, replace = TRUE)) degree_distribution(g) plot(degree_distribution(g, cumulative = TRUE), log = "xy")
N <- 10000 g <- sample_fitness(5 * N, sample((1:50)^-2, N, replace = TRUE)) degree_distribution(g) plot(degree_distribution(g, cumulative = TRUE), log = "xy")
This function generates a non-growing random graph with expected power-law degree distributions.
sample_fitness_pl( no.of.nodes, no.of.edges, exponent.out, exponent.in = -1, loops = FALSE, multiple = FALSE, finite.size.correction = TRUE )
sample_fitness_pl( no.of.nodes, no.of.edges, exponent.out, exponent.in = -1, loops = FALSE, multiple = FALSE, finite.size.correction = TRUE )
no.of.nodes |
The number of vertices in the generated graph. |
no.of.edges |
The number of edges in the generated graph. |
exponent.out |
Numeric scalar, the power law exponent of the degree
distribution. For directed graphs, this specifies the exponent of the
out-degree distribution. It must be greater than or equal to 2. If you pass
|
exponent.in |
Numeric scalar. If negative, the generated graph will be undirected. If greater than or equal to 2, this argument specifies the exponent of the in-degree distribution. If non-negative but less than 2, an error will be generated. |
loops |
Logical scalar, whether to allow loop edges in the generated graph. |
multiple |
Logical scalar, whether to allow multiple edges in the generated graph. |
finite.size.correction |
Logical scalar, whether to use the proposed finite size correction of Cho et al., see references below. |
This game generates a directed or undirected random graph where the degrees of vertices follow power-law distributions with prescribed exponents. For directed graphs, the exponents of the in- and out-degree distributions may be specified separately.
The game simply uses sample_fitness()
with appropriately
constructed fitness vectors. In particular, the fitness of vertex is
, where
and
is the exponent given in the arguments.
To remove correlations between in- and out-degrees in case of directed
graphs, the in-fitness vector will be shuffled after it has been set up and
before sample_fitness()
is called.
Note that significant finite size effects may be observed for exponents
smaller than 3 in the original formulation of the game. This function
provides an argument that lets you remove the finite size effects by
assuming that the fitness of vertex is
where
is a
constant chosen appropriately to ensure that the maximum degree is less than
the square root of the number of edges times the average degree; see the
paper of Chung and Lu, and Cho et al for more details.
An igraph graph, directed or undirected.
igraph_static_power_law_game()
.
Tamas Nepusz [email protected]
Goh K-I, Kahng B, Kim D: Universal behaviour of load distribution in scale-free networks. Phys Rev Lett 87(27):278701, 2001.
Chung F and Lu L: Connected components in a random graph with given degree sequences. Annals of Combinatorics 6, 125-145, 2002.
Cho YS, Kim JS, Park J, Kahng B, Kim D: Percolation transitions in scale-free networks under the Achlioptas process. Phys Rev Lett 103:135702, 2009.
Random graph models (games)
erdos.renyi.game()
,
sample_()
,
sample_bipartite()
,
sample_chung_lu()
,
sample_correlated_gnp()
,
sample_correlated_gnp_pair()
,
sample_degseq()
,
sample_dot_product()
,
sample_fitness()
,
sample_forestfire()
,
sample_gnm()
,
sample_gnp()
,
sample_grg()
,
sample_growing()
,
sample_hierarchical_sbm()
,
sample_islands()
,
sample_k_regular()
,
sample_last_cit()
,
sample_pa()
,
sample_pa_age()
,
sample_pref()
,
sample_sbm()
,
sample_smallworld()
,
sample_traits_callaway()
,
sample_tree()
g <- sample_fitness_pl(10000, 30000, 2.2, 2.3) plot(degree_distribution(g, cumulative = TRUE, mode = "out"), log = "xy")
g <- sample_fitness_pl(10000, 30000, 2.2, 2.3) plot(degree_distribution(g, cumulative = TRUE, mode = "out"), log = "xy")
This is a growing network model, which resembles of how the forest fire spreads by igniting trees close by.
sample_forestfire(nodes, fw.prob, bw.factor = 1, ambs = 1, directed = TRUE)
sample_forestfire(nodes, fw.prob, bw.factor = 1, ambs = 1, directed = TRUE)
nodes |
The number of vertices in the graph. |
fw.prob |
The forward burning probability, see details below. |
bw.factor |
The backward burning ratio. The backward burning
probability is calculated as |
ambs |
The number of ambassador vertices. |
directed |
Logical scalar, whether to create a directed graph. |
The forest fire model intends to reproduce the following network characteristics, observed in real networks:
Heavy-tailed in-degree distribution.
Heavy-tailed out-degree distribution.
Communities.
Densification power-law. The network is densifying in time, according to a power-law rule.
Shrinking diameter. The diameter of the network decreases in time.
The network is generated in the following way. One vertex is added at a
time. This vertex connects to (cites) ambs
vertices already present
in the network, chosen uniformly random. Now, for each cited vertex
we do the following procedure:
We generate two random
number, and
, that are geometrically distributed with means
and
. (
is
fw.prob
, is
bw.factor
.) The new vertex cites outgoing neighbors and
incoming neighbors of
, from those which are not yet cited by
the new vertex. If there are less than
or
such vertices
available then we cite all of them.
The same procedure is applied to all the newly cited vertices.
A simple graph, possibly directed if the directed
argument is
TRUE
.
The version of the model in the published paper is incorrect in the sense that it cannot generate the kind of graphs the authors claim. A corrected version is available from http://www.cs.cmu.edu/~jure/pubs/powergrowth-tkdd.pdf, our implementation is based on this.
Gabor Csardi [email protected]
Jure Leskovec, Jon Kleinberg and Christos Faloutsos. Graphs over time: densification laws, shrinking diameters and possible explanations. KDD '05: Proceeding of the eleventh ACM SIGKDD international conference on Knowledge discovery in data mining, 177–187, 2005.
sample_pa()
for the basic preferential attachment
model.
Random graph models (games)
erdos.renyi.game()
,
sample_()
,
sample_bipartite()
,
sample_chung_lu()
,
sample_correlated_gnp()
,
sample_correlated_gnp_pair()
,
sample_degseq()
,
sample_dot_product()
,
sample_fitness()
,
sample_fitness_pl()
,
sample_gnm()
,
sample_gnp()
,
sample_grg()
,
sample_growing()
,
sample_hierarchical_sbm()
,
sample_islands()
,
sample_k_regular()
,
sample_last_cit()
,
sample_pa()
,
sample_pa_age()
,
sample_pref()
,
sample_sbm()
,
sample_smallworld()
,
sample_traits_callaway()
,
sample_tree()
fire <- sample_forestfire(50, fw.prob = 0.37, bw.factor = 0.32 / 0.37) plot(fire) g <- sample_forestfire(10000, fw.prob = 0.37, bw.factor = 0.32 / 0.37) dd1 <- degree_distribution(g, mode = "in") dd2 <- degree_distribution(g, mode = "out") # The forest fire model produces graphs with a heavy tail degree distribution. # Note that some in- or out-degrees are zero which will be excluded from the logarithmic plot. plot(seq(along.with = dd1) - 1, dd1, log = "xy") points(seq(along.with = dd2) - 1, dd2, col = 2, pch = 2)
fire <- sample_forestfire(50, fw.prob = 0.37, bw.factor = 0.32 / 0.37) plot(fire) g <- sample_forestfire(10000, fw.prob = 0.37, bw.factor = 0.32 / 0.37) dd1 <- degree_distribution(g, mode = "in") dd2 <- degree_distribution(g, mode = "out") # The forest fire model produces graphs with a heavy tail degree distribution. # Note that some in- or out-degrees are zero which will be excluded from the logarithmic plot. plot(seq(along.with = dd1) - 1, dd1, log = "xy") points(seq(along.with = dd2) - 1, dd2, col = 2, pch = 2)
Erdős-Rényi modelRandom graph with a fixed number of edges and vertices.
sample_gnm(n, m, directed = FALSE, loops = FALSE) gnm(...)
sample_gnm(n, m, directed = FALSE, loops = FALSE) gnm(...)
n |
The number of vertices in the graph. |
m |
The number of edges in the graph. |
directed |
Logical, whether the graph will be directed, defaults to
|
loops |
Logical, whether to add loop edges, defaults to |
... |
Passed to |
The graph has n
vertices and m
edges. The edges are chosen uniformly
at random from the set of all vertex pairs. This set includes potential
self-connections as well if the loops
parameter is TRUE
.
A graph object.
Gabor Csardi [email protected]
Erdős, P. and Rényi, A., On random graphs, Publicationes Mathematicae 6, 290–297 (1959).
Random graph models (games)
erdos.renyi.game()
,
sample_()
,
sample_bipartite()
,
sample_chung_lu()
,
sample_correlated_gnp()
,
sample_correlated_gnp_pair()
,
sample_degseq()
,
sample_dot_product()
,
sample_fitness()
,
sample_fitness_pl()
,
sample_forestfire()
,
sample_gnp()
,
sample_grg()
,
sample_growing()
,
sample_hierarchical_sbm()
,
sample_islands()
,
sample_k_regular()
,
sample_last_cit()
,
sample_pa()
,
sample_pa_age()
,
sample_pref()
,
sample_sbm()
,
sample_smallworld()
,
sample_traits_callaway()
,
sample_tree()
g <- sample_gnm(1000, 1000) degree_distribution(g)
g <- sample_gnm(1000, 1000) degree_distribution(g)
Erdős-Rényi modelEvery possible edge is created independently with the same probability p
.
This model is also referred to as a Bernoulli random graph since the
connectivity status of vertex pairs follows a Bernoulli distribution.
sample_gnp(n, p, directed = FALSE, loops = FALSE) gnp(...)
sample_gnp(n, p, directed = FALSE, loops = FALSE) gnp(...)
n |
The number of vertices in the graph. |
p |
The probability for drawing an edge between two
arbitrary vertices ( |
directed |
Logical, whether the graph will be directed, defaults to
|
loops |
Logical, whether to add loop edges, defaults to |
... |
Passed to |
The graph has n
vertices and each pair of vertices is connected
with the same probability p
. The loops
parameter controls whether
self-connections are also considered. This model effectively constrains
the average number of edges, , where
is the largest possible number of edges, which depends on whether the
graph is directed or undirected and whether self-loops are allowed.
A graph object.
Gabor Csardi [email protected]
Erdős, P. and Rényi, A., On random graphs, Publicationes Mathematicae 6, 290–297 (1959).
Random graph models (games)
erdos.renyi.game()
,
sample_()
,
sample_bipartite()
,
sample_chung_lu()
,
sample_correlated_gnp()
,
sample_correlated_gnp_pair()
,
sample_degseq()
,
sample_dot_product()
,
sample_fitness()
,
sample_fitness_pl()
,
sample_forestfire()
,
sample_gnm()
,
sample_grg()
,
sample_growing()
,
sample_hierarchical_sbm()
,
sample_islands()
,
sample_k_regular()
,
sample_last_cit()
,
sample_pa()
,
sample_pa_age()
,
sample_pref()
,
sample_sbm()
,
sample_smallworld()
,
sample_traits_callaway()
,
sample_tree()
# Random graph with expected mean degree of 2 g <- sample_gnp(1000, 2 / 1000) mean(degree(g)) degree_distribution(g) # Pick a simple graph on 6 vertices uniformly at random plot(sample_gnp(6, 0.5))
# Random graph with expected mean degree of 2 g <- sample_gnp(1000, 2 / 1000) mean(degree(g)) degree_distribution(g) # Pick a simple graph on 6 vertices uniformly at random plot(sample_gnp(6, 0.5))
Generate a random graph based on the distance of random point on a unit square
sample_grg(nodes, radius, torus = FALSE, coords = FALSE) grg(...)
sample_grg(nodes, radius, torus = FALSE, coords = FALSE) grg(...)
nodes |
The number of vertices in the graph. |
radius |
The radius within which the vertices will be connected by an edge. |
torus |
Logical constant, whether to use a torus instead of a square. |
coords |
Logical scalar, whether to add the positions of the vertices
as vertex attributes called ‘ |
... |
Passed to |
First a number of points are dropped on a unit square, these points
correspond to the vertices of the graph to create. Two points will be
connected with an undirected edge if they are closer to each other in
Euclidean norm than a given radius. If the torus
argument is
TRUE
then a unit area torus is used instead of a square.
A graph object. If coords
is TRUE
then with vertex
attributes ‘x
’ and ‘y
’.
Gabor Csardi [email protected], first version was written by Keith Briggs (http://keithbriggs.info/).
Random graph models (games)
erdos.renyi.game()
,
sample_()
,
sample_bipartite()
,
sample_chung_lu()
,
sample_correlated_gnp()
,
sample_correlated_gnp_pair()
,
sample_degseq()
,
sample_dot_product()
,
sample_fitness()
,
sample_fitness_pl()
,
sample_forestfire()
,
sample_gnm()
,
sample_gnp()
,
sample_growing()
,
sample_hierarchical_sbm()
,
sample_islands()
,
sample_k_regular()
,
sample_last_cit()
,
sample_pa()
,
sample_pa_age()
,
sample_pref()
,
sample_sbm()
,
sample_smallworld()
,
sample_traits_callaway()
,
sample_tree()
g <- sample_grg(1000, 0.05, torus = FALSE) g2 <- sample_grg(1000, 0.05, torus = TRUE)
g <- sample_grg(1000, 0.05, torus = FALSE) g2 <- sample_grg(1000, 0.05, torus = TRUE)
This function creates a random graph by simulating its stochastic evolution.
sample_growing(n, m = 1, ..., directed = TRUE, citation = FALSE) growing(...)
sample_growing(n, m = 1, ..., directed = TRUE, citation = FALSE) growing(...)
n |
Numeric constant, number of vertices in the graph. |
m |
Numeric constant, number of edges added in each time step. |
... |
Passed to |
directed |
Logical, whether to create a directed graph. |
citation |
Logical. If |
This is discrete time step model, in each time step a new vertex is added to
the graph and m
new edges are created. If citation
is
FALSE
these edges are connecting two uniformly randomly chosen
vertices, otherwise the edges are connecting new vertex to uniformly
randomly chosen old vertices.
A new graph object.
Gabor Csardi [email protected]
Random graph models (games)
erdos.renyi.game()
,
sample_()
,
sample_bipartite()
,
sample_chung_lu()
,
sample_correlated_gnp()
,
sample_correlated_gnp_pair()
,
sample_degseq()
,
sample_dot_product()
,
sample_fitness()
,
sample_fitness_pl()
,
sample_forestfire()
,
sample_gnm()
,
sample_gnp()
,
sample_grg()
,
sample_hierarchical_sbm()
,
sample_islands()
,
sample_k_regular()
,
sample_last_cit()
,
sample_pa()
,
sample_pa_age()
,
sample_pref()
,
sample_sbm()
,
sample_smallworld()
,
sample_traits_callaway()
,
sample_tree()
g <- sample_growing(500, citation = FALSE) g2 <- sample_growing(500, citation = TRUE)
g <- sample_growing(500, citation = FALSE) g2 <- sample_growing(500, citation = TRUE)
Sampling from a hierarchical stochastic block model of networks.
sample_hierarchical_sbm(n, m, rho, C, p) hierarchical_sbm(...)
sample_hierarchical_sbm(n, m, rho, C, p) hierarchical_sbm(...)
n |
Integer scalar, the number of vertices. |
m |
Integer scalar, the number of vertices per block. |
rho |
Numeric vector, the fraction of vertices per cluster, within a
block. Must sum up to 1, and |
C |
A square, symmetric numeric matrix, the Bernoulli rates for the
clusters within a block. Its size must mach the size of the |
p |
Numeric scalar, the Bernoulli rate of connections between vertices in different blocks. |
... |
Passed to |
The function generates a random graph according to the hierarchical stochastic block model.
An igraph graph.
igraph_hsbm_game()
, igraph_hsbm_list_game()
.
Gabor Csardi [email protected]
Random graph models (games)
erdos.renyi.game()
,
sample_()
,
sample_bipartite()
,
sample_chung_lu()
,
sample_correlated_gnp()
,
sample_correlated_gnp_pair()
,
sample_degseq()
,
sample_dot_product()
,
sample_fitness()
,
sample_fitness_pl()
,
sample_forestfire()
,
sample_gnm()
,
sample_gnp()
,
sample_grg()
,
sample_growing()
,
sample_islands()
,
sample_k_regular()
,
sample_last_cit()
,
sample_pa()
,
sample_pa_age()
,
sample_pref()
,
sample_sbm()
,
sample_smallworld()
,
sample_traits_callaway()
,
sample_tree()
## Ten blocks with three clusters each C <- matrix(c( 1, 3 / 4, 0, 3 / 4, 0, 3 / 4, 0, 3 / 4, 3 / 4 ), nrow = 3) g <- sample_hierarchical_sbm(100, 10, rho = c(3, 3, 4) / 10, C = C, p = 1 / 20) g if (require(Matrix)) { image(g[]) }
## Ten blocks with three clusters each C <- matrix(c( 1, 3 / 4, 0, 3 / 4, 0, 3 / 4, 0, 3 / 4, 3 / 4 ), nrow = 3) g <- sample_hierarchical_sbm(100, 10, rho = c(3, 3, 4) / 10, C = C, p = 1 / 20) g if (require(Matrix)) { image(g[]) }
sample_hrg()
samples a graph from a given hierarchical random graph
model.
sample_hrg(hrg)
sample_hrg(hrg)
hrg |
A hierarchical random graph model. |
An igraph graph.
Other hierarchical random graph functions:
consensus_tree()
,
fit_hrg()
,
hrg()
,
hrg-methods
,
hrg_tree()
,
predict_edges()
,
print.igraphHRG()
,
print.igraphHRGConsensus()
Create a number of Erdős-Rényi random graphs with identical parameters, and connect them with the specified number of edges.
sample_islands(islands.n, islands.size, islands.pin, n.inter)
sample_islands(islands.n, islands.size, islands.pin, n.inter)
islands.n |
The number of islands in the graph. |
islands.size |
The size of islands in the graph. |
islands.pin |
The probability to create each possible edge into each island. |
n.inter |
The number of edges to create between two islands. |
An igraph graph.
g <- sample_islands(3, 10, 5/10, 1) oc <- cluster_optimal(g) oc
igraph_simple_interconnected_islands_game()
.
Samuel Thiriot
Random graph models (games)
erdos.renyi.game()
,
sample_()
,
sample_bipartite()
,
sample_chung_lu()
,
sample_correlated_gnp()
,
sample_correlated_gnp_pair()
,
sample_degseq()
,
sample_dot_product()
,
sample_fitness()
,
sample_fitness_pl()
,
sample_forestfire()
,
sample_gnm()
,
sample_gnp()
,
sample_grg()
,
sample_growing()
,
sample_hierarchical_sbm()
,
sample_k_regular()
,
sample_last_cit()
,
sample_pa()
,
sample_pa_age()
,
sample_pref()
,
sample_sbm()
,
sample_smallworld()
,
sample_traits_callaway()
,
sample_tree()
Generate a random graph where each vertex has the same degree.
sample_k_regular(no.of.nodes, k, directed = FALSE, multiple = FALSE)
sample_k_regular(no.of.nodes, k, directed = FALSE, multiple = FALSE)
no.of.nodes |
Integer scalar, the number of vertices in the generated graph. |
k |
Integer scalar, the degree of each vertex in the graph, or the out-degree and in-degree in a directed graph. |
directed |
Logical scalar, whether to create a directed graph. |
multiple |
Logical scalar, whether multiple edges are allowed. |
This game generates a directed or undirected random graph where the degrees of vertices are equal to a predefined constant k. For undirected graphs, at least one of k and the number of vertices must be even.
The game simply uses sample_degseq()
with appropriately
constructed degree sequences.
An igraph graph.
Tamas Nepusz [email protected]
sample_degseq()
for a generator with prescribed degree
sequence.
Random graph models (games)
erdos.renyi.game()
,
sample_()
,
sample_bipartite()
,
sample_chung_lu()
,
sample_correlated_gnp()
,
sample_correlated_gnp_pair()
,
sample_degseq()
,
sample_dot_product()
,
sample_fitness()
,
sample_fitness_pl()
,
sample_forestfire()
,
sample_gnm()
,
sample_gnp()
,
sample_grg()
,
sample_growing()
,
sample_hierarchical_sbm()
,
sample_islands()
,
sample_last_cit()
,
sample_pa()
,
sample_pa_age()
,
sample_pref()
,
sample_sbm()
,
sample_smallworld()
,
sample_traits_callaway()
,
sample_tree()
## A simple ring ring <- sample_k_regular(10, 2) plot(ring) ## k-regular graphs on 10 vertices, with k=1:9 k10 <- lapply(1:9, sample_k_regular, no.of.nodes = 10) layout(matrix(1:9, nrow = 3, byrow = TRUE)) sapply(k10, plot, vertex.label = NA)
## A simple ring ring <- sample_k_regular(10, 2) plot(ring) ## k-regular graphs on 10 vertices, with k=1:9 k10 <- lapply(1:9, sample_k_regular, no.of.nodes = 10) layout(matrix(1:9, nrow = 3, byrow = TRUE)) sapply(k10, plot, vertex.label = NA)
sample_last_cit()
creates a graph, where vertices age, and
gain new connections based on how long ago their last citation
happened.
sample_last_cit( n, edges = 1, agebins = n/7100, pref = (1:(agebins + 1))^-3, directed = TRUE ) last_cit(...) sample_cit_types( n, edges = 1, types = rep(0, n), pref = rep(1, length(types)), directed = TRUE, attr = TRUE ) cit_types(...) sample_cit_cit_types( n, edges = 1, types = rep(0, n), pref = matrix(1, nrow = length(types), ncol = length(types)), directed = TRUE, attr = TRUE ) cit_cit_types(...)
sample_last_cit( n, edges = 1, agebins = n/7100, pref = (1:(agebins + 1))^-3, directed = TRUE ) last_cit(...) sample_cit_types( n, edges = 1, types = rep(0, n), pref = rep(1, length(types)), directed = TRUE, attr = TRUE ) cit_types(...) sample_cit_cit_types( n, edges = 1, types = rep(0, n), pref = matrix(1, nrow = length(types), ncol = length(types)), directed = TRUE, attr = TRUE ) cit_cit_types(...)
n |
Number of vertices. |
edges |
Number of edges per step. |
agebins |
Number of aging bins. |
pref |
Vector ( |
directed |
Logical scalar, whether to generate directed networks. |
... |
Passed to the actual constructor. |
types |
Vector of length ‘ |
attr |
Logical scalar, whether to add the vertex types to the generated
graph as a vertex attribute called ‘ |
sample_cit_cit_types()
is a stochastic block model where the
graph is growing.
sample_cit_types()
is similarly a growing stochastic block model,
but the probability of an edge depends on the (potentially) cited
vertex only.
A new graph.
Gabor Csardi [email protected]
Random graph models (games)
erdos.renyi.game()
,
sample_()
,
sample_bipartite()
,
sample_chung_lu()
,
sample_correlated_gnp()
,
sample_correlated_gnp_pair()
,
sample_degseq()
,
sample_dot_product()
,
sample_fitness()
,
sample_fitness_pl()
,
sample_forestfire()
,
sample_gnm()
,
sample_gnp()
,
sample_grg()
,
sample_growing()
,
sample_hierarchical_sbm()
,
sample_islands()
,
sample_k_regular()
,
sample_pa()
,
sample_pa_age()
,
sample_pref()
,
sample_sbm()
,
sample_smallworld()
,
sample_traits_callaway()
,
sample_tree()
Graph motifs are small connected induced subgraphs with a well-defined structure. These functions search a graph for various motifs.
sample_motifs( graph, size = 3, cut.prob = rep(0, size), sample.size = NULL, sample = NULL )
sample_motifs( graph, size = 3, cut.prob = rep(0, size), sample.size = NULL, sample = NULL )
graph |
Graph object, the input graph. |
size |
The size of the motif, currently size 3 and 4 are supported in directed graphs and sizes 3-6 in undirected graphs. |
cut.prob |
Numeric vector giving the probabilities that the search
graph is cut at a certain level. Its length should be the same as the size
of the motif (the |
sample.size |
The number of vertices to use as a starting point for
finding motifs. Only used if the |
sample |
If not |
sample_motifs()
estimates the total number of motifs of a given
size in a graph based on a sample.
A numeric scalar, an estimate for the total number of motifs in the graph.
Other graph motifs:
count_motifs()
,
dyad_census()
,
motifs()
g <- sample_pa(100) motifs(g, 3) count_motifs(g, 3) sample_motifs(g, 3)
g <- sample_pa(100) motifs(g, 3) count_motifs(g, 3) sample_motifs(g, 3)
Preferential attachment is a family of simple stochastic algorithms for building a graph. Variants include the Barabási-Abert model and the Price model.
sample_pa( n, power = 1, m = NULL, out.dist = NULL, out.seq = NULL, out.pref = FALSE, zero.appeal = 1, directed = TRUE, algorithm = c("psumtree", "psumtree-multiple", "bag"), start.graph = NULL ) pa(...)
sample_pa( n, power = 1, m = NULL, out.dist = NULL, out.seq = NULL, out.pref = FALSE, zero.appeal = 1, directed = TRUE, algorithm = c("psumtree", "psumtree-multiple", "bag"), start.graph = NULL ) pa(...)
n |
Number of vertices. |
power |
The power of the preferential attachment, the default is one, i.e. linear preferential attachment. |
m |
Numeric constant, the number of edges to add in each time step This
argument is only used if both |
out.dist |
Numeric vector, the distribution of the number of edges to
add in each time step. This argument is only used if the |
out.seq |
Numeric vector giving the number of edges to add in each time step. Its first element is ignored as no edges are added in the first time step. |
out.pref |
Logical, if true the total degree is used for calculating the citation probability, otherwise the in-degree is used. |
zero.appeal |
The ‘attractiveness’ of the vertices with no adjacent edges. See details below. |
directed |
Whether to create a directed graph. |
algorithm |
The algorithm to use for the graph generation.
|
start.graph |
|
... |
Passed to |
This is a simple stochastic algorithm to generate a graph. It is a discrete time step model and in each time step a single vertex is added.
We start with a single vertex and no edges in the first time step. Then we add one vertex in each time step and the new vertex initiates some edges to old vertices. The probability that an old vertex is chosen is given by
where
is the in-degree of vertex
in the current time step (more precisely
the number of adjacent edges of
which were not initiated by
itself) and
and
are parameters given by the
power
and zero.appeal
arguments.
The number of edges initiated in a time step is given by the m
,
out.dist
and out.seq
arguments. If out.seq
is given and
not NULL then it gives the number of edges to add in a vector, the first
element is ignored, the second is the number of edges to add in the second
time step and so on. If out.seq
is not given or null and
out.dist
is given and not NULL then it is used as a discrete
distribution to generate the number of edges in each time step. Its first
element is the probability that no edges will be added, the second is the
probability that one edge is added, etc. (out.dist
does not need to
sum up to one, it normalized automatically.) out.dist
should contain
non-negative numbers and at east one element should be positive.
If both out.seq
and out.dist
are omitted or NULL then m
will be used, it should be a positive integer constant and m
edges
will be added in each time step.
sample_pa()
generates a directed graph by default, set
directed
to FALSE
to generate an undirected graph. Note that
even if an undirected graph is generated denotes the number
of adjacent edges not initiated by the vertex itself and not the total
(in- + out-) degree of the vertex, unless the
out.pref
argument is set to
TRUE
.
A graph object.
Gabor Csardi [email protected]
Barabási, A.-L. and Albert R. 1999. Emergence of scaling in random networks Science, 286 509–512.
de Solla Price, D. J. 1965. Networks of Scientific Papers Science, 149 510–515.
Random graph models (games)
erdos.renyi.game()
,
sample_()
,
sample_bipartite()
,
sample_chung_lu()
,
sample_correlated_gnp()
,
sample_correlated_gnp_pair()
,
sample_degseq()
,
sample_dot_product()
,
sample_fitness()
,
sample_fitness_pl()
,
sample_forestfire()
,
sample_gnm()
,
sample_gnp()
,
sample_grg()
,
sample_growing()
,
sample_hierarchical_sbm()
,
sample_islands()
,
sample_k_regular()
,
sample_last_cit()
,
sample_pa_age()
,
sample_pref()
,
sample_sbm()
,
sample_smallworld()
,
sample_traits_callaway()
,
sample_tree()
g <- sample_pa(10000) degree_distribution(g)
g <- sample_pa(10000) degree_distribution(g)
This function creates a random graph by simulating its evolution. Each time a new vertex is added it creates a number of links to old vertices and the probability that an old vertex is cited depends on its in-degree (preferential attachment) and age.
sample_pa_age( n, pa.exp, aging.exp, m = NULL, aging.bin = 300, out.dist = NULL, out.seq = NULL, out.pref = FALSE, directed = TRUE, zero.deg.appeal = 1, zero.age.appeal = 0, deg.coef = 1, age.coef = 1, time.window = NULL ) pa_age(...)
sample_pa_age( n, pa.exp, aging.exp, m = NULL, aging.bin = 300, out.dist = NULL, out.seq = NULL, out.pref = FALSE, directed = TRUE, zero.deg.appeal = 1, zero.age.appeal = 0, deg.coef = 1, age.coef = 1, time.window = NULL ) pa_age(...)
n |
The number of vertices in the graph. |
pa.exp |
The preferential attachment exponent, see the details below. |
aging.exp |
The exponent of the aging, usually a non-positive number, see details below. |
m |
The number of edges each new vertex creates (except the very first
vertex). This argument is used only if both the |
aging.bin |
The number of bins to use for measuring the age of vertices, see details below. |
out.dist |
The discrete distribution to generate the number of edges to
add in each time step if |
out.seq |
The number of edges to add in each time step, a vector containing as many elements as the number of vertices. See details below. |
out.pref |
Logical constant, whether to include edges not initiated by the vertex as a basis of preferential attachment. See details below. |
directed |
Logical constant, whether to generate a directed graph. See details below. |
zero.deg.appeal |
The degree-dependent part of the ‘attractiveness’ of the vertices with no adjacent edges. See also details below. |
zero.age.appeal |
The age-dependent part of the ‘attrativeness’ of the vertices with age zero. It is usually zero, see details below. |
deg.coef |
The coefficient of the degree-dependent ‘attractiveness’. See details below. |
age.coef |
The coefficient of the age-dependent part of the ‘attractiveness’. See details below. |
time.window |
Integer constant, if NULL only adjacent added in the last
|
... |
Passed to |
This is a discrete time step model of a growing graph. We start with a network containing a single vertex (and no edges) in the first time step. Then in each time step (starting with the second) a new vertex is added and it initiates a number of edges to the old vertices in the network. The probability that an old vertex is connected to is proportional to
.
Here is the in-degree of vertex
in the current time
step and
is the age of vertex
. The age is simply
defined as the number of time steps passed since the vertex is added, with
the extension that vertex age is divided to be in
aging.bin
bins.
,
,
,
,
and
are parameters and they can be set via the following arguments:
pa.exp
(, mandatory argument),
aging.exp
(, mandatory argument),
zero.deg.appeal
(,
optional, the default value is 1),
zero.age.appeal
(,
optional, the default is 0),
deg.coef
(, optional, the default
is 1), and
age.coef
(, optional, the default is 1).
The number of edges initiated in each time step is governed by the m
,
out.seq
and out.pref
parameters. If out.seq
is given
then it is interpreted as a vector giving the number of edges to be added in
each time step. It should be of length n
(the number of vertices),
and its first element will be ignored. If out.seq
is not given (or
NULL) and out.dist
is given then it will be used as a discrete
probability distribution to generate the number of edges. Its first element
gives the probability that zero edges are added at a time step, the second
element is the probability that one edge is added, etc. (out.seq
should contain non-negative numbers, but if they don't sum up to 1, they
will be normalized to sum up to 1. This behavior is similar to the
prob
argument of the sample
command.)
By default a directed graph is generated, but it directed
is set to
FALSE
then an undirected is created. Even if an undirected graph is
generated denotes only the adjacent edges not initiated by
the vertex itself except if
out.pref
is set to TRUE
.
If the time.window
argument is given (and not NULL) then
means only the adjacent edges added in the previous
time.window
time steps.
This function might generate graphs with multiple edges.
A new graph.
Gabor Csardi [email protected]
Random graph models (games)
erdos.renyi.game()
,
sample_()
,
sample_bipartite()
,
sample_chung_lu()
,
sample_correlated_gnp()
,
sample_correlated_gnp_pair()
,
sample_degseq()
,
sample_dot_product()
,
sample_fitness()
,
sample_fitness_pl()
,
sample_forestfire()
,
sample_gnm()
,
sample_gnp()
,
sample_grg()
,
sample_growing()
,
sample_hierarchical_sbm()
,
sample_islands()
,
sample_k_regular()
,
sample_last_cit()
,
sample_pa()
,
sample_pref()
,
sample_sbm()
,
sample_smallworld()
,
sample_traits_callaway()
,
sample_tree()
# The maximum degree for graph with different aging exponents g1 <- sample_pa_age(10000, pa.exp = 1, aging.exp = 0, aging.bin = 1000) g2 <- sample_pa_age(10000, pa.exp = 1, aging.exp = -1, aging.bin = 1000) g3 <- sample_pa_age(10000, pa.exp = 1, aging.exp = -3, aging.bin = 1000) max(degree(g1)) max(degree(g2)) max(degree(g3))
# The maximum degree for graph with different aging exponents g1 <- sample_pa_age(10000, pa.exp = 1, aging.exp = 0, aging.bin = 1000) g2 <- sample_pa_age(10000, pa.exp = 1, aging.exp = -1, aging.bin = 1000) g3 <- sample_pa_age(10000, pa.exp = 1, aging.exp = -3, aging.bin = 1000) max(degree(g1)) max(degree(g2)) max(degree(g3))
Generation of random graphs based on different vertex types.
sample_pref( nodes, types, type.dist = rep(1, types), fixed.sizes = FALSE, pref.matrix = matrix(1, types, types), directed = FALSE, loops = FALSE ) pref(...) sample_asym_pref( nodes, types, type.dist.matrix = matrix(1, types, types), pref.matrix = matrix(1, types, types), loops = FALSE ) asym_pref(...)
sample_pref( nodes, types, type.dist = rep(1, types), fixed.sizes = FALSE, pref.matrix = matrix(1, types, types), directed = FALSE, loops = FALSE ) pref(...) sample_asym_pref( nodes, types, type.dist.matrix = matrix(1, types, types), pref.matrix = matrix(1, types, types), loops = FALSE ) asym_pref(...)
nodes |
The number of vertices in the graphs. |
types |
The number of different vertex types. |
type.dist |
The distribution of the vertex types, a numeric vector of length ‘types’ containing non-negative numbers. The vector will be normed to obtain probabilities. |
fixed.sizes |
Fix the number of vertices with a given vertex type
label. The |
pref.matrix |
A square matrix giving the preferences of the vertex types. The matrix has ‘types’ rows and columns. When generating an undirected graph, it must be symmetric. |
directed |
Logical constant, whether to create a directed graph. |
loops |
Logical constant, whether self-loops are allowed in the graph. |
... |
Passed to the constructor, |
type.dist.matrix |
The joint distribution of the in- and out-vertex types. |
Both models generate random graphs with given vertex types. For
sample_pref()
the probability that two vertices will be connected
depends on their type and is given by the ‘pref.matrix’ argument.
This matrix should be symmetric to make sense but this is not checked. The
distribution of the different vertex types is given by the
‘type.dist’ vector.
For sample_asym_pref()
each vertex has an in-type and an
out-type and a directed graph is created. The probability that a directed
edge is realized from a vertex with a given out-type to a vertex with a
given in-type is given in the ‘pref.matrix’ argument, which can be
asymmetric. The joint distribution for the in- and out-types is given in the
‘type.dist.matrix’ argument.
The types of the generated vertices can be retrieved from the
type
vertex attribute for sample_pref()
and from the
intype
and outtype
vertex attribute for sample_asym_pref()
.
An igraph graph.
Tamas Nepusz [email protected] and Gabor Csardi [email protected] for the R interface
Random graph models (games)
erdos.renyi.game()
,
sample_()
,
sample_bipartite()
,
sample_chung_lu()
,
sample_correlated_gnp()
,
sample_correlated_gnp_pair()
,
sample_degseq()
,
sample_dot_product()
,
sample_fitness()
,
sample_fitness_pl()
,
sample_forestfire()
,
sample_gnm()
,
sample_gnp()
,
sample_grg()
,
sample_growing()
,
sample_hierarchical_sbm()
,
sample_islands()
,
sample_k_regular()
,
sample_last_cit()
,
sample_pa()
,
sample_pa_age()
,
sample_sbm()
,
sample_smallworld()
,
sample_traits_callaway()
,
sample_tree()
pf <- matrix(c(1, 0, 0, 1), nrow = 2) g <- sample_pref(20, 2, pref.matrix = pf) # example code tkplot(g, layout = layout_with_fr) pf <- matrix(c(0, 1, 0, 0), nrow = 2) g <- sample_asym_pref(20, 2, pref.matrix = pf) tkplot(g, layout = layout_in_circle)
pf <- matrix(c(1, 0, 0, 1), nrow = 2) g <- sample_pref(20, 2, pref.matrix = pf) # example code tkplot(g, layout = layout_with_fr) pf <- matrix(c(0, 1, 0, 0), nrow = 2) g <- sample_asym_pref(20, 2, pref.matrix = pf) tkplot(g, layout = layout_in_circle)
Sampling from the stochastic block model of networks
sample_sbm(n, pref.matrix, block.sizes, directed = FALSE, loops = FALSE) sbm(...)
sample_sbm(n, pref.matrix, block.sizes, directed = FALSE, loops = FALSE) sbm(...)
n |
Number of vertices in the graph. |
pref.matrix |
The matrix giving the Bernoulli rates. This is a
|
block.sizes |
Numeric vector giving the number of vertices in each group. The sum of the vector must match the number of vertices. |
directed |
Logical scalar, whether to generate a directed graph. |
loops |
Logical scalar, whether self-loops are allowed in the graph. |
... |
Passed to |
This function samples graphs from a stochastic block model by (doing the
equivalent of) Bernoulli trials for each potential edge with the
probabilities given by the Bernoulli rate matrix, pref.matrix
.
The order of the vertices in the generated graph corresponds to the
block.sizes
argument.
An igraph graph.
Gabor Csardi [email protected]
Faust, K., & Wasserman, S. (1992a). Blockmodels: Interpretation and evaluation. Social Networks, 14, 5–61.
Random graph models (games)
erdos.renyi.game()
,
sample_()
,
sample_bipartite()
,
sample_chung_lu()
,
sample_correlated_gnp()
,
sample_correlated_gnp_pair()
,
sample_degseq()
,
sample_dot_product()
,
sample_fitness()
,
sample_fitness_pl()
,
sample_forestfire()
,
sample_gnm()
,
sample_gnp()
,
sample_grg()
,
sample_growing()
,
sample_hierarchical_sbm()
,
sample_islands()
,
sample_k_regular()
,
sample_last_cit()
,
sample_pa()
,
sample_pa_age()
,
sample_pref()
,
sample_smallworld()
,
sample_traits_callaway()
,
sample_tree()
## Two groups with not only few connection between groups pm <- cbind(c(.1, .001), c(.001, .05)) g <- sample_sbm(1000, pref.matrix = pm, block.sizes = c(300, 700)) g
## Two groups with not only few connection between groups pm <- cbind(c(.1, .001), c(.001, .05)) g <- sample_sbm(1000, pref.matrix = pm, block.sizes = c(300, 700)) g
This function provides a very efficient way to pull an integer random sample sequence from an integer interval.
sample_seq(low, high, length)
sample_seq(low, high, length)
low |
The lower limit of the interval (inclusive). |
high |
The higher limit of the interval (inclusive). |
length |
The length of the sample. |
The algorithm runs in O(length)
expected time, even if
high-low
is big. It is much faster (but of course less general) than
the builtin sample
function of R.
An increasing numeric vector containing integers, the sample.
Gabor Csardi [email protected]
Jeffrey Scott Vitter: An Efficient Algorithm for Sequential Random Sampling, ACM Transactions on Mathematical Software, 13/1, 58–67.
Other other:
convex_hull()
,
running_mean()
rs <- sample_seq(1, 100000000, 10) rs
rs <- sample_seq(1, 100000000, 10) rs
This function generates networks with the small-world property
based on a variant of the Watts-Strogatz model. The network is obtained
by first creating a periodic undirected lattice, then rewiring both
endpoints of each edge with probability p
, while avoiding the
creation of multi-edges.
sample_smallworld(dim, size, nei, p, loops = FALSE, multiple = FALSE) smallworld(...)
sample_smallworld(dim, size, nei, p, loops = FALSE, multiple = FALSE) smallworld(...)
dim |
Integer constant, the dimension of the starting lattice. |
size |
Integer constant, the size of the lattice along each dimension. |
nei |
Integer constant, the neighborhood within which the vertices of the lattice will be connected. |
p |
Real constant between zero and one, the rewiring probability. |
loops |
Logical scalar, whether loops edges are allowed in the generated graph. |
multiple |
Logical scalar, whether multiple edges are allowed int the generated graph. |
... |
Passed to |
Note that this function might create graphs with loops and/or multiple
edges. You can use simplify()
to get rid of these.
This process differs from the original model of Watts and Strogatz
(see reference) in that it rewires both endpoints of edges. Thus in
the limit of p=1
, we obtain a G(n,m) random graph with the
same number of vertices and edges as the original lattice. In comparison,
the original Watts-Strogatz model only rewires a single endpoint of each edge,
thus the network does not become fully random even for p=1
.
For appropriate choices of p
, both models exhibit the property of
simultaneously having short path lengths and high clustering.
A graph object.
Gabor Csardi [email protected]
Duncan J Watts and Steven H Strogatz: Collective dynamics of ‘small world’ networks, Nature 393, 440-442, 1998.
Random graph models (games)
erdos.renyi.game()
,
sample_()
,
sample_bipartite()
,
sample_chung_lu()
,
sample_correlated_gnp()
,
sample_correlated_gnp_pair()
,
sample_degseq()
,
sample_dot_product()
,
sample_fitness()
,
sample_fitness_pl()
,
sample_forestfire()
,
sample_gnm()
,
sample_gnp()
,
sample_grg()
,
sample_growing()
,
sample_hierarchical_sbm()
,
sample_islands()
,
sample_k_regular()
,
sample_last_cit()
,
sample_pa()
,
sample_pa_age()
,
sample_pref()
,
sample_sbm()
,
sample_traits_callaway()
,
sample_tree()
g <- sample_smallworld(1, 100, 5, 0.05) mean_distance(g) transitivity(g, type = "average")
g <- sample_smallworld(1, 100, 5, 0.05) mean_distance(g) transitivity(g, type = "average")
sample_spanning_tree()
picks a spanning tree of an undirected graph
randomly and uniformly, using loop-erased random walks.
sample_spanning_tree(graph, vid = 0)
sample_spanning_tree(graph, vid = 0)
graph |
The input graph to sample from. Edge directions are ignored if the graph is directed. |
vid |
When the graph is disconnected, this argument specifies how to handle the situation. When the argument is zero (the default), the sampling will be performed component-wise, and the result will be a spanning forest. When the argument contains a vertex ID, only the component containing the given vertex will be processed, and the result will be a spanning tree of the component of the graph. |
An edge sequence containing the edges of the spanning tree. Use
subgraph_from_edges()
to extract the corresponding subgraph.
igraph_random_spanning_tree()
.
subgraph_from_edges()
to extract the tree itself
Other trees:
is_forest()
,
is_tree()
,
make_from_prufer()
,
to_prufer()
g <- make_full_graph(10) %du% make_full_graph(5) edges <- sample_spanning_tree(g) forest <- subgraph_from_edges(g, edges)
g <- make_full_graph(10) %du% make_full_graph(5) edges <- sample_spanning_tree(g) forest <- subgraph_from_edges(g, edges)
Sample finite-dimensional vectors to use as latent position vectors in random dot product graphs
sample_sphere_surface(dim, n = 1, radius = 1, positive = TRUE)
sample_sphere_surface(dim, n = 1, radius = 1, positive = TRUE)
dim |
Integer scalar, the dimension of the random vectors. |
n |
Integer scalar, the sample size. |
radius |
Numeric scalar, the radius of the sphere to sample. |
positive |
Logical scalar, whether to sample from the positive orthant of the sphere. |
sample_sphere_surface()
generates uniform samples from
(the
(dim-1)
-sphere) with radius radius
, i.e. the Euclidean
norm of the samples equal radius
.
A dim
(length of the alpha
vector for
sample_dirichlet()
) times n
matrix, whose columns are the sample
vectors.
Other latent position vector samplers:
sample_dirichlet()
,
sample_sphere_volume()
lpvs.sph <- sample_sphere_surface(dim = 10, n = 20, radius = 1) RDP.graph.3 <- sample_dot_product(lpvs.sph) vec.norm <- apply(lpvs.sph, 2, function(x) { sum(x^2) }) vec.norm
lpvs.sph <- sample_sphere_surface(dim = 10, n = 20, radius = 1) RDP.graph.3 <- sample_dot_product(lpvs.sph) vec.norm <- apply(lpvs.sph, 2, function(x) { sum(x^2) }) vec.norm
Sample finite-dimensional vectors to use as latent position vectors in random dot product graphs
sample_sphere_volume(dim, n = 1, radius = 1, positive = TRUE)
sample_sphere_volume(dim, n = 1, radius = 1, positive = TRUE)
dim |
Integer scalar, the dimension of the random vectors. |
n |
Integer scalar, the sample size. |
radius |
Numeric scalar, the radius of the sphere to sample. |
positive |
Logical scalar, whether to sample from the positive orthant of the sphere. |
sample_sphere_volume()
generates uniform samples from
(the
(dim-1)
-sphere) i.e. the Euclidean norm of the samples is
smaller or equal to radius
.
A dim
(length of the alpha
vector for
sample_dirichlet()
) times n
matrix, whose columns are the sample
vectors.
Other latent position vector samplers:
sample_dirichlet()
,
sample_sphere_surface()
lpvs.sph.vol <- sample_sphere_volume(dim = 10, n = 20, radius = 1) RDP.graph.4 <- sample_dot_product(lpvs.sph.vol) vec.norm <- apply(lpvs.sph.vol, 2, function(x) { sum(x^2) }) vec.norm
lpvs.sph.vol <- sample_sphere_volume(dim = 10, n = 20, radius = 1) RDP.graph.4 <- sample_dot_product(lpvs.sph.vol) vec.norm <- apply(lpvs.sph.vol, 2, function(x) { sum(x^2) }) vec.norm
These functions implement evolving network models based on different vertex types.
sample_traits_callaway( nodes, types, edge.per.step = 1, type.dist = rep(1, types), pref.matrix = matrix(1, types, types), directed = FALSE ) traits_callaway(...) sample_traits( nodes, types, k = 1, type.dist = rep(1, types), pref.matrix = matrix(1, types, types), directed = FALSE ) traits(...)
sample_traits_callaway( nodes, types, edge.per.step = 1, type.dist = rep(1, types), pref.matrix = matrix(1, types, types), directed = FALSE ) traits_callaway(...) sample_traits( nodes, types, k = 1, type.dist = rep(1, types), pref.matrix = matrix(1, types, types), directed = FALSE ) traits(...)
nodes |
The number of vertices in the graph. |
types |
The number of different vertex types. |
edge.per.step |
The number of edges to add to the graph per time step. |
type.dist |
The distribution of the vertex types. This is assumed to be stationary in time. |
pref.matrix |
A matrix giving the preferences of the given vertex types. These should be probabilities, i.e. numbers between zero and one. |
directed |
Logical constant, whether to generate directed graphs. |
... |
Passed to the constructor, |
k |
The number of trials per time step, see details below. |
For sample_traits_callaway()
the simulation goes like this: in each
discrete time step a new vertex is added to the graph. The type of this
vertex is generated based on type.dist
. Then two vertices are
selected uniformly randomly from the graph. The probability that they will
be connected depends on the types of these vertices and is taken from
pref.matrix
. Then another two vertices are selected and this is
repeated edges.per.step
times in each time step.
For sample_traits()
the simulation goes like this: a single vertex is
added at each time step. This new vertex tries to connect to k
vertices in the graph. The probability that such a connection is realized
depends on the types of the vertices involved and is taken from
pref.matrix
.
A new graph object.
Gabor Csardi [email protected]
Random graph models (games)
erdos.renyi.game()
,
sample_()
,
sample_bipartite()
,
sample_chung_lu()
,
sample_correlated_gnp()
,
sample_correlated_gnp_pair()
,
sample_degseq()
,
sample_dot_product()
,
sample_fitness()
,
sample_fitness_pl()
,
sample_forestfire()
,
sample_gnm()
,
sample_gnp()
,
sample_grg()
,
sample_growing()
,
sample_hierarchical_sbm()
,
sample_islands()
,
sample_k_regular()
,
sample_last_cit()
,
sample_pa()
,
sample_pa_age()
,
sample_pref()
,
sample_sbm()
,
sample_smallworld()
,
sample_tree()
# two types of vertices, they like only themselves g1 <- sample_traits_callaway(1000, 2, pref.matrix = matrix(c(1, 0, 0, 1), ncol = 2)) g2 <- sample_traits(1000, 2, k = 2, pref.matrix = matrix(c(1, 0, 0, 1), ncol = 2))
# two types of vertices, they like only themselves g1 <- sample_traits_callaway(1000, 2, pref.matrix = matrix(c(1, 0, 0, 1), ncol = 2)) g2 <- sample_traits(1000, 2, k = 2, pref.matrix = matrix(c(1, 0, 0, 1), ncol = 2))
sample_tree()
generates a random with a given number of nodes uniform
at random from the set of labelled trees.
sample_tree(n, directed = FALSE, method = c("lerw", "prufer"))
sample_tree(n, directed = FALSE, method = c("lerw", "prufer"))
n |
The number of nodes in the tree |
directed |
Whether to create a directed tree. The edges of the tree are oriented away from the root. |
method |
The algorithm to use to generate the tree. ‘prufer’ samples Prüfer sequences uniformly and then converts the sampled sequence to a tree. ‘lerw’ performs a loop-erased random walk on the complete graph to uniformly sampleits spanning trees. (This is also known as Wilson's algorithm). The default is ‘lerw’. Note that the method based on Prüfer sequences does not support directed trees at the moment. |
In other words, the function generates each possible labelled tree with the given number of nodes with the same probability.
A graph object.
Random graph models (games)
erdos.renyi.game()
,
sample_()
,
sample_bipartite()
,
sample_chung_lu()
,
sample_correlated_gnp()
,
sample_correlated_gnp_pair()
,
sample_degseq()
,
sample_dot_product()
,
sample_fitness()
,
sample_fitness_pl()
,
sample_forestfire()
,
sample_gnm()
,
sample_gnp()
,
sample_grg()
,
sample_growing()
,
sample_hierarchical_sbm()
,
sample_islands()
,
sample_k_regular()
,
sample_last_cit()
,
sample_pa()
,
sample_pa_age()
,
sample_pref()
,
sample_sbm()
,
sample_smallworld()
,
sample_traits_callaway()
g <- sample_tree(100, method = "lerw")
g <- sample_tree(100, method = "lerw")
Calculate scan statistics on a time series of graphs. This is done by calculating the local scan statistics for each graph and each vertex, and then normalizing across the vertices and across the time steps.
scan_stat(graphs, tau = 1, ell = 0, locality = c("us", "them"), ...)
scan_stat(graphs, tau = 1, ell = 0, locality = c("us", "them"), ...)
graphs |
A list of igraph graph objects. They must be all directed or all undirected and they must have the same number of vertices. |
tau |
The number of previous time steps to consider for the time-dependent normalization for individual vertices. In other words, the current locality statistics of each vertex will be compared to this many previous time steps of the same vertex to decide whether it is significantly larger. |
ell |
The number of previous time steps to consider for the aggregated scan statistics. This is essentially a smoothing parameter. |
locality |
Whether to calculate the ‘us’ or ‘them’ statistics. |
... |
Extra arguments are passed to |
A list with entries:
stat |
The scan statistics in each time step. It is |
arg_max_v |
The (numeric) vertex ids for the vertex with
the largest locality statistics, at each time step. It is |
Other scan statistics:
local_scan()
## Generate a bunch of SBMs, with the last one being different num_t <- 20 block_sizes <- c(10, 5, 5) p_ij <- list(p = 0.1, h = 0.9, q = 0.9) P0 <- matrix(p_ij$p, 3, 3) P0[2, 2] <- p_ij$h PA <- P0 PA[3, 3] <- p_ij$q num_v <- sum(block_sizes) tsg <- replicate(num_t - 1, P0, simplify = FALSE) %>% append(list(PA)) %>% lapply(sample_sbm, n = num_v, block.sizes = block_sizes, directed = TRUE) scan_stat(graphs = tsg, k = 1, tau = 4, ell = 2) scan_stat(graphs = tsg, locality = "them", k = 1, tau = 4, ell = 2)
## Generate a bunch of SBMs, with the last one being different num_t <- 20 block_sizes <- c(10, 5, 5) p_ij <- list(p = 0.1, h = 0.9, q = 0.9) P0 <- matrix(p_ij$p, 3, 3) P0[2, 2] <- p_ij$h PA <- P0 PA[3, 3] <- p_ij$q num_v <- sum(block_sizes) tsg <- replicate(num_t - 1, P0, simplify = FALSE) %>% append(list(PA)) %>% lapply(sample_sbm, n = num_v, block.sizes = block_sizes, directed = TRUE) scan_stat(graphs = tsg, k = 1, tau = 4, ell = 2) scan_stat(graphs = tsg, locality = "them", k = 1, tau = 4, ell = 2)
This is the ‘OrRd’ palette from https://colorbrewer2.org/. It has at most nine colors.
sequential_pal(n)
sequential_pal(n)
n |
The number of colors in the palette. The maximum is nine currently. |
Use this palette, if vertex colors mark some ordinal quantity, e.g. some centrality measure, or some ordinal vertex covariate, like the age of people, or their seniority level.
A character vector of RGB color codes.
Other palettes:
categorical_pal()
,
diverging_pal()
,
r_pal()
library(igraphdata) data(karate) karate <- karate %>% add_layout_(with_kk()) %>% set_vertex_attr("size", value = 10) V(karate)$color <- scales::dscale(degree(karate) %>% cut(5), sequential_pal) plot(karate)
library(igraphdata) data(karate) karate <- karate %>% add_layout_(with_kk()) %>% set_vertex_attr("size", value = 10) V(karate)$color <- scales::dscale(degree(karate) %>% cut(5), sequential_pal) plot(karate)
Set edge attributes
set_edge_attr(graph, name, index = E(graph), value)
set_edge_attr(graph, name, index = E(graph), value)
graph |
The graph |
name |
The name of the attribute to set. |
index |
An optional edge sequence to set the attributes of a subset of edges. |
value |
The new value of the attribute for all (or |
The graph, with the edge attribute added or set.
Vertex, edge and graph attributes
delete_edge_attr()
,
delete_graph_attr()
,
delete_vertex_attr()
,
edge_attr()
,
edge_attr<-()
,
edge_attr_names()
,
graph_attr()
,
graph_attr<-()
,
graph_attr_names()
,
igraph-attribute-combination
,
igraph-dollar
,
igraph-vs-attributes
,
set_graph_attr()
,
set_vertex_attr()
,
vertex_attr()
,
vertex_attr<-()
,
vertex_attr_names()
g <- make_ring(10) %>% set_edge_attr("label", value = LETTERS[1:10]) g plot(g)
g <- make_ring(10) %>% set_edge_attr("label", value = LETTERS[1:10]) g plot(g)
An existing attribute with the same name is overwritten.
set_graph_attr(graph, name, value)
set_graph_attr(graph, name, value)
graph |
The graph. |
name |
The name of the attribute to set. |
value |
New value of the attribute. |
The graph with the new graph attribute added or set.
Vertex, edge and graph attributes
delete_edge_attr()
,
delete_graph_attr()
,
delete_vertex_attr()
,
edge_attr()
,
edge_attr<-()
,
edge_attr_names()
,
graph_attr()
,
graph_attr<-()
,
graph_attr_names()
,
igraph-attribute-combination
,
igraph-dollar
,
igraph-vs-attributes
,
set_edge_attr()
,
set_vertex_attr()
,
vertex_attr()
,
vertex_attr<-()
,
vertex_attr_names()
g <- make_ring(10) %>% set_graph_attr("layout", layout_with_fr) g plot(g)
g <- make_ring(10) %>% set_graph_attr("layout", layout_with_fr) g plot(g)
Set vertex attributes
set_vertex_attr(graph, name, index = V(graph), value)
set_vertex_attr(graph, name, index = V(graph), value)
graph |
The graph. |
name |
The name of the attribute to set. |
index |
An optional vertex sequence to set the attributes of a subset of vertices. |
value |
The new value of the attribute for all (or |
The graph, with the vertex attribute added or set.
Vertex, edge and graph attributes
delete_edge_attr()
,
delete_graph_attr()
,
delete_vertex_attr()
,
edge_attr()
,
edge_attr<-()
,
edge_attr_names()
,
graph_attr()
,
graph_attr<-()
,
graph_attr_names()
,
igraph-attribute-combination
,
igraph-dollar
,
igraph-vs-attributes
,
set_edge_attr()
,
set_graph_attr()
,
vertex_attr()
,
vertex_attr<-()
,
vertex_attr_names()
g <- make_ring(10) %>% set_vertex_attr("label", value = LETTERS[1:10]) g plot(g)
g <- make_ring(10) %>% set_vertex_attr("label", value = LETTERS[1:10]) g plot(g)
Starting from version 0.5.1 igraph supports different vertex shapes when plotting graphs.
shapes(shape = NULL) shape_noclip(coords, el, params, end = c("both", "from", "to")) shape_noplot(coords, v = NULL, params) add_shape(shape, clip = shape_noclip, plot = shape_noplot, parameters = list())
shapes(shape = NULL) shape_noclip(coords, el, params, end = c("both", "from", "to")) shape_noplot(coords, v = NULL, params) add_shape(shape, clip = shape_noclip, plot = shape_noplot, parameters = list())
shape |
Character scalar, name of a vertex shape. If it is
|
coords , el , params , end , v
|
See parameters of the clipping/plotting functions below. |
clip |
An R function object, the clipping function. |
plot |
An R function object, the plotting function. |
parameters |
Named list, additional plot/vertex/edge
parameters. The element named define the new parameters, and the
elements themselves define their default values.
Vertex parameters should have a prefix
‘ |
In igraph a vertex shape is defined by two functions: 1) provides information about the size of the shape for clipping the edges and 2) plots the shape if requested. These functions are called “shape functions” in the rest of this manual page. The first one is the clipping function and the second is the plotting function.
The clipping function has the following arguments:
A matrix with four columns, it contains the
coordinates of the vertices for the edge list supplied in the
el
argument.
A matrix with two columns, the edges of which some end
points will be clipped. It should have the same number of rows as
coords
.
This is a function object that can be called to query
vertex/edge/plot graphical parameters. The first argument of the
function is “vertex
”, “edge
” or
“plot
” to decide the type of the parameter, the
second is a character string giving the name of the
parameter. E.g.
params("vertex", "size")
Character string, it gives which end points will be
used. Possible values are “both
”,
“from
” and “to
”. If
“from
” the function is expected to clip the
first column in the el
edge list, “to
”
selects the second column, “both
” selects both.
The clipping function should return a matrix
with the same number of rows as the el
arguments.
If end
is both
then the matrix must have four
columns, otherwise two. The matrix contains the modified coordinates,
with the clipping applied.
The plotting function has the following arguments:
The coordinates of the vertices, a matrix with two columns.
The ids of the vertices to plot. It should match the number
of rows in the coords
argument.
The same as for the clipping function, see above.
The return value of the plotting function is not used.
shapes()
can be used to list the names of all installed
vertex shapes, by calling it without arguments, or setting the
shape
argument to NULL
. If a shape name is given, then
the clipping and plotting functions of that shape are returned in a
named list.
add_shape()
can be used to add new vertex shapes to
igraph. For this one must give the clipping and plotting functions of
the new shape. It is also possible to list the plot/vertex/edge
parameters, in the parameters
argument, that the clipping
and/or plotting functions can make use of. An example would be a
generic regular polygon shape, which can have a parameter for the
number of sides.
shape_noclip()
is a very simple clipping function that the
user can use in their own shape definitions. It does no clipping, the
edges will be drawn exactly until the listed vertex position
coordinates.
shape_noplot()
is a very simple (and probably not very
useful) plotting function, that does not plot anything.
shapes()
returns a character vector if the
shape
argument is NULL
. It returns a named list with
entries named ‘clip’ and ‘plot’, both of them R
functions.
add_shape()
returns TRUE
, invisibly.
shape_noclip()
returns the appropriate columns of its
coords
argument.
# all vertex shapes, minus "raster", that might not be available shapes <- setdiff(shapes(), "") g <- make_ring(length(shapes)) set.seed(42) plot(g, vertex.shape = shapes, vertex.label = shapes, vertex.label.dist = 1, vertex.size = 15, vertex.size2 = 15, vertex.pie = lapply(shapes, function(x) if (x == "pie") 2:6 else 0), vertex.pie.color = list(heat.colors(5)) ) # add new vertex shape, plot nothing with no clipping add_shape("nil") plot(g, vertex.shape = "nil") ################################################################# # triangle vertex shape mytriangle <- function(coords, v = NULL, params) { vertex.color <- params("vertex", "color") if (length(vertex.color) != 1 && !is.null(v)) { vertex.color <- vertex.color[v] } vertex.size <- 1 / 200 * params("vertex", "size") if (length(vertex.size) != 1 && !is.null(v)) { vertex.size <- vertex.size[v] } symbols( x = coords[, 1], y = coords[, 2], bg = vertex.color, stars = cbind(vertex.size, vertex.size, vertex.size), add = TRUE, inches = FALSE ) } # clips as a circle add_shape("triangle", clip = shapes("circle")$clip, plot = mytriangle ) plot(g, vertex.shape = "triangle", vertex.color = rainbow(vcount(g)), vertex.size = seq(10, 20, length.out = vcount(g)) ) ################################################################# # generic star vertex shape, with a parameter for number of rays mystar <- function(coords, v = NULL, params) { vertex.color <- params("vertex", "color") if (length(vertex.color) != 1 && !is.null(v)) { vertex.color <- vertex.color[v] } vertex.size <- 1 / 200 * params("vertex", "size") if (length(vertex.size) != 1 && !is.null(v)) { vertex.size <- vertex.size[v] } norays <- params("vertex", "norays") if (length(norays) != 1 && !is.null(v)) { norays <- norays[v] } mapply(coords[, 1], coords[, 2], vertex.color, vertex.size, norays, FUN = function(x, y, bg, size, nor) { symbols( x = x, y = y, bg = bg, stars = matrix(c(size, size / 2), nrow = 1, ncol = nor * 2), add = TRUE, inches = FALSE ) } ) } # no clipping, edges will be below the vertices anyway add_shape("star", clip = shape_noclip, plot = mystar, parameters = list(vertex.norays = 5) ) plot(g, vertex.shape = "star", vertex.color = rainbow(vcount(g)), vertex.size = seq(10, 20, length.out = vcount(g)) ) plot(g, vertex.shape = "star", vertex.color = rainbow(vcount(g)), vertex.size = seq(10, 20, length.out = vcount(g)), vertex.norays = rep(4:8, length.out = vcount(g)) )
# all vertex shapes, minus "raster", that might not be available shapes <- setdiff(shapes(), "") g <- make_ring(length(shapes)) set.seed(42) plot(g, vertex.shape = shapes, vertex.label = shapes, vertex.label.dist = 1, vertex.size = 15, vertex.size2 = 15, vertex.pie = lapply(shapes, function(x) if (x == "pie") 2:6 else 0), vertex.pie.color = list(heat.colors(5)) ) # add new vertex shape, plot nothing with no clipping add_shape("nil") plot(g, vertex.shape = "nil") ################################################################# # triangle vertex shape mytriangle <- function(coords, v = NULL, params) { vertex.color <- params("vertex", "color") if (length(vertex.color) != 1 && !is.null(v)) { vertex.color <- vertex.color[v] } vertex.size <- 1 / 200 * params("vertex", "size") if (length(vertex.size) != 1 && !is.null(v)) { vertex.size <- vertex.size[v] } symbols( x = coords[, 1], y = coords[, 2], bg = vertex.color, stars = cbind(vertex.size, vertex.size, vertex.size), add = TRUE, inches = FALSE ) } # clips as a circle add_shape("triangle", clip = shapes("circle")$clip, plot = mytriangle ) plot(g, vertex.shape = "triangle", vertex.color = rainbow(vcount(g)), vertex.size = seq(10, 20, length.out = vcount(g)) ) ################################################################# # generic star vertex shape, with a parameter for number of rays mystar <- function(coords, v = NULL, params) { vertex.color <- params("vertex", "color") if (length(vertex.color) != 1 && !is.null(v)) { vertex.color <- vertex.color[v] } vertex.size <- 1 / 200 * params("vertex", "size") if (length(vertex.size) != 1 && !is.null(v)) { vertex.size <- vertex.size[v] } norays <- params("vertex", "norays") if (length(norays) != 1 && !is.null(v)) { norays <- norays[v] } mapply(coords[, 1], coords[, 2], vertex.color, vertex.size, norays, FUN = function(x, y, bg, size, nor) { symbols( x = x, y = y, bg = bg, stars = matrix(c(size, size / 2), nrow = 1, ncol = nor * 2), add = TRUE, inches = FALSE ) } ) } # no clipping, edges will be below the vertices anyway add_shape("star", clip = shape_noclip, plot = mystar, parameters = list(vertex.norays = 5) ) plot(g, vertex.shape = "star", vertex.color = rainbow(vcount(g)), vertex.size = seq(10, 20, length.out = vcount(g)) ) plot(g, vertex.shape = "star", vertex.color = rainbow(vcount(g)), vertex.size = seq(10, 20, length.out = vcount(g)), vertex.norays = rep(4:8, length.out = vcount(g)) )
These functions calculates similarity scores for vertices based on their connection patterns.
similarity( graph, vids = V(graph), mode = c("all", "out", "in", "total"), loops = FALSE, method = c("jaccard", "dice", "invlogweighted") )
similarity( graph, vids = V(graph), mode = c("all", "out", "in", "total"), loops = FALSE, method = c("jaccard", "dice", "invlogweighted") )
graph |
The input graph. |
vids |
The vertex ids for which the similarity is calculated. |
mode |
The type of neighboring vertices to use for the calculation,
possible values: ‘ |
loops |
Whether to include vertices themselves in the neighbor sets. |
method |
The method to use. |
The Jaccard similarity coefficient of two vertices is the number of common
neighbors divided by the number of vertices that are neighbors of at least
one of the two vertices being considered. The jaccard
method
calculates the pairwise Jaccard similarities for some (or all) of the
vertices.
The Dice similarity coefficient of two vertices is twice the number of
common neighbors divided by the sum of the degrees of the vertices.
Methof dice
calculates the pairwise Dice similarities for some
(or all) of the vertices.
The inverse log-weighted similarity of two vertices is the number of their common neighbors, weighted by the inverse logarithm of their degrees. It is based on the assumption that two vertices should be considered more similar if they share a low-degree common neighbor, since high-degree common neighbors are more likely to appear even by pure chance. Isolated vertices will have zero similarity to any other vertex. Self-similarities are not calculated. See the following paper for more details: Lada A. Adamic and Eytan Adar: Friends and neighbors on the Web. Social Networks, 25(3):211-230, 2003.
A length(vids)
by length(vids)
numeric matrix
containing the similarity scores. This argument is ignored by the
invlogweighted
method.
igraph_similarity_jaccard()
, igraph_similarity_dice()
, igraph_similarity_inverse_log_weighted()
.
Tamas Nepusz [email protected] and Gabor Csardi [email protected] for the manual page.
Lada A. Adamic and Eytan Adar: Friends and neighbors on the Web. Social Networks, 25(3):211-230, 2003.
Other cocitation:
cocitation()
g <- make_ring(5) similarity(g, method = "dice") similarity(g, method = "jaccard")
g <- make_ring(5) similarity(g, method = "dice") similarity(g, method = "jaccard")
Constructor modifier to drop multiple and loop edges
simplified()
simplified()
Constructor modifiers (and related functions)
make_()
,
sample_()
,
with_edge_()
,
with_graph_()
,
with_vertex_()
,
without_attr()
,
without_loops()
,
without_multiples()
sample_(pa(10, m = 3, algorithm = "bag")) sample_(pa(10, m = 3, algorithm = "bag"), simplified())
sample_(pa(10, m = 3, algorithm = "bag")) sample_(pa(10, m = 3, algorithm = "bag"), simplified())
Simple graphs are graphs which do not contain loop and multiple edges.
simplify( graph, remove.multiple = TRUE, remove.loops = TRUE, edge.attr.comb = igraph_opt("edge.attr.comb") ) is_simple(graph) simplify_and_colorize(graph)
simplify( graph, remove.multiple = TRUE, remove.loops = TRUE, edge.attr.comb = igraph_opt("edge.attr.comb") ) is_simple(graph) simplify_and_colorize(graph)
graph |
The graph to work on. |
remove.multiple |
Logical, whether the multiple edges are to be removed. |
remove.loops |
Logical, whether the loop edges are to be removed. |
edge.attr.comb |
Specifies what to do with edge attributes, if
|
A loop edge is an edge for which the two endpoints are the same vertex. Two edges are multiple edges if they have exactly the same two endpoints (for directed graphs order does matter). A graph is simple is it does not contain loop edges and multiple edges.
is_simple()
checks whether a graph is simple.
simplify()
removes the loop and/or multiple edges from a graph. If
both remove.loops
and remove.multiple
are TRUE
the
function returns a simple graph.
simplify_and_colorize()
constructs a new, simple graph from a graph and
also sets a color
attribute on both the vertices and the edges.
The colors of the vertices represent the number of self-loops that were
originally incident on them, while the colors of the edges represent the
multiplicities of the same edges in the original graph. This allows one to
take into account the edge multiplicities and the number of loop edges in
the VF2 isomorphism algorithm. Other graph, vertex and edge attributes from
the original graph are discarded as the primary purpose of this function is
to facilitate the usage of multigraphs with the VF2 algorithm.
a new graph object with the edges deleted.
igraph_simplify()
, igraph_is_simple()
.
Gabor Csardi [email protected]
which_loop()
, which_multiple()
and
count_multiple()
, delete_edges()
,
delete_vertices()
Other functions for manipulating graph structure:
+.igraph()
,
add_edges()
,
add_vertices()
,
complementer()
,
compose()
,
connect()
,
contract()
,
delete_edges()
,
delete_vertices()
,
difference()
,
difference.igraph()
,
disjoint_union()
,
edge()
,
igraph-minus
,
intersection()
,
intersection.igraph()
,
path()
,
permute()
,
rep.igraph()
,
reverse_edges()
,
union()
,
union.igraph()
,
vertex()
g <- make_graph(c(1, 2, 1, 2, 3, 3)) is_simple(g) is_simple(simplify(g, remove.loops = FALSE)) is_simple(simplify(g, remove.multiple = FALSE)) is_simple(simplify(g))
g <- make_graph(c(1, 2, 1, 2, 3, 3)) is_simple(g) is_simple(simplify(g, remove.loops = FALSE)) is_simple(simplify(g, remove.multiple = FALSE)) is_simple(simplify(g))
Calculate selected eigenvalues and eigenvectors of a (supposedly sparse) graph.
spectrum( graph, algorithm = c("arpack", "auto", "lapack", "comp_auto", "comp_lapack", "comp_arpack"), which = list(), options = arpack_defaults() )
spectrum( graph, algorithm = c("arpack", "auto", "lapack", "comp_auto", "comp_lapack", "comp_arpack"), which = list(), options = arpack_defaults() )
graph |
The input graph, can be directed or undirected. |
algorithm |
The algorithm to use. Currently only |
which |
A list to specify which eigenvalues and eigenvectors to calculate. By default the leading (i.e. largest magnitude) eigenvalue and the corresponding eigenvector is calculated. |
options |
Options for the ARPACK solver. See
|
The which
argument is a list and it specifies which eigenvalues and
corresponding eigenvectors to calculate: There are eight options:
Eigenvalues with the largest magnitude. Set pos
to
LM
, and howmany
to the number of eigenvalues you want.
Eigenvalues with the smallest magnitude. Set pos
to SM
and
howmany
to the number of eigenvalues you want.
Largest
eigenvalues. Set pos
to LA
and howmany
to the number of
eigenvalues you want.
Smallest eigenvalues. Set pos
to
SA
and howmany
to the number of eigenvalues you want.
Eigenvalues from both ends of the spectrum. Set pos
to BE
and
howmany
to the number of eigenvalues you want. If howmany
is
odd, then one more eigenvalue is returned from the larger end.
Selected eigenvalues. This is not (yet) implemented currently.
Eigenvalues in an interval. This is not (yet) implemented.
All
eigenvalues. This is not implemented yet. The standard eigen
function
does a better job at this, anyway.
Note that ARPACK might be unstable for graphs with multiple components, e.g. graphs with isolate vertices.
Depends on the algorithm used.
For arpack
a list with three entries is returned:
options |
See
the return value for |
values |
Numeric vector, the eigenvalues. |
vectors |
Numeric matrix, with the eigenvectors as columns. |
Gabor Csardi [email protected]
as_adjacency_matrix()
to create a (sparse) adjacency matrix.
Centrality measures
alpha_centrality()
,
authority_score()
,
betweenness()
,
closeness()
,
diversity()
,
eigen_centrality()
,
harmonic_centrality()
,
hits_scores()
,
page_rank()
,
power_centrality()
,
strength()
,
subgraph_centrality()
## Small example graph, leading eigenvector by default kite <- make_graph("Krackhardt_kite") spectrum(kite)[c("values", "vectors")] ## Double check eigen(as_adjacency_matrix(kite, sparse = FALSE))$vectors[, 1] ## Should be the same as 'eigen_centrality' (but rescaled) cor(eigen_centrality(kite)$vector, spectrum(kite)$vectors) ## Smallest eigenvalues spectrum(kite, which = list(pos = "SM", howmany = 2))$values
## Small example graph, leading eigenvector by default kite <- make_graph("Krackhardt_kite") spectrum(kite)[c("values", "vectors")] ## Double check eigen(as_adjacency_matrix(kite, sparse = FALSE))$vectors[, 1] ## Should be the same as 'eigen_centrality' (but rescaled) cor(eigen_centrality(kite)$vector, spectrum(kite)$vectors) ## Smallest eigenvalues spectrum(kite, which = list(pos = "SM", howmany = 2))$values
The split-join distance between partitions A and B is the sum of the projection distance of A from B and the projection distance of B from A. The projection distance is an asymmetric measure and it is defined as follows:
split_join_distance(comm1, comm2)
split_join_distance(comm1, comm2)
comm1 |
The first community structure. |
comm2 |
The second community structure. |
First, each set in partition A is evaluated against all sets in partition B. For each set in partition A, the best matching set in partition B is found and the overlap size is calculated. (Matching is quantified by the size of the overlap between the two sets). Then, the maximal overlap sizes for each set in A are summed together and subtracted from the number of elements in A.
The split-join distance will be returned as two numbers, the first is the projection distance of the first partition from the second, while the second number is the projection distance of the second partition from the first. This makes it easier to detect whether a partition is a subpartition of the other, since in this case, the corresponding distance will be zero.
Two integer numbers, see details below.
van Dongen S: Performance criteria for graph clustering and Markov cluster experiments. Technical Report INS-R0012, National Research Institute for Mathematics and Computer Science in the Netherlands, Amsterdam, May 2000.
Community detection
as_membership()
,
cluster_edge_betweenness()
,
cluster_fast_greedy()
,
cluster_fluid_communities()
,
cluster_infomap()
,
cluster_label_prop()
,
cluster_leading_eigen()
,
cluster_leiden()
,
cluster_louvain()
,
cluster_optimal()
,
cluster_spinglass()
,
cluster_walktrap()
,
compare()
,
groups()
,
make_clusters()
,
membership()
,
modularity.igraph()
,
plot_dendrogram()
,
voronoi_cells()
List all (s,t)-cuts in a directed graph.
st_cuts(graph, source, target)
st_cuts(graph, source, target)
graph |
The input graph. It must be directed. |
source |
The source vertex. |
target |
The target vertex. |
Given a directed graph and two, different and non-ajacent vertices,
and
, an
-cut is a set of edges, such that after
removing these edges from
there is no directed path from
to
.
A list with entries:
cuts |
A list of numeric vectors
containing edge ids. Each vector is an |
partition1s |
A list of numeric vectors containing vertex ids, they
correspond to the edge cuts. Each vertex set is a generator of the
corresponding cut, i.e. in the graph |
Gabor Csardi [email protected]
JS Provan and DR Shier: A Paradigm for listing (s,t)-cuts in graphs, Algorithmica 15, 351–372, 1996.
Other flow:
dominator_tree()
,
edge_connectivity()
,
is_min_separator()
,
is_separator()
,
max_flow()
,
min_cut()
,
min_separators()
,
min_st_separators()
,
st_min_cuts()
,
vertex_connectivity()
# A very simple graph g <- graph_from_literal(a -+ b -+ c -+ d -+ e) st_cuts(g, source = "a", target = "e") # A somewhat more difficult graph g2 <- graph_from_literal( s --+ a:b, a:b --+ t, a --+ 1:2:3, 1:2:3 --+ b ) st_cuts(g2, source = "s", target = "t")
# A very simple graph g <- graph_from_literal(a -+ b -+ c -+ d -+ e) st_cuts(g, source = "a", target = "e") # A somewhat more difficult graph g2 <- graph_from_literal( s --+ a:b, a:b --+ t, a --+ 1:2:3, 1:2:3 --+ b ) st_cuts(g2, source = "s", target = "t")
-cuts of a graphListing all minimum -cuts of a directed graph, for given
and
.
st_min_cuts(graph, source, target, capacity = NULL)
st_min_cuts(graph, source, target, capacity = NULL)
graph |
The input graph. It must be directed. |
source |
The id of the source vertex. |
target |
The id of the target vertex. |
capacity |
Numeric vector giving the edge capacities. If this is
|
Given a directed graph and two, different and non-ajacent vertices,
and
, an
-cut is a set of edges, such that after
removing these edges from
there is no directed path from
to
.
The size of an -cut is defined as the sum of the capacities (or
weights) in the cut. For unweighted (=equally weighted) graphs, this is
simply the number of edges.
An -cut is minimum if it is of the smallest possible size.
A list with entries:
value |
Numeric scalar, the size of the minimum cut(s). |
cuts |
A list of numeric vectors containing edge ids.
Each vector is a minimum |
partition1s |
A list of
numeric vectors containing vertex ids, they correspond to the edge cuts.
Each vertex set is a generator of the corresponding cut, i.e. in the graph
|
Gabor Csardi [email protected]
JS Provan and DR Shier: A Paradigm for listing (s,t)-cuts in graphs, Algorithmica 15, 351–372, 1996.
Other flow:
dominator_tree()
,
edge_connectivity()
,
is_min_separator()
,
is_separator()
,
max_flow()
,
min_cut()
,
min_separators()
,
min_st_separators()
,
st_cuts()
,
vertex_connectivity()
# A difficult graph, from the Provan-Shier paper g <- graph_from_literal( s --+ a:b, a:b --+ t, a --+ 1:2:3:4:5, 1:2:3:4:5 --+ b ) st_min_cuts(g, source = "s", target = "t")
# A difficult graph, from the Provan-Shier paper g <- graph_from_literal( s --+ a:b, a:b --+ t, a --+ 1:2:3:4:5, 1:2:3:4:5 --+ b ) st_min_cuts(g, source = "s", target = "t")
Retrieves the stochastic matrix of a graph of class igraph
.
stochastic_matrix( graph, column.wise = FALSE, sparse = igraph_opt("sparsematrices") )
stochastic_matrix( graph, column.wise = FALSE, sparse = igraph_opt("sparsematrices") )
graph |
The input graph. Must be of class |
column.wise |
If |
sparse |
Logical scalar, whether to return a sparse matrix. The
|
Let be an
adjacency matrix with real
non-negative entries. Let us define
The (row) stochastic matrix is defined as
where it is assumed that is non-singular. Column stochastic
matrices are defined in a symmetric way.
A regular matrix or a matrix of class Matrix
if a
sparse
argument was TRUE
.
Gabor Csardi [email protected]
library(Matrix) ## g is a large sparse graph g <- sample_pa(n = 10^5, power = 2, directed = FALSE) W <- stochastic_matrix(g, sparse = TRUE) ## a dense matrix here would probably not fit in the memory class(W) ## may not be exactly 1, due to numerical errors max(abs(rowSums(W)) - 1)
library(Matrix) ## g is a large sparse graph g <- sample_pa(n = 10^5, power = 2, directed = FALSE) W <- stochastic_matrix(g, sparse = TRUE) ## a dense matrix here would probably not fit in the memory class(W) ## may not be exactly 1, due to numerical errors max(abs(rowSums(W)) - 1)
Summing up the edge weights of the adjacent edges for each vertex.
strength( graph, vids = V(graph), mode = c("all", "out", "in", "total"), loops = TRUE, weights = NULL )
strength( graph, vids = V(graph), mode = c("all", "out", "in", "total"), loops = TRUE, weights = NULL )
graph |
The input graph. |
vids |
The vertices for which the strength will be calculated. |
mode |
Character string, “out” for out-degree, “in” for in-degree or “all” for the sum of the two. For undirected graphs this argument is ignored. |
loops |
Logical; whether the loop edges are also counted. |
weights |
Weight vector. If the graph has a |
A numeric vector giving the strength of the vertices.
Gabor Csardi [email protected]
Alain Barrat, Marc Barthelemy, Romualdo Pastor-Satorras, Alessandro Vespignani: The architecture of complex weighted networks, Proc. Natl. Acad. Sci. USA 101, 3747 (2004)
degree()
for the unweighted version.
Centrality measures
alpha_centrality()
,
authority_score()
,
betweenness()
,
closeness()
,
diversity()
,
eigen_centrality()
,
harmonic_centrality()
,
hits_scores()
,
page_rank()
,
power_centrality()
,
spectrum()
,
subgraph_centrality()
g <- make_star(10) E(g)$weight <- seq(ecount(g)) strength(g) strength(g, mode = "out") strength(g, mode = "in") # No weights g <- make_ring(10) strength(g)
g <- make_star(10) E(g)$weight <- seq(ecount(g)) strength(g) strength(g, mode = "out") strength(g, mode = "in") # No weights g <- make_ring(10) strength(g)
Finds all vertices reachable from a given vertex, or the opposite: all vertices from which a given vertex is reachable via a directed path.
subcomponent(graph, v, mode = c("all", "out", "in"))
subcomponent(graph, v, mode = c("all", "out", "in"))
graph |
The graph to analyze. |
v |
The vertex to start the search from. |
mode |
Character string, either “in”, “out” or
“all”. If “in” all vertices from which |
A breadth-first search is conducted starting from vertex v
.
Numeric vector, the ids of the vertices in the same component as
v
.
Gabor Csardi [email protected]
Other structural.properties:
bfs()
,
component_distribution()
,
connect()
,
constraint()
,
coreness()
,
degree()
,
dfs()
,
distance_table()
,
edge_density()
,
feedback_arc_set()
,
girth()
,
is_acyclic()
,
is_dag()
,
is_matching()
,
k_shortest_paths()
,
knn()
,
reciprocity()
,
subgraph()
,
topo_sort()
,
transitivity()
,
unfold_tree()
,
which_multiple()
,
which_mutual()
g <- sample_gnp(100, 1 / 200) subcomponent(g, 1, "in") subcomponent(g, 1, "out") subcomponent(g, 1, "all")
g <- sample_gnp(100, 1 / 200) subcomponent(g, 1, "in") subcomponent(g, 1, "out") subcomponent(g, 1, "all")
subgraph()
creates a subgraph of a graph, containing only the specified
vertices and all the edges among them.
subgraph(graph, vids) induced_subgraph( graph, vids, impl = c("auto", "copy_and_delete", "create_from_scratch") ) subgraph_from_edges(graph, eids, delete.vertices = TRUE)
subgraph(graph, vids) induced_subgraph( graph, vids, impl = c("auto", "copy_and_delete", "create_from_scratch") ) subgraph_from_edges(graph, eids, delete.vertices = TRUE)
graph |
The original graph. |
vids |
Numeric vector, the vertices of the original graph which will form the subgraph. |
impl |
Character scalar, to choose between two implementation of the
subgraph calculation. ‘ |
eids |
The edge ids of the edges that will be kept in the result graph. |
delete.vertices |
Logical scalar, whether to remove vertices that do
not have any adjacent edges in |
induced_subgraph()
calculates the induced subgraph of a set of vertices
in a graph. This means that exactly the specified vertices and all the edges
between them will be kept in the result graph.
subgraph_from_edges()
calculates the subgraph of a graph. For this function
one can specify the vertices and edges to keep. This function will be
renamed to subgraph()
in the next major version of igraph.
The subgraph()
function currently does the same as induced_subgraph()
(assuming ‘auto
’ as the impl
argument), but this behaviour
is deprecated. In the next major version, subgraph()
will overtake the
functionality of subgraph_from_edges()
.
A new graph object.
Gabor Csardi [email protected]
Other structural.properties:
bfs()
,
component_distribution()
,
connect()
,
constraint()
,
coreness()
,
degree()
,
dfs()
,
distance_table()
,
edge_density()
,
feedback_arc_set()
,
girth()
,
is_acyclic()
,
is_dag()
,
is_matching()
,
k_shortest_paths()
,
knn()
,
reciprocity()
,
subcomponent()
,
topo_sort()
,
transitivity()
,
unfold_tree()
,
which_multiple()
,
which_mutual()
g <- make_ring(10) g2 <- induced_subgraph(g, 1:7) g3 <- subgraph_from_edges(g, 1:5)
g <- make_ring(10) g2 <- induced_subgraph(g, 1:7) g3 <- subgraph_from_edges(g, 1:5)
Subgraph centrality of a vertex measures the number of subgraphs a vertex participates in, weighting them according to their size.
subgraph_centrality(graph, diag = FALSE)
subgraph_centrality(graph, diag = FALSE)
graph |
The input graph. It will be treated as undirected. |
diag |
Boolean scalar, whether to include the diagonal of the adjacency
matrix in the analysis. Giving |
The subgraph centrality of a vertex is defined as the number of closed walks originating at the vertex, where longer walks are downweighted by the factorial of their length.
Currently the calculation is performed by explicitly calculating all eigenvalues and eigenvectors of the adjacency matrix of the graph. This effectively means that the measure can only be calculated for small graphs.
A numeric vector, the subgraph centrality scores of the vertices.
Gabor Csardi [email protected] based on the Matlab code by Ernesto Estrada
Ernesto Estrada, Juan A. Rodriguez-Velazquez: Subgraph centrality in Complex Networks. Physical Review E 71, 056103 (2005).
eigen_centrality()
, page_rank()
Centrality measures
alpha_centrality()
,
authority_score()
,
betweenness()
,
closeness()
,
diversity()
,
eigen_centrality()
,
harmonic_centrality()
,
hits_scores()
,
page_rank()
,
power_centrality()
,
spectrum()
,
strength()
g <- sample_pa(100, m = 4, dir = FALSE) sc <- subgraph_centrality(g) cor(degree(g), sc)
g <- sample_pa(100, m = 4, dir = FALSE) sc <- subgraph_centrality(g) cor(degree(g), sc)
Decide if a graph is subgraph isomorphic to another one
subgraph_isomorphic(pattern, target, method = c("auto", "lad", "vf2"), ...) is_subgraph_isomorphic_to( pattern, target, method = c("auto", "lad", "vf2"), ... )
subgraph_isomorphic(pattern, target, method = c("auto", "lad", "vf2"), ...) is_subgraph_isomorphic_to( pattern, target, method = c("auto", "lad", "vf2"), ... )
pattern |
The smaller graph, it might be directed or undirected. Undirected graphs are treated as directed graphs with mutual edges. |
target |
The bigger graph, it might be directed or undirected. Undirected graphs are treated as directed graphs with mutual edges. |
method |
The method to use. Possible values: ‘auto’, ‘lad’, ‘vf2’. See their details below. |
... |
Additional arguments, passed to the various methods. |
Logical scalar, TRUE
if the pattern
is
isomorphic to a (possibly induced) subgraph of target
.
This method currently selects ‘lad’, always, as it seems to be superior on most graphs.
This is the LAD algorithm by Solnon, see the reference below. It has the following extra arguments:
If not NULL
, then it specifies matching
restrictions. It must be a list of target
vertex sets, given
as numeric vertex ids or symbolic vertex names. The length of the
list must be vcount(pattern)
and for each vertex in
pattern
it gives the allowed matching vertices in
target
. Defaults to NULL
.
Logical scalar, whether to search for an induced
subgraph. It is FALSE
by default.
The processor time limit for the computation, in
seconds. It defaults to Inf
, which means no limit.
This method uses the VF2 algorithm by Cordella, Foggia et al., see references below. It supports vertex and edge colors and have the following extra arguments:
Optional integer vectors giving the
colors of the vertices for colored graph isomorphism. If they
are not given, but the graph has a “color” vertex attribute,
then it will be used. If you want to ignore these attributes, then
supply NULL
for both of these arguments. See also examples
below.
Optional integer vectors giving the
colors of the edges for edge-colored (sub)graph isomorphism. If they
are not given, but the graph has a “color” edge attribute,
then it will be used. If you want to ignore these attributes, then
supply NULL
for both of these arguments.
LP Cordella, P Foggia, C Sansone, and M Vento: An improved algorithm for matching large graphs, Proc. of the 3rd IAPR TC-15 Workshop on Graphbased Representations in Pattern Recognition, 149–159, 2001.
C. Solnon: AllDifferent-based Filtering for Subgraph Isomorphism, Artificial Intelligence 174(12-13):850–864, 2010.
Other graph isomorphism:
canonical_permutation()
,
count_isomorphisms()
,
count_subgraph_isomorphisms()
,
graph_from_isomorphism_class()
,
isomorphic()
,
isomorphism_class()
,
isomorphisms()
,
subgraph_isomorphisms()
# A LAD example pattern <- make_graph( ~ 1:2:3:4:5, 1 - 2:5, 2 - 1:5:3, 3 - 2:4, 4 - 3:5, 5 - 4:2:1 ) target <- make_graph( ~ 1:2:3:4:5:6:7:8:9, 1 - 2:5:7, 2 - 1:5:3, 3 - 2:4, 4 - 3:5:6:8:9, 5 - 1:2:4:6:7, 6 - 7:5:4:9, 7 - 1:5:6, 8 - 4:9, 9 - 6:4:8 ) domains <- list( `1` = c(1, 3, 9), `2` = c(5, 6, 7, 8), `3` = c(2, 4, 6, 7, 8, 9), `4` = c(1, 3, 9), `5` = c(2, 4, 8, 9) ) subgraph_isomorphisms(pattern, target) subgraph_isomorphisms(pattern, target, induced = TRUE) subgraph_isomorphisms(pattern, target, domains = domains) # Directed LAD example pattern <- make_graph(~ 1:2:3, 1 -+ 2:3) dring <- make_ring(10, directed = TRUE) subgraph_isomorphic(pattern, dring)
# A LAD example pattern <- make_graph( ~ 1:2:3:4:5, 1 - 2:5, 2 - 1:5:3, 3 - 2:4, 4 - 3:5, 5 - 4:2:1 ) target <- make_graph( ~ 1:2:3:4:5:6:7:8:9, 1 - 2:5:7, 2 - 1:5:3, 3 - 2:4, 4 - 3:5:6:8:9, 5 - 1:2:4:6:7, 6 - 7:5:4:9, 7 - 1:5:6, 8 - 4:9, 9 - 6:4:8 ) domains <- list( `1` = c(1, 3, 9), `2` = c(5, 6, 7, 8), `3` = c(2, 4, 6, 7, 8, 9), `4` = c(1, 3, 9), `5` = c(2, 4, 8, 9) ) subgraph_isomorphisms(pattern, target) subgraph_isomorphisms(pattern, target, induced = TRUE) subgraph_isomorphisms(pattern, target, domains = domains) # Directed LAD example pattern <- make_graph(~ 1:2:3, 1 -+ 2:3) dring <- make_ring(10, directed = TRUE) subgraph_isomorphic(pattern, dring)
All isomorphic mappings between a graph and subgraphs of another graph
subgraph_isomorphisms(pattern, target, method = c("lad", "vf2"), ...)
subgraph_isomorphisms(pattern, target, method = c("lad", "vf2"), ...)
pattern |
The smaller graph, it might be directed or undirected. Undirected graphs are treated as directed graphs with mutual edges. |
target |
The bigger graph, it might be directed or undirected. Undirected graphs are treated as directed graphs with mutual edges. |
method |
The method to use. Possible values: ‘auto’, ‘lad’, ‘vf2’. See their details below. |
... |
Additional arguments, passed to the various methods. |
A list of vertex sequences, corresponding to all mappings from the first graph to the second.
This is the LAD algorithm by Solnon, see the reference below. It has the following extra arguments:
If not NULL
, then it specifies matching
restrictions. It must be a list of target
vertex sets, given
as numeric vertex ids or symbolic vertex names. The length of the
list must be vcount(pattern)
and for each vertex in
pattern
it gives the allowed matching vertices in
target
. Defaults to NULL
.
Logical scalar, whether to search for an induced
subgraph. It is FALSE
by default.
The processor time limit for the computation, in
seconds. It defaults to Inf
, which means no limit.
This method uses the VF2 algorithm by Cordella, Foggia et al., see references below. It supports vertex and edge colors and have the following extra arguments:
Optional integer vectors giving the
colors of the vertices for colored graph isomorphism. If they
are not given, but the graph has a “color” vertex attribute,
then it will be used. If you want to ignore these attributes, then
supply NULL
for both of these arguments. See also examples
below.
Optional integer vectors giving the
colors of the edges for edge-colored (sub)graph isomorphism. If they
are not given, but the graph has a “color” edge attribute,
then it will be used. If you want to ignore these attributes, then
supply NULL
for both of these arguments.
Other graph isomorphism:
canonical_permutation()
,
count_isomorphisms()
,
count_subgraph_isomorphisms()
,
graph_from_isomorphism_class()
,
isomorphic()
,
isomorphism_class()
,
isomorphisms()
,
subgraph_isomorphic()
For undirected graphs, head and tail is not defined. In this case
tail_of()
returns vertices incident to the supplied edges, and
head_of()
returns the other end(s) of the edge(s).
tail_of(graph, es)
tail_of(graph, es)
graph |
The input graph. |
es |
The edges to query. |
A vertex sequence with the tail(s) of the edge(s).
Other structural queries:
[.igraph()
,
[[.igraph()
,
adjacent_vertices()
,
are_adjacent()
,
ends()
,
get_edge_ids()
,
gorder()
,
gsize()
,
head_of()
,
incident()
,
incident_edges()
,
is_directed()
,
neighbors()
Run simulations for an SIR (susceptible-infected-recovered) model, on a graph
time_bins(x, middle = TRUE) ## S3 method for class 'sir' time_bins(x, middle = TRUE) ## S3 method for class 'sir' median(x, na.rm = FALSE, ...) ## S3 method for class 'sir' quantile(x, comp = c("NI", "NS", "NR"), prob, ...) sir(graph, beta, gamma, no.sim = 100)
time_bins(x, middle = TRUE) ## S3 method for class 'sir' time_bins(x, middle = TRUE) ## S3 method for class 'sir' median(x, na.rm = FALSE, ...) ## S3 method for class 'sir' quantile(x, comp = c("NI", "NS", "NR"), prob, ...) sir(graph, beta, gamma, no.sim = 100)
x |
A |
middle |
Logical scalar, whether to return the middle of the time bins, or the boundaries. |
na.rm |
Logical scalar, whether to ignore |
... |
Additional arguments, ignored currently. |
comp |
Character scalar. The component to calculate the quantile of.
|
prob |
Numeric vector of probabilities, in [0,1], they specify the quantiles to calculate. |
graph |
The graph to run the model on. If directed, then edge directions are ignored and a warning is given. |
beta |
Non-negative scalar. The rate of infection of an individual that is susceptible and has a single infected neighbor. The infection rate of a susceptible individual with n infected neighbors is n times beta. Formally this is the rate parameter of an exponential distribution. |
gamma |
Positive scalar. The rate of recovery of an infected individual. Formally, this is the rate parameter of an exponential distribution. |
no.sim |
Integer scalar, the number simulation runs to perform. |
The SIR model is a simple model from epidemiology. The individuals of the population might be in three states: susceptible, infected and recovered. Recovered people are assumed to be immune to the disease. Susceptibles become infected with a rate that depends on their number of infected neighbors. Infected people become recovered with a constant rate.
The function sir()
simulates the model. This function runs multiple
simulations, all starting with a single uniformly randomly chosen infected
individual. A simulation is stopped when no infected individuals are left.
Function time_bins()
bins the simulation steps, using the
Freedman-Diaconis heuristics to determine the bin width.
Function median
and quantile
calculate the median and
quantiles of the results, respectively, in bins calculated with
time_bins()
.
For sir()
the results are returned in an object of class
‘sir
’, which is a list, with one element for each simulation.
Each simulation is itself a list with the following elements. They are all
numeric vectors, with equal length:
The times of the events.
The number of susceptibles in the population, over time.
The number of infected individuals in the population, over time.
The number of recovered individuals in the population, over time.
Function time_bins()
returns a numeric vector, the middle or the
boundaries of the time bins, depending on the middle
argument.
median
returns a list of three named numeric vectors, NS
,
NI
and NR
. The names within the vectors are created from the
time bins.
quantile
returns the same vector as median
(but only one, the
one requested) if only one quantile is requested. If multiple quantiles are
requested, then a list of these vectors is returned, one for each quantile.
Gabor Csardi [email protected]. Eric Kolaczyk (http://math.bu.edu/people/kolaczyk/) wrote the initial version in R.
Bailey, Norman T. J. (1975). The mathematical theory of infectious diseases and its applications (2nd ed.). London: Griffin.
plot.sir()
to conveniently plot the results
Processes on graphs
plot.sir()
g <- sample_gnm(100, 100) sm <- sir(g, beta = 5, gamma = 1) plot(sm)
g <- sample_gnm(100, 100) sm <- sir(g, beta = 5, gamma = 1) plot(sm)
tkplot()
and its companion functions serve as an interactive graph
drawing facility. Not all parameters of the plot can be changed
interactively right now though, e.g. the colors of vertices, edges, and also
others have to be pre-defined.
tkplot(graph, canvas.width = 450, canvas.height = 450, ...) tk_close(tkp.id, window.close = TRUE) tk_off() tk_fit(tkp.id, width = NULL, height = NULL) tk_center(tkp.id) tk_reshape(tkp.id, newlayout, ..., params) tk_postscript(tkp.id) tk_coords(tkp.id, norm = FALSE) tk_set_coords(tkp.id, coords) tk_rotate(tkp.id, degree = NULL, rad = NULL) tk_canvas(tkp.id)
tkplot(graph, canvas.width = 450, canvas.height = 450, ...) tk_close(tkp.id, window.close = TRUE) tk_off() tk_fit(tkp.id, width = NULL, height = NULL) tk_center(tkp.id) tk_reshape(tkp.id, newlayout, ..., params) tk_postscript(tkp.id) tk_coords(tkp.id, norm = FALSE) tk_set_coords(tkp.id, coords) tk_rotate(tkp.id, degree = NULL, rad = NULL) tk_canvas(tkp.id)
graph |
The |
canvas.width , canvas.height
|
The size of the tkplot drawing area. |
... |
Additional plotting parameters. See igraph.plotting for the complete list. |
tkp.id |
The id of the tkplot window to close/reshape/etc. |
window.close |
Leave this on the default value. |
width |
The width of the rectangle for generating new coordinates. |
height |
The height of the rectangle for generating new coordinates. |
newlayout |
The new layout, see the |
params |
Extra parameters in a list, to pass to the layout function. |
norm |
Logical, should we norm the coordinates. |
coords |
Two-column numeric matrix, the new coordinates of the vertices, in absolute coordinates. |
degree |
The degree to rotate the plot. |
rad |
The degree to rotate the plot, in radian. |
tkplot()
is an interactive graph drawing facility. It is not very well
developed at this stage, but it should be still useful.
It's handling should be quite straightforward most of the time, here are some remarks and hints.
There are different popup menus, activated by the right mouse button, for vertices and edges. Both operate on the current selection if the vertex/edge under the cursor is part of the selection and operate on the vertex/edge under the cursor if it is not.
One selection can be active at a time, either a vertex or an edge selection.
A vertex/edge can be added to a selection by holding the control
key
while clicking on it with the left mouse button. Doing this again deselect
the vertex/edge.
Selections can be made also from the "Select" menu. The "Select some
vertices" dialog allows to give an expression for the vertices to be
selected: this can be a list of numeric R expessions separated by commas,
like 1,2:10,12,14,15
for example. Similarly in the "Select some
edges" dialog two such lists can be given and all edges connecting a vertex
in the first list to one in the second list will be selected.
In the color dialog a color name like 'orange' or RGB notation can also be used.
The tkplot()
command creates a new Tk window with the graphical
representation of graph
. The command returns an integer number, the
tkplot id. The other commands utilize this id to be able to query or
manipulate the plot.
tk_close()
closes the Tk plot with id tkp.id
.
tk_off()
closes all Tk plots.
tk_fit()
fits the plot to the given rectangle
(width
and height
), if some of these are NULL
the
actual physical width od height of the plot window is used.
tk_reshape()
applies a new layout to the plot, its optional
parameters will be collected to a list analogous to layout.par
.
tk_postscript()
creates a dialog window for saving the plot
in postscript format.
tk_canvas()
returns the Tk canvas object that belongs to a graph
plot. The canvas can be directly manipulated then, e.g. labels can be added,
it could be saved to a file programmatically, etc. See an example below.
tk_coords()
returns the coordinates of the vertices in a matrix.
Each row corresponds to one vertex.
tk_set_coords()
sets the coordinates of the vertices. A two-column
matrix specifies the new positions, with each row corresponding to a single
vertex.
tk_center()
shifts the figure to the center of its plot window.
tk_rotate()
rotates the figure, its parameter can be given either
in degrees or in radians.
tkplot.center tkplot.rotate
tkplot()
returns an integer, the id of the plot, this can be
used to manipulate it from the command line.
tk_canvas()
returns tkwin
object, the Tk canvas.
tk_coords()
returns a matrix with the coordinates.
tk_close()
, tk_off()
, tk_fit()
,
tk_reshape()
, tk_postscript()
, tk_center()
and tk_rotate()
return NULL
invisibly.
g <- make_ring(10) tkplot(g) ## Saving a tkplot() to a file programmatically g <- make_star(10, center=10) E(g)$width <- sample(1:10, ecount(g), replace=TRUE) lay <- layout_nicely(g) id <- tkplot(g, layout=lay) canvas <- tk_canvas(id) tcltk::tkpostscript(canvas, file="/tmp/output.eps") tk_close(id) ## Setting the coordinates and adding a title label g <- make_ring(10) id <- tkplot(make_ring(10), canvas.width=450, canvas.height=500) canvas <- tk_canvas(id) padding <- 20 coords <- norm_coords(layout_in_circle(g), 0+padding, 450-padding, 50+padding, 500-padding) tk_set_coords(id, coords) width <- as.numeric(tkcget(canvas, "-width")) height <- as.numeric(tkcget(canvas, "-height")) tkcreate(canvas, "text", width/2, 25, text="My title", justify="center", font=tcltk::tkfont.create(family="helvetica", size=20,weight="bold"))
Gabor Csardi [email protected]
to_prufer()
converts a tree graph into its Prüfer sequence.
to_prufer(graph)
to_prufer(graph)
graph |
The graph to convert to a Prüfer sequence |
The Prüfer sequence of a tree graph with n labeled vertices is a sequence of n-2 numbers, constructed as follows. If the graph has more than two vertices, find a vertex with degree one, remove it from the tree and add the label of the vertex that it was connected to to the sequence. Repeat until there are only two vertices in the remaining graph.
The Prüfer sequence of the graph, represented as a numeric vector of vertex IDs in the sequence.
make_from_prufer()
to construct a graph from its
Prüfer sequence
Other trees:
is_forest()
,
is_tree()
,
make_from_prufer()
,
sample_spanning_tree()
g <- make_tree(13, 3) to_prufer(g)
g <- make_tree(13, 3) to_prufer(g)
A topological sorting of a directed acyclic graph is a linear ordering of its nodes where each node comes before all nodes to which it has edges.
topo_sort(graph, mode = c("out", "all", "in"))
topo_sort(graph, mode = c("out", "all", "in"))
graph |
The input graph, should be directed |
mode |
Specifies how to use the direction of the edges. For
“ |
Every DAG has at least one topological sort, and may have many. This function returns a possible topological sort among them. If the graph is not acyclic (it has at least one cycle), a partial topological sort is returned and a warning is issued.
A vertex sequence (by default, but see the return.vs.es
option of igraph_options()
) containing vertices in
topologically sorted order.
Tamas Nepusz [email protected] and Gabor Csardi [email protected] for the R interface
Other structural.properties:
bfs()
,
component_distribution()
,
connect()
,
constraint()
,
coreness()
,
degree()
,
dfs()
,
distance_table()
,
edge_density()
,
feedback_arc_set()
,
girth()
,
is_acyclic()
,
is_dag()
,
is_matching()
,
k_shortest_paths()
,
knn()
,
reciprocity()
,
subcomponent()
,
subgraph()
,
transitivity()
,
unfold_tree()
,
which_multiple()
,
which_mutual()
g <- sample_pa(100) topo_sort(g)
g <- sample_pa(100) topo_sort(g)
Transitivity measures the probability that the adjacent vertices of a vertex are connected. This is sometimes also called the clustering coefficient.
transitivity( graph, type = c("undirected", "global", "globalundirected", "localundirected", "local", "average", "localaverage", "localaverageundirected", "barrat", "weighted"), vids = NULL, weights = NULL, isolates = c("NaN", "zero") )
transitivity( graph, type = c("undirected", "global", "globalundirected", "localundirected", "local", "average", "localaverage", "localaverageundirected", "barrat", "weighted"), vids = NULL, weights = NULL, isolates = c("NaN", "zero") )
graph |
The graph to analyze. |
type |
The type of the transitivity to calculate. Possible values:
|
vids |
The vertex ids for the local transitivity will be calculated.
This will be ignored for global transitivity types. The default value is
|
weights |
Optional weights for weighted transitivity. It is ignored for
other transitivity measures. If it is |
isolates |
Character scalar, for local versions of transitivity, it
defines how to treat vertices with degree zero and one.
If it is ‘ |
Note that there are essentially two classes of transitivity measures, one is a vertex-level, the other a graph level property.
There are several generalizations of transitivity to weighted graphs, here we use the definition by A. Barrat, this is a local vertex-level quantity, its formula is
is the strength of vertex
, see
strength()
, are elements of the
adjacency matrix,
is the vertex degree,
are the weights.
This formula gives back the normal not-weighted local transitivity if all the edge weights are the same.
The barrat
type of transitivity does not work for graphs with
multiple and/or loop edges. If you want to calculate it for a directed
graph, call as_undirected()
with the collapse
mode first.
For ‘global
’ a single number, or NaN
if there
are no connected triples in the graph.
For ‘local
’ a vector of transitivity scores, one for each
vertex in ‘vids
’.
Gabor Csardi [email protected]
Wasserman, S., and Faust, K. (1994). Social Network Analysis: Methods and Applications. Cambridge: Cambridge University Press.
Alain Barrat, Marc Barthelemy, Romualdo Pastor-Satorras, Alessandro Vespignani: The architecture of complex weighted networks, Proc. Natl. Acad. Sci. USA 101, 3747 (2004)
Other structural.properties:
bfs()
,
component_distribution()
,
connect()
,
constraint()
,
coreness()
,
degree()
,
dfs()
,
distance_table()
,
edge_density()
,
feedback_arc_set()
,
girth()
,
is_acyclic()
,
is_dag()
,
is_matching()
,
k_shortest_paths()
,
knn()
,
reciprocity()
,
subcomponent()
,
subgraph()
,
topo_sort()
,
unfold_tree()
,
which_multiple()
,
which_mutual()
g <- make_ring(10) transitivity(g) g2 <- sample_gnp(1000, 10 / 1000) transitivity(g2) # this is about 10/1000 # Weighted version, the figure from the Barrat paper gw <- graph_from_literal(A - B:C:D:E, B - C:D, C - D) E(gw)$weight <- 1 E(gw)[V(gw)[name == "A"] %--% V(gw)[name == "E"]]$weight <- 5 transitivity(gw, vids = "A", type = "local") transitivity(gw, vids = "A", type = "weighted") # Weighted reduces to "local" if weights are the same gw2 <- sample_gnp(1000, 10 / 1000) E(gw2)$weight <- 1 t1 <- transitivity(gw2, type = "local") t2 <- transitivity(gw2, type = "weighted") all(is.na(t1) == is.na(t2)) all(na.omit(t1 == t2))
g <- make_ring(10) transitivity(g) g2 <- sample_gnp(1000, 10 / 1000) transitivity(g2) # this is about 10/1000 # Weighted version, the figure from the Barrat paper gw <- graph_from_literal(A - B:C:D:E, B - C:D, C - D) E(gw)$weight <- 1 E(gw)[V(gw)[name == "A"] %--% V(gw)[name == "E"]]$weight <- 5 transitivity(gw, vids = "A", type = "local") transitivity(gw, vids = "A", type = "weighted") # Weighted reduces to "local" if weights are the same gw2 <- sample_gnp(1000, 10 / 1000) E(gw2)$weight <- 1 t1 <- transitivity(gw2, type = "local") t2 <- transitivity(gw2, type = "weighted") all(is.na(t1) == is.na(t2)) all(na.omit(t1 == t2))
This function counts the different induced subgraphs of three vertices in a graph.
triad_census(graph)
triad_census(graph)
graph |
The input graph, it should be directed. An undirected graph results a warning, and undefined results. |
Triad census was defined by David and Leinhardt (see References below). Every triple of vertices (A, B, C) are classified into the 16 possible states:
A,B,C, the empty graph.
A->B, C, the graph with a single directed edge.
A<->B, C, the graph with a mutual connection between two vertices.
A<-B->C, the out-star.
A->B<-C, the in-star.
A->B->C, directed line.
A<->B<-C.
A<->B->C.
A->B<-C, A->C.
A<-B<-C, A->C.
A<->B<->C.
A<-B->C, A<->C.
A->B<-C, A<->C.
A->B->C, A<->C.
A->B<->C, A<->C.
A<->B<->C, A<->C, the complete graph.
This functions uses the RANDESU motif finder algorithm to find and count the
subgraphs, see motifs()
.
A numeric vector, the subgraph counts, in the order given in the above description.
Gabor Csardi [email protected]
See also 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.
dyad_census()
for classifying binary relationships,
motifs()
for the underlying implementation.
g <- sample_gnm(15, 45, directed = TRUE) triad_census(g)
g <- sample_gnm(15, 45, directed = TRUE) triad_census(g)
Count how many triangles a vertex is part of, in a graph, or just list the triangles of a graph.
triangles(graph) count_triangles(graph, vids = V(graph))
triangles(graph) count_triangles(graph, vids = V(graph))
graph |
The input graph. It might be directed, but edge directions are ignored. |
vids |
The vertices to query, all of them by default. This might be a vector of numeric ids, or a character vector of symbolic vertex names for named graphs. |
triangles()
lists all triangles of a graph. For efficiency, all
triangles are returned in a single vector. The first three vertices belong
to the first triangle, etc.
count_triangles()
counts how many triangles a vertex is part of.
For triangles()
a numeric vector of vertex ids, the first three
vertices belong to the first triangle found, etc.
For count_triangles()
a numeric vector, the number of triangles for all
vertices queried.
igraph_list_triangles()
, igraph_adjacent_triangles()
.
Gabor Csardi [email protected]
## A small graph kite <- make_graph("Krackhardt_Kite") plot(kite) matrix(triangles(kite), nrow = 3) ## Adjacenct triangles atri <- count_triangles(kite) plot(kite, vertex.label = atri) ## Always true sum(count_triangles(kite)) == length(triangles(kite)) ## Should match, local transitivity is the ## number of adjacent triangles divided by the number ## of adjacency triples transitivity(kite, type = "local") count_triangles(kite) / (degree(kite) * (degree(kite) - 1) / 2)
## A small graph kite <- make_graph("Krackhardt_Kite") plot(kite) matrix(triangles(kite), nrow = 3) ## Adjacenct triangles atri <- count_triangles(kite) plot(kite, vertex.label = atri) ## Always true sum(count_triangles(kite)) == length(triangles(kite)) ## Should match, local transitivity is the ## number of adjacent triangles divided by the number ## of adjacency triples transitivity(kite, type = "local") count_triangles(kite) / (degree(kite) * (degree(kite) - 1) / 2)
Perform a breadth-first search on a graph and convert it into a tree or forest by replicating vertices that were found more than once.
unfold_tree(graph, mode = c("all", "out", "in", "total"), roots)
unfold_tree(graph, mode = c("all", "out", "in", "total"), roots)
graph |
The input graph, it can be either directed or undirected. |
mode |
Character string, defined the types of the paths used for the breadth-first search. “out” follows the outgoing, “in” the incoming edges, “all” and “total” both of them. This argument is ignored for undirected graphs. |
roots |
A vector giving the vertices from which the breadth-first search is performed. Typically it contains one vertex per component. |
A forest is a graph, whose components are trees.
The roots
vector can be calculated by simply doing a topological sort
in all components of the graph, see the examples below.
A list with two components:
tree |
The result, an |
vertex_index |
A numeric vector, it gives a mapping from the vertices of the new graph to the vertices of the old graph. |
Gabor Csardi [email protected]
Other structural.properties:
bfs()
,
component_distribution()
,
connect()
,
constraint()
,
coreness()
,
degree()
,
dfs()
,
distance_table()
,
edge_density()
,
feedback_arc_set()
,
girth()
,
is_acyclic()
,
is_dag()
,
is_matching()
,
k_shortest_paths()
,
knn()
,
reciprocity()
,
subcomponent()
,
subgraph()
,
topo_sort()
,
transitivity()
,
which_multiple()
,
which_mutual()
g <- make_tree(10) %du% make_tree(10) V(g)$id <- seq_len(vcount(g)) - 1 roots <- sapply(decompose(g), function(x) { V(x)$id[topo_sort(x)[1] + 1] }) tree <- unfold_tree(g, roots = roots)
g <- make_tree(10) %du% make_tree(10) V(g)$id <- seq_len(vcount(g)) - 1 roots <- sapply(decompose(g), function(x) { V(x)$id[topo_sort(x)[1] + 1] }) tree <- unfold_tree(g, roots = roots)
This is an S3 generic function. See methods("union")
for the actual implementations for various S3 classes. Initially
it is implemented for igraph graphs and igraph vertex and edge
sequences. See
union.igraph()
, and
union.igraph.vs()
.
union(...)
union(...)
... |
Arguments, their number and interpretation depends on
the function that implements |
Depends on the function that implements this method.
Other functions for manipulating graph structure:
+.igraph()
,
add_edges()
,
add_vertices()
,
complementer()
,
compose()
,
connect()
,
contract()
,
delete_edges()
,
delete_vertices()
,
difference()
,
difference.igraph()
,
disjoint_union()
,
edge()
,
igraph-minus
,
intersection()
,
intersection.igraph()
,
path()
,
permute()
,
rep.igraph()
,
reverse_edges()
,
simplify()
,
union.igraph()
,
vertex()
The union of two or more graphs are created. The graphs may have identical or overlapping vertex sets.
## S3 method for class 'igraph' union(..., byname = "auto")
## S3 method for class 'igraph' union(..., byname = "auto")
... |
Graph objects or lists of graph objects. |
byname |
A logical scalar, or the character scalar |
union()
creates the union of two or more graphs. Edges which are
included in at least one graph will be part of the new graph. This function
can be also used via the %u%
operator.
If the byname
argument is TRUE
(or auto
and all graphs
are named), then the operation is performed on symbolic vertex names instead
of the internal numeric vertex ids.
union()
keeps the attributes of all graphs. All graph, vertex and
edge attributes are copied to the result. If an attribute is present in
multiple graphs and would result a name clash, then this attribute is
renamed by adding suffixes: _1, _2, etc.
The name
vertex attribute is treated specially if the operation is
performed based on symbolic vertex names. In this case name
must be
present in all graphs, and it is not renamed in the result graph.
An error is generated if some input graphs are directed and others are undirected.
A new graph object.
Gabor Csardi [email protected]
Other functions for manipulating graph structure:
+.igraph()
,
add_edges()
,
add_vertices()
,
complementer()
,
compose()
,
connect()
,
contract()
,
delete_edges()
,
delete_vertices()
,
difference()
,
difference.igraph()
,
disjoint_union()
,
edge()
,
igraph-minus
,
intersection()
,
intersection.igraph()
,
path()
,
permute()
,
rep.igraph()
,
reverse_edges()
,
simplify()
,
union()
,
vertex()
## Union of two social networks with overlapping sets of actors net1 <- graph_from_literal( D - A:B:F:G, A - C - F - A, B - E - G - B, A - B, F - G, H - F:G, H - I - J ) net2 <- graph_from_literal(D - A:F:Y, B - A - X - F - H - Z, F - Y) print_all(net1 %u% net2)
## Union of two social networks with overlapping sets of actors net1 <- graph_from_literal( D - A:B:F:G, A - C - F - A, B - E - G - B, A - B, F - G, H - F:G, H - I - J ) net2 <- graph_from_literal(D - A:F:Y, B - A - X - F - H - Z, F - Y) print_all(net1 %u% net2)
Union of edge sequences
## S3 method for class 'igraph.es' union(...)
## S3 method for class 'igraph.es' union(...)
... |
The edge sequences to take the union of. |
They must belong to the same graph. Note that this function has
‘set’ semantics and the multiplicity of edges is lost in the
result. (This is to match the behavior of the based unique
function.)
An edge sequence that contains all edges in the given sequences, exactly once.
Other vertex and edge sequence operations:
c.igraph.es()
,
c.igraph.vs()
,
difference.igraph.es()
,
difference.igraph.vs()
,
igraph-es-indexing
,
igraph-es-indexing2
,
igraph-vs-indexing
,
igraph-vs-indexing2
,
intersection.igraph.es()
,
intersection.igraph.vs()
,
rev.igraph.es()
,
rev.igraph.vs()
,
union.igraph.vs()
,
unique.igraph.es()
,
unique.igraph.vs()
g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) union(E(g)[1:6], E(g)[5:9], E(g)["A|J"])
g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) union(E(g)[1:6], E(g)[5:9], E(g)["A|J"])
Union of vertex sequences
## S3 method for class 'igraph.vs' union(...)
## S3 method for class 'igraph.vs' union(...)
... |
The vertex sequences to take the union of. |
They must belong to the same graph. Note that this function has
‘set’ semantics and the multiplicity of vertices is lost in the
result. (This is to match the behavior of the based unique
function.)
A vertex sequence that contains all vertices in the given sequences, exactly once.
Other vertex and edge sequence operations:
c.igraph.es()
,
c.igraph.vs()
,
difference.igraph.es()
,
difference.igraph.vs()
,
igraph-es-indexing
,
igraph-es-indexing2
,
igraph-vs-indexing
,
igraph-vs-indexing2
,
intersection.igraph.es()
,
intersection.igraph.vs()
,
rev.igraph.es()
,
rev.igraph.vs()
,
union.igraph.es()
,
unique.igraph.es()
,
unique.igraph.vs()
g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) union(V(g)[1:6], V(g)[5:10])
g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) union(V(g)[1:6], V(g)[5:10])
Remove duplicate edges from an edge sequence
## S3 method for class 'igraph.es' unique(x, incomparables = FALSE, ...)
## S3 method for class 'igraph.es' unique(x, incomparables = FALSE, ...)
x |
An edge sequence. |
incomparables |
a vector of values that cannot be compared.
Passed to base function |
... |
Passed to base function |
An edge sequence with the duplicate vertices removed.
Other vertex and edge sequence operations:
c.igraph.es()
,
c.igraph.vs()
,
difference.igraph.es()
,
difference.igraph.vs()
,
igraph-es-indexing
,
igraph-es-indexing2
,
igraph-vs-indexing
,
igraph-vs-indexing2
,
intersection.igraph.es()
,
intersection.igraph.vs()
,
rev.igraph.es()
,
rev.igraph.vs()
,
union.igraph.es()
,
union.igraph.vs()
,
unique.igraph.vs()
g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) E(g)[1, 1:5, 1:10, 5:10] E(g)[1, 1:5, 1:10, 5:10] %>% unique()
g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) E(g)[1, 1:5, 1:10, 5:10] E(g)[1, 1:5, 1:10, 5:10] %>% unique()
Remove duplicate vertices from a vertex sequence
## S3 method for class 'igraph.vs' unique(x, incomparables = FALSE, ...)
## S3 method for class 'igraph.vs' unique(x, incomparables = FALSE, ...)
x |
A vertex sequence. |
incomparables |
a vector of values that cannot be compared.
Passed to base function |
... |
Passed to base function |
A vertex sequence with the duplicate vertices removed.
Other vertex and edge sequence operations:
c.igraph.es()
,
c.igraph.vs()
,
difference.igraph.es()
,
difference.igraph.vs()
,
igraph-es-indexing
,
igraph-es-indexing2
,
igraph-vs-indexing
,
igraph-vs-indexing2
,
intersection.igraph.es()
,
intersection.igraph.vs()
,
rev.igraph.es()
,
rev.igraph.vs()
,
union.igraph.es()
,
union.igraph.vs()
,
unique.igraph.es()
g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) V(g)[1, 1:5, 1:10, 5:10] V(g)[1, 1:5, 1:10, 5:10] %>% unique()
g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) V(g)[1, 1:5, 1:10, 5:10] V(g)[1, 1:5, 1:10, 5:10] %>% unique()
igraph's internal data representation changes sometimes between versions. This means that it is not possible to use igraph objects that were created (and possibly saved to a file) with an older igraph version.
upgrade_graph(graph)
upgrade_graph(graph)
graph |
The input graph. |
graph_version()
queries the current data format,
or the data format of a possibly older igraph graph.
upgrade_graph()
can convert an older data format
to the current one.
The graph in the current format.
graph_version to check the current data format version or the version of a graph.
Other versions:
graph_version()
Create a vertex sequence (vs) containing all vertices of a graph.
V(graph)
V(graph)
graph |
The graph |
A vertex sequence is just what the name says it is: a sequence of vertices. Vertex sequences are usually used as igraph function arguments that refer to vertices of a graph.
A vertex sequence is tied to the graph it refers to: it really denoted the specific vertices of that graph, and cannot be used together with another graph.
At the implementation level, a vertex sequence is simply a vector containing numeric vertex ids, but it has a special class attribute which makes it possible to perform graph specific operations on it, like selecting a subset of the vertices based on graph structure, or vertex attributes.
A vertex sequence is most often created by the V()
function. The
result of this includes all vertices in increasing vertex id order. A
vertex sequence can be indexed by a numeric vector, just like a regular
R vector. See [.igraph.vs
and additional links to other
vertex sequence operations below.
A vertex sequence containing all vertices, in the order of their numeric vertex ids.
Vertex sequences mostly behave like regular vectors, but there are some
additional indexing operations that are specific for them;
e.g. selecting vertices based on graph structure, or based on vertex
attributes. See [.igraph.vs
for details.
Vertex sequences can be used to query or set attributes for the
vertices in the sequence. See $.igraph.vs()
for details.
Other vertex and edge sequences:
E()
,
as_ids()
,
igraph-es-attributes
,
igraph-es-indexing
,
igraph-es-indexing2
,
igraph-vs-attributes
,
igraph-vs-indexing
,
igraph-vs-indexing2
,
print.igraph.es()
,
print.igraph.vs()
# Vertex ids of an unnamed graph g <- make_ring(10) V(g) # Vertex ids of a named graph g2 <- make_ring(10) %>% set_vertex_attr("name", value = letters[1:10]) V(g2)
# Vertex ids of an unnamed graph g <- make_ring(10) V(g) # Vertex ids of a named graph g2 <- make_ring(10) %>% set_vertex_attr("name", value = letters[1:10]) V(g2)
This is a helper function that simplifies adding and deleting vertices to/from graphs.
vertex(...) vertices(...)
vertex(...) vertices(...)
... |
See details below. |
vertices()
is an alias for vertex()
.
When adding vertices via +
, all unnamed arguments are interpreted
as vertex names of the new vertices. Named arguments are interpreted as
vertex attributes for the new vertices.
When deleting vertices via -
, all arguments of vertex()
(or
vertices()
) are concatenated via c()
and passed to
delete_vertices()
.
A special object that can be used with together with igraph graphs and the plus and minus operators.
Other functions for manipulating graph structure:
+.igraph()
,
add_edges()
,
add_vertices()
,
complementer()
,
compose()
,
connect()
,
contract()
,
delete_edges()
,
delete_vertices()
,
difference()
,
difference.igraph()
,
disjoint_union()
,
edge()
,
igraph-minus
,
intersection()
,
intersection.igraph()
,
path()
,
permute()
,
rep.igraph()
,
reverse_edges()
,
simplify()
,
union()
,
union.igraph()
g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) + vertices("X", "Y") g plot(g)
g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) + vertices("X", "Y") g plot(g)
Query vertex attributes of a graph
vertex_attr(graph, name, index = V(graph))
vertex_attr(graph, name, index = V(graph))
graph |
The graph. |
name |
Name of the attribute to query. If missing, then all vertex attributes are returned in a list. |
index |
An optional vertex sequence to query the attribute only for these vertices. |
The value of the vertex attribute, or the list of
all vertex attributes, if name
is missing.
Vertex, edge and graph attributes
delete_edge_attr()
,
delete_graph_attr()
,
delete_vertex_attr()
,
edge_attr()
,
edge_attr<-()
,
edge_attr_names()
,
graph_attr()
,
graph_attr<-()
,
graph_attr_names()
,
igraph-attribute-combination
,
igraph-dollar
,
igraph-vs-attributes
,
set_edge_attr()
,
set_graph_attr()
,
set_vertex_attr()
,
vertex_attr<-()
,
vertex_attr_names()
g <- make_ring(10) %>% set_vertex_attr("color", value = "red") %>% set_vertex_attr("label", value = letters[1:10]) vertex_attr(g, "label") vertex_attr(g) plot(g)
g <- make_ring(10) %>% set_vertex_attr("color", value = "red") %>% set_vertex_attr("label", value = letters[1:10]) vertex_attr(g, "label") vertex_attr(g) plot(g)
List names of vertex attributes
vertex_attr_names(graph)
vertex_attr_names(graph)
graph |
The graph. |
Character vector, the names of the vertex attributes.
Vertex, edge and graph attributes
delete_edge_attr()
,
delete_graph_attr()
,
delete_vertex_attr()
,
edge_attr()
,
edge_attr<-()
,
edge_attr_names()
,
graph_attr()
,
graph_attr<-()
,
graph_attr_names()
,
igraph-attribute-combination
,
igraph-dollar
,
igraph-vs-attributes
,
set_edge_attr()
,
set_graph_attr()
,
set_vertex_attr()
,
vertex_attr()
,
vertex_attr<-()
g <- make_ring(10) %>% set_vertex_attr("name", value = LETTERS[1:10]) %>% set_vertex_attr("color", value = rep("green", 10)) vertex_attr_names(g) plot(g)
g <- make_ring(10) %>% set_vertex_attr("name", value = LETTERS[1:10]) %>% set_vertex_attr("color", value = rep("green", 10)) vertex_attr_names(g) plot(g)
Set one or more vertex attributes
vertex_attr(graph, name, index = V(graph)) <- value
vertex_attr(graph, name, index = V(graph)) <- value
graph |
The graph. |
name |
The name of the vertex attribute to set. If missing,
then |
index |
An optional vertex sequence to set the attributes of a subset of vertices. |
value |
The new value of the attribute(s) for all
(or |
The graph, with the vertex attribute(s) added or set.
Vertex, edge and graph attributes
delete_edge_attr()
,
delete_graph_attr()
,
delete_vertex_attr()
,
edge_attr()
,
edge_attr<-()
,
edge_attr_names()
,
graph_attr()
,
graph_attr<-()
,
graph_attr_names()
,
igraph-attribute-combination
,
igraph-dollar
,
igraph-vs-attributes
,
set_edge_attr()
,
set_graph_attr()
,
set_vertex_attr()
,
vertex_attr()
,
vertex_attr_names()
g <- make_ring(10) vertex_attr(g) <- list( name = LETTERS[1:10], color = rep("yellow", gorder(g)) ) vertex_attr(g, "label") <- V(g)$name g plot(g)
g <- make_ring(10) vertex_attr(g) <- list( name = LETTERS[1:10], color = rep("yellow", gorder(g)) ) vertex_attr(g, "label") <- V(g)$name g plot(g)
The vertex connectivity of a graph or two vertices, this is recently also called group cohesion.
vertex_connectivity(graph, source = NULL, target = NULL, checks = TRUE) vertex_disjoint_paths(graph, source = NULL, target = NULL) ## S3 method for class 'igraph' cohesion(x, checks = TRUE, ...)
vertex_connectivity(graph, source = NULL, target = NULL, checks = TRUE) vertex_disjoint_paths(graph, source = NULL, target = NULL) ## S3 method for class 'igraph' cohesion(x, checks = TRUE, ...)
graph , x
|
The input graph. |
source |
The id of the source vertex, for |
target |
The id of the target vertex, for |
checks |
Logical constant. Whether to check that the graph is connected and also the degree of the vertices. If the graph is not (strongly) connected then the connectivity is obviously zero. Otherwise if the minimum degree is one then the vertex connectivity is also one. It is a good idea to perform these checks, as they can be done quickly compared to the connectivity calculation itself. They were suggested by Peter McMahan, thanks Peter. |
... |
Ignored. |
The vertex connectivity of two vertices (source
and target
) in
a graph is the minimum number of vertices that must be deleted to
eliminate all (directed) paths from source
to target
.
vertex_connectivity()
calculates this quantity if both the
source
and target
arguments are given and they're not
NULL
.
The vertex connectivity of a pair is the same as the number of different (i.e. node-independent) paths from source to target, assuming no direct edges between them.
The vertex connectivity of a graph is the minimum vertex connectivity of all
(ordered) pairs of vertices in the graph. In other words this is the minimum
number of vertices needed to remove to make the graph not strongly
connected. (If the graph is not strongly connected then this is zero.)
vertex_connectivity()
calculates this quantity if neither the
source
nor target
arguments are given. (I.e. they are both
NULL
.)
A set of vertex disjoint directed paths from source
to vertex
is a set of directed paths between them whose vertices do not contain common
vertices (apart from source
and target
). The maximum number of
vertex disjoint paths between two vertices is the same as their vertex
connectivity in most cases (if the two vertices are not connected by an
edge).
The cohesion of a graph (as defined by White and Harary, see references), is
the vertex connectivity of the graph. This is calculated by
cohesion()
.
These three functions essentially calculate the same measure(s), more
precisely vertex_connectivity()
is the most general, the other two are
included only for the ease of using more descriptive function names.
A scalar real value.
Gabor Csardi [email protected]
White, Douglas R and Frank Harary 2001. The Cohesiveness of Blocks In Social Networks: Node Connectivity and Conditional Density. Sociological Methodology 31 (1) : 305-359.
Other flow:
dominator_tree()
,
edge_connectivity()
,
is_min_separator()
,
is_separator()
,
max_flow()
,
min_cut()
,
min_separators()
,
min_st_separators()
,
st_cuts()
,
st_min_cuts()
g <- sample_pa(100, m = 1) g <- delete_edges(g, E(g)[100 %--% 1]) g2 <- sample_pa(100, m = 5) g2 <- delete_edges(g2, E(g2)[100 %--% 1]) vertex_connectivity(g, 100, 1) vertex_connectivity(g2, 100, 1) vertex_disjoint_paths(g2, 100, 1) g <- sample_gnp(50, 5 / 50) g <- as_directed(g) g <- induced_subgraph(g, subcomponent(g, 1)) cohesion(g)
g <- sample_pa(100, m = 1) g <- delete_edges(g, E(g)[100 %--% 1]) g2 <- sample_pa(100, m = 5) g2 <- delete_edges(g2, E(g2)[100 %--% 1]) vertex_connectivity(g, 100, 1) vertex_connectivity(g2, 100, 1) vertex_disjoint_paths(g2, 100, 1) g <- sample_gnp(50, 5 / 50) g <- as_directed(g) g <- induced_subgraph(g, subcomponent(g, 1)) cohesion(g)
This function partitions the vertices of a graph based on a set of generator vertices. Each vertex is assigned to the generator vertex from (or to) which it is closest.
groups()
may be used on the output of this function.
voronoi_cells( graph, generators, ..., weights = NULL, mode = c("out", "in", "all", "total"), tiebreaker = c("random", "first", "last") )
voronoi_cells( graph, generators, ..., weights = NULL, mode = c("out", "in", "all", "total"), tiebreaker = c("random", "first", "last") )
graph |
The graph to partition into Voronoi cells. |
generators |
The generator vertices of the Voronoi cells. |
... |
These dots are for future extensions and must be empty. |
weights |
Possibly a numeric vector giving edge weights. If this is
|
mode |
Character string. In directed graphs, whether to compute
distances from generator vertices to other vertices ( |
tiebreaker |
Character string that specifies what to do when a vertex
is at the same distance from multiple generators. |
A named list with two components:
membership |
numeric vector giving the cluster id to which each vertex belongs. |
distances |
numeric vector giving the distance of each vertex from its generator |
Community detection
as_membership()
,
cluster_edge_betweenness()
,
cluster_fast_greedy()
,
cluster_fluid_communities()
,
cluster_infomap()
,
cluster_label_prop()
,
cluster_leading_eigen()
,
cluster_leiden()
,
cluster_louvain()
,
cluster_optimal()
,
cluster_spinglass()
,
cluster_walktrap()
,
compare()
,
groups()
,
make_clusters()
,
membership()
,
modularity.igraph()
,
plot_dendrogram()
,
split_join_distance()
g <- make_lattice(c(10,10)) clu <- voronoi_cells(g, c(25, 43, 67)) groups(clu) plot(g, vertex.color=clu$membership)
g <- make_lattice(c(10,10)) clu <- voronoi_cells(g, c(25, 43, 67)) groups(clu) plot(g, vertex.color=clu$membership)
These functions find all, the largest or all the maximal weighted cliques in an undirected graph. The weight of a clique is the sum of the weights of its vertices.
weighted_cliques( graph, vertex.weights = NULL, min.weight = 0, max.weight = 0, maximal = FALSE )
weighted_cliques( graph, vertex.weights = NULL, min.weight = 0, max.weight = 0, maximal = FALSE )
graph |
The input graph, directed graphs will be considered as undirected ones, multiple edges and loops are ignored. |
vertex.weights |
Vertex weight vector. If the graph has a |
min.weight |
Numeric constant, lower limit on the weight of the cliques to find.
|
max.weight |
Numeric constant, upper limit on the weight of the cliques to find.
|
maximal |
Specifies whether to look for all weighted cliques ( |
weighted_cliques()
finds all complete subgraphs in the input graph,
obeying the weight limitations given in the min
and max
arguments.
largest_weighted_cliques()
finds all largest weighted cliques in the
input graph. A clique is largest if there is no other clique whose total
weight is larger than the weight of this clique.
weighted_clique_num()
calculates the weight of the largest weighted clique(s).
weighted_cliques()
and largest_weighted_cliques()
return a
list containing numeric vectors of vertex IDs. Each list element is a weighted
clique, i.e. a vertex sequence of class igraph.vs()
.
weighted_clique_num()
returns an integer scalar.
Tamas Nepusz [email protected] and Gabor Csardi [email protected]
Other cliques:
cliques()
,
ivs()
g <- make_graph("zachary") V(g)$weight <- 1 V(g)[c(1, 2, 3, 4, 14)]$weight <- 3 weighted_cliques(g) weighted_cliques(g, maximal = TRUE) largest_weighted_cliques(g) weighted_clique_num(g)
g <- make_graph("zachary") V(g)$weight <- 1 V(g)[c(1, 2, 3, 4, 14)]$weight <- 3 weighted_cliques(g) weighted_cliques(g, maximal = TRUE) largest_weighted_cliques(g) weighted_clique_num(g)
A loop edge is an edge from a vertex to itself. An edge is a multiple edge if it has exactly the same head and tail vertices as another edge. A graph without multiple and loop edges is called a simple graph.
which_multiple(graph, eids = E(graph)) any_multiple(graph) count_multiple(graph, eids = E(graph)) which_loop(graph, eids = E(graph)) any_loop(graph)
which_multiple(graph, eids = E(graph)) any_multiple(graph) count_multiple(graph, eids = E(graph)) which_loop(graph, eids = E(graph)) any_loop(graph)
graph |
The input graph. |
eids |
The edges to which the query is restricted. By default this is all edges in the graph. |
any_loop()
decides whether the graph has any loop edges.
which_loop()
decides whether the edges of the graph are loop edges.
any_multiple()
decides whether the graph has any multiple edges.
which_multiple()
decides whether the edges of the graph are multiple
edges.
count_multiple()
counts the multiplicity of each edge of a graph.
Note that the semantics for which_multiple()
and count_multiple()
is
different. which_multiple()
gives TRUE
for all occurrences of a
multiple edge except for one. I.e. if there are three i-j
edges in the
graph then which_multiple()
returns TRUE
for only two of them while
count_multiple()
returns ‘3’ for all three.
See the examples for getting rid of multiple edges while keeping their original multiplicity as an edge attribute.
any_loop()
and any_multiple()
return a logical scalar.
which_loop()
and which_multiple()
return a logical vector.
count_multiple()
returns a numeric vector.
igraph_is_multiple()
, igraph_has_multiple()
, igraph_count_multiple()
, igraph_is_loop()
, igraph_has_loop()
.
Gabor Csardi [email protected]
simplify()
to eliminate loop and multiple edges.
Other structural.properties:
bfs()
,
component_distribution()
,
connect()
,
constraint()
,
coreness()
,
degree()
,
dfs()
,
distance_table()
,
edge_density()
,
feedback_arc_set()
,
girth()
,
is_acyclic()
,
is_dag()
,
is_matching()
,
k_shortest_paths()
,
knn()
,
reciprocity()
,
subcomponent()
,
subgraph()
,
topo_sort()
,
transitivity()
,
unfold_tree()
,
which_mutual()
# Loops g <- make_graph(c(1, 1, 2, 2, 3, 3, 4, 5)) any_loop(g) which_loop(g) # Multiple edges g <- sample_pa(10, m = 3, algorithm = "bag") any_multiple(g) which_multiple(g) count_multiple(g) which_multiple(simplify(g)) all(count_multiple(simplify(g)) == 1) # Direction of the edge is important which_multiple(make_graph(c(1, 2, 2, 1))) which_multiple(make_graph(c(1, 2, 2, 1), dir = FALSE)) # Remove multiple edges but keep multiplicity g <- sample_pa(10, m = 3, algorithm = "bag") E(g)$weight <- count_multiple(g) g <- simplify(g, edge.attr.comb = list(weight = "min")) any(which_multiple(g)) E(g)$weight
# Loops g <- make_graph(c(1, 1, 2, 2, 3, 3, 4, 5)) any_loop(g) which_loop(g) # Multiple edges g <- sample_pa(10, m = 3, algorithm = "bag") any_multiple(g) which_multiple(g) count_multiple(g) which_multiple(simplify(g)) all(count_multiple(simplify(g)) == 1) # Direction of the edge is important which_multiple(make_graph(c(1, 2, 2, 1))) which_multiple(make_graph(c(1, 2, 2, 1), dir = FALSE)) # Remove multiple edges but keep multiplicity g <- sample_pa(10, m = 3, algorithm = "bag") E(g)$weight <- count_multiple(g) g <- simplify(g, edge.attr.comb = list(weight = "min")) any(which_multiple(g)) E(g)$weight
This function checks the reciprocal pair of the supplied edges.
which_mutual(graph, eids = E(graph), loops = TRUE)
which_mutual(graph, eids = E(graph), loops = TRUE)
graph |
The input graph. |
eids |
Edge sequence, the edges that will be probed. By default is includes all edges in the order of their ids. |
loops |
Logical, whether to consider directed self-loops to be mutual. |
In a directed graph an (A,B) edge is mutual if the graph also includes a (B,A) directed edge.
Note that multi-graphs are not handled properly, i.e. if the graph contains two copies of (A,B) and one copy of (B,A), then these three edges are considered to be mutual.
Undirected graphs contain only mutual edges by definition.
A logical vector of the same length as the number of edges supplied.
Gabor Csardi [email protected]
reciprocity()
, dyad_census()
if you just
want some statistics about mutual edges.
Other structural.properties:
bfs()
,
component_distribution()
,
connect()
,
constraint()
,
coreness()
,
degree()
,
dfs()
,
distance_table()
,
edge_density()
,
feedback_arc_set()
,
girth()
,
is_acyclic()
,
is_dag()
,
is_matching()
,
k_shortest_paths()
,
knn()
,
reciprocity()
,
subcomponent()
,
subgraph()
,
topo_sort()
,
transitivity()
,
unfold_tree()
,
which_multiple()
g <- sample_gnm(10, 50, directed = TRUE) reciprocity(g) dyad_census(g) which_mutual(g) sum(which_mutual(g)) / 2 == dyad_census(g)$mut
g <- sample_gnm(10, 50, directed = TRUE) reciprocity(g) dyad_census(g) which_mutual(g) sum(which_mutual(g)) / 2 == dyad_census(g)$mut
Constructor modifier to add edge attributes
with_edge_(...)
with_edge_(...)
... |
The attributes to add. They must be named. |
Constructor modifiers (and related functions)
make_()
,
sample_()
,
simplified()
,
with_graph_()
,
with_vertex_()
,
without_attr()
,
without_loops()
,
without_multiples()
make_( ring(10), with_edge_( color = "red", weight = rep(1:2, 5) ) ) %>% plot()
make_( ring(10), with_edge_( color = "red", weight = rep(1:2, 5) ) ) %>% plot()
Constructor modifier to add graph attributes
with_graph_(...)
with_graph_(...)
... |
The attributes to add. They must be named. |
Constructor modifiers (and related functions)
make_()
,
sample_()
,
simplified()
,
with_edge_()
,
with_vertex_()
,
without_attr()
,
without_loops()
,
without_multiples()
make_(ring(10), with_graph_(name = "10-ring"))
make_(ring(10), with_graph_(name = "10-ring"))
Run code with a temporary igraph options setting
with_igraph_opt(options, code)
with_igraph_opt(options, code)
options |
A named list of the options to change. |
code |
The code to run. |
The result of the code
.
Other igraph options:
igraph_options()
with_igraph_opt( list(sparsematrices = FALSE), make_ring(10)[] ) igraph_opt("sparsematrices")
with_igraph_opt( list(sparsematrices = FALSE), make_ring(10)[] ) igraph_opt("sparsematrices")
Constructor modifier to add vertex attributes
with_vertex_(...)
with_vertex_(...)
... |
The attributes to add. They must be named. |
Constructor modifiers (and related functions)
make_()
,
sample_()
,
simplified()
,
with_edge_()
,
with_graph_()
,
without_attr()
,
without_loops()
,
without_multiples()
make_( ring(10), with_vertex_( color = "#7fcdbb", frame.color = "#7fcdbb", name = LETTERS[1:10] ) ) %>% plot()
make_( ring(10), with_vertex_( color = "#7fcdbb", frame.color = "#7fcdbb", name = LETTERS[1:10] ) ) %>% plot()
Construtor modifier to remove all attributes from a graph
without_attr()
without_attr()
Constructor modifiers (and related functions)
make_()
,
sample_()
,
simplified()
,
with_edge_()
,
with_graph_()
,
with_vertex_()
,
without_loops()
,
without_multiples()
g1 <- make_ring(10) g1 g2 <- make_(ring(10), without_attr()) g2
g1 <- make_ring(10) g1 g2 <- make_(ring(10), without_attr()) g2
Constructor modifier to drop loop edges
without_loops()
without_loops()
Constructor modifiers (and related functions)
make_()
,
sample_()
,
simplified()
,
with_edge_()
,
with_graph_()
,
with_vertex_()
,
without_attr()
,
without_multiples()
# An artificial example make_(full_graph(5, loops = TRUE)) make_(full_graph(5, loops = TRUE), without_loops())
# An artificial example make_(full_graph(5, loops = TRUE)) make_(full_graph(5, loops = TRUE), without_loops())
Constructor modifier to drop multiple edges
without_multiples()
without_multiples()
Constructor modifiers (and related functions)
make_()
,
sample_()
,
simplified()
,
with_edge_()
,
with_graph_()
,
with_vertex_()
,
without_attr()
,
without_loops()
sample_(pa(10, m = 3, algorithm = "bag")) sample_(pa(10, m = 3, algorithm = "bag"), without_multiples())
sample_(pa(10, m = 3, algorithm = "bag")) sample_(pa(10, m = 3, algorithm = "bag"), without_multiples())
write_graph()
is a general function for exporting graphs to foreign
file formats. The recommended formats for data exchange are GraphML and GML.
write_graph( graph, file, format = c("edgelist", "pajek", "ncol", "lgl", "graphml", "dimacs", "gml", "dot", "leda"), ... )
write_graph( graph, file, format = c("edgelist", "pajek", "ncol", "lgl", "graphml", "dimacs", "gml", "dot", "leda"), ... )
graph |
The graph to export. |
file |
A connection or a string giving the file name to write the graph to. |
format |
Character string giving the file format. Right now
|
... |
Other, format specific arguments, see below. |
A 'NULL“, invisibly.
The edgelist
format is a simple text file,
with one edge per line, the two zero-based numerical vertex IDs separated
by a space character. Note that vertices are indexed starting with zero.
The file is sorted by the first and the second column. This format has no
additional arguments.
This format is a plain text edge list in which vertices are referred to by name rather than numerical ID. Edge weights may be optionally written. Additional parameters:
The name of a vertex attribute to take vertex names from or
NULL
to use zero-based numerical IDs.
The name of an edge attribute to take edge weights from or
NULL
to omit edge weights.
The pajek
format is provided for interoperability
with the Pajek software only. Since the format does not have a formal
specification, it is not recommended for general data exchange or archival.
igraph_write_graph_dimacs_flow()
, igraph_write_graph_dot()
, igraph_write_graph_edgelist()
, igraph_write_graph_gml()
, igraph_write_graph_graphml()
, igraph_write_graph_leda()
, igraph_write_graph_lgl()
, igraph_write_graph_ncol()
, igraph_write_graph_pajek()
.
Gabor Csardi [email protected]
Adai AT, Date SV, Wieland S, Marcotte EM. LGL: creating a map of protein function with an algorithm for visualizing very large biological networks. J Mol Biol. 2004 Jun 25;340(1):179-90.
Foreign format readers
graph_from_graphdb()
,
read_graph()
g <- make_ring(10) file <- tempfile(fileext = ".txt") write_graph(g, file, "edgelist") if (!interactive()) { unlink(file) }
g <- make_ring(10) file <- tempfile(fileext = ".txt") write_graph(g, file, "edgelist") if (!interactive()) { unlink(file) }