| Title: | Network Analysis and Visualization |
| Version: | 2.2.1 |
| 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. |
| License: | GPL-2 |GPL-3 [expanded from: GPL (≥ 2)] |
| URL: | https://r.igraph.org/,https://igraph.org/,https://igraph.discourse.group/ |
| BugReports: | https://github.com/igraph/rigraph/issues |
| Depends: | methods, R (≥ 3.5.0) |
| Imports: | cli, graphics, grDevices, lifecycle, magrittr, Matrix,pkgconfig (≥ 2.0.0), rlang (≥ 1.1.0), stats, utils, vctrs |
| Suggests: | ape (≥ 5.7-0.1), callr, decor, digest, igraphdata, knitr,rgl (≥ 1.3.14), rmarkdown, scales, stats4, tcltk, testthat,vdiffr, withr |
| Enhances: | graph |
| LinkingTo: | cpp11 (≥ 0.5.0) |
| VignetteBuilder: | knitr |
| Config/build/compilation-database: | false |
| Config/build/never-clean: | true |
| Config/comment/compilation-database: | Generate manually withpkgload:::generate_db() for faster pkgload::load_all() |
| Config/Needs/build: | r-lib/roxygen2, devtools, irlba, pkgconfig,igraph/igraph.r2cdocs, moodymudskipper/devtag |
| Config/Needs/coverage: | covr |
| Config/Needs/website: | here, readr, tibble, xmlparsedata, xml2 |
| Config/testthat/edition: | 3 |
| Config/testthat/parallel: | true |
| Config/testthat/start-first: | aaa-auto, vs-es, scan, vs-operators,weakref, watts.strogatz.game |
| Encoding: | UTF-8 |
| RoxygenNote: | 7.3.3.9000 |
| SystemRequirements: | libxml2 (optional), glpk (>= 4.57, optional) |
| NeedsCompilation: | yes |
| Packaged: | 2025-10-27 06:14:50 UTC; kirill |
| Author: | Gábor Csárdi |
| Maintainer: | Kirill Müller <kirill@cynkra.com> |
| Repository: | CRAN |
| Date/Publication: | 2025-10-27 09:50:02 UTC |
The igraph package
Description
igraph is a library and R package for network analysis.
Introduction
The main goals of the igraph library is to provide a set of data typesand functions for 1) pain-free implementation of graph algorithms, 2)fast handling of large graphs, with millions of vertices and edges, 3)allowing rapid prototyping via high level languages like R.
igraph graphs
igraph graphs have a class ‘igraph’. They are printed tothe screen in a special format, here is an example, a ring graphcreated usingmake_ring():
IGRAPH U--- 10 10 -- Ring graph + attr: name (g/c), mutual (g/x), circular (g/x)
‘IGRAPH’ denotes that this is an igraph graph. Thencome four bits that denote the kind of the graph: the first is‘U’ for undirected and ‘D’ for directedgraphs. The second is ‘N’ for named graph (i.e. if thegraph has the ‘name’ vertex attribute set). The third is‘W’ for weighted graphs (i.e. if the‘weight’ edge attribute is set). The fourth is‘B’ for bipartite graphs (i.e. if the‘type’ vertex attribute is set).
Then come two numbers, the number of vertices and the number of edgesin the graph, and after a double dash, the name of the graph (the‘name’ graph attribute) is printed if present. Thesecond line is optional and it contains all the attributes of thegraph. This graph has a ‘name’ graph attribute, of typecharacter, and two other graph attributes called‘mutual’ and ‘circular’, of a complextype. A complex type is simply anything that is not numeric orcharacter. See the documentation ofprint.igraph() fordetails.
If you want to see the edges of the graph as well, then use theprint_all() function:
> print_all(g) IGRAPH badcafe U--- 10 10 -- Ring graph + attr: name (g/c), mutual (g/x), circular (g/x) + edges: [1] 1-- 2 2-- 3 3-- 4 4-- 5 5-- 6 6-- 7 7-- 8 8-- 9 9--10 1--10
Creating graphs
There are many functions in igraph for creating graphs, bothdeterministic and stochastic; stochastic graph constructors are called‘games’.
To create small graphs with a given structure probably thegraph_from_literal() function is easiest. It uses R's formulainterface, its manual page contains many examples. Another option ismake_graph(), which takes numeric vertex ids directly.graph_from_atlas() creates graph from the Graph Atlas,make_graph() can create some special graphs.
To create graphs from field data,graph_from_edgelist(),graph_from_data_frame() andgraph_from_adjacency_matrix() areprobably the best choices.
The igraph package includes some classic random graphs like theErdős-Rényi GNP and GNM graphs (sample_gnp(),sample_gnm()) andsome recent popular models, like preferential attachment(sample_pa()) and the small-world model(sample_smallworld()).
Vertex and edge IDs
Vertices and edges have numerical vertex ids in igraph. Vertex ids arealways consecutive and they start with one. I.e. for a graph withn vertices the vertex ids are between1 andn. If some operation changes the number of vertices in thegraphs, e.g. a subgraph is created viainduced_subgraph(), thenthe vertices are renumbered to satisfy this criteria.
The same is true for the edges as well, edge ids are always betweenone andm, the total number of edges in the graph.
It is often desirable to follow vertices along a number of graphoperations, and vertex ids don't allow this because of therenumbering. The solution is to assign attributes to thevertices. These are kept by all operations, if possible. See moreabout attributes in the next section.
Attributes
In igraph it is possible to assign attributes to the vertices or edgesof a graph, or to the graph itself. igraph provides flexibleconstructs for selecting a set of vertices or edges based on theirattribute values, seevertex_attr(),V() andE() for details.
Some vertex/edge/graph attributes are treated specially. One of themis the ‘name’ attribute. This is used for printing the graphinstead of the numerical ids, if it exists. Vertex names can also beused to specify a vector or set of vertices, in all igraphfunctions. E.g.degree() has av argumentthat gives the vertices for which the degree is calculated. Thisargument can be given as a character vector of vertex names.
Edges can also have a ‘name’ attribute, and this is treatedspecially as well. Just like for vertices, edges can also be selectedbased on their names, e.g. in thedelete_edges() andother functions.
We note here, that vertex names can also be used to select edges.The form ‘from|to’, where ‘from’ and‘to’ are vertex names, select a single, possiblydirected, edge going from ‘from’ to‘to’. The two forms can also be mixed in the same edgeselector.
Other attributes define visualization parameters, seeigraph.plotting for details.
Attribute values can be set to any R object, but note that storing thegraph in some file formats might result the loss of complex attributevalues. All attribute values are preserved if you usebase::save() andbase::load() to store/retrieve yourgraphs.
Visualization
igraph provides three different ways for visualization. The first istheplot.igraph() function. (Actually you don't need towriteplot.igraph(),plot() is enough. This function usesregular R graphics and can be used with any R device.
The second function istkplot(), which uses a Tk GUI forbasic interactive graph manipulation. (Tk is quite resource hungry, sodon't try this for very large graphs.)
The third way requires thergl package and uses OpenGL. See therglplot() function for the details.
Make sure you readigraph.plotting before you startplotting your graphs.
File formats
igraph can handle various graph file formats, usually both for readingand writing. We suggest that you use the GraphML file format for yourgraphs, except if the graphs are too big. For big graphs a simplerformat is recommended. Seeread_graph() andwrite_graph() for details.
Further information
The igraph homepage is athttps://igraph.org.See especially the documentation section. Join the discussion forum athttps://igraph.discourse.group if you have questions or comments.
Author(s)
Maintainer: Kirill Müllerkirill@cynkra.com (ORCID)
Authors:
Gábor Csárdicsardi.gabor@gmail.com (ORCID)
Tamás Nepuszntamas@gmail.com (ORCID)
Vincent Traag (ORCID)
Szabolcs Horvátszhorvat@gmail.com (ORCID)
Fabio Zaninifabio.zanini@unsw.edu.au (ORCID)
Daniel Noom
David Schochdavid.schoch@cynkra.com (ORCID)
Maëlle Salmonmaelle@cynkra.com (ORCID)
Other contributors:
Michael Antonov [contributor]
Chan Zuckerberg Initiative (ROR) [funder]
See Also
Useful links:
Report bugs athttps://github.com/igraph/rigraph/issues
Magrittr's pipes
Description
igraph re-exports the%>% operator of magrittr, becausewe find it very useful. Please see the documentation in themagrittr package.
Arguments
lhs | Left hand side of the pipe. |
rhs | Right hand side of the pipe. |
Value
Result of applying the right hand side to theresult of the left hand side.
Examples
make_ring(10) %>% add_edges(c(1, 6)) %>% plot()Add vertices, edges or another graph to a graph
Description
Add vertices, edges or another graph to a graph
Usage
## S3 method for class 'igraph'e1 + e2Arguments
e1 | First argument, probably an igraph graph, but see detailsbelow. |
e2 | Second argument, see details below. |
Details
The plus operator can be used to add vertices or edges to graph.The actual operation that is performed depends on the type of theright hand side argument.
If is is another igraph graph object and they are bothnamed graphs, then the union of the two graphs are calculated,see
union().If it is another igraph graph object, but either of the twoare not named, then the disjoint union ofthe two graphs is calculated, see
disjoint_union().If it is a numeric scalar, then the specified number of verticesare added to the graph.
If it is a character scalar or vector, then it is interpreted asthe names of the vertices to add to the graph.
If it is an object created with the
vertex()orvertices()function, then new vertices are added to thegraph. This form is appropriate when one wants to add some vertexattributes as well. The operands of thevertices()functionspecifies the number of vertices to add and their attributes aswell.The unnamed arguments of
vertices()are concatenated andused as the ‘name’ vertex attribute (i.e. vertexnames), the named arguments will be added as additional vertexattributes. 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 tovertices(), and it isprovided for readability. The user should use it if a single vertexis added to the graph.If it is an object created with the
edge()oredges()function, then new edges will be added to thegraph. The new edges and possibly their attributes can be specified asthe arguments of theedges()function.The unnamed arguments of
edges()are concatenated and usedas vertex ids of the end points of the new edges. The namedarguments 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 toedges()and it is providedfor readability. The user should use it if a single edge is added tothe graph.If it is an object created with the
path()function, thennew edges that form a path are added. The edges and possibly theirattributes are specified as the arguments to thepath()function. The non-named arguments are concatenated and interpretedas the vertex ids along the path. The remaining arguments are addedas 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 iscommutative, 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 lefthand side of the operator:
graph <- make_empty_graph() + "foo" + "bar"
See Also
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()
Examples
# 10 vertices named a,b,c,... and no edgesg <- make_empty_graph() + vertices(letters[1:10])# Add edges to make it a ringg <- g + path(letters[1:10], letters[1], color = "grey")# Add some extra random edgesg <- g + edges(sample(V(g), 10, replace = TRUE), color = "red")g$layout <- layout_in_circleplot(g)Helpers within vertex/index sequences
Description
Functions to be used only with[.igraph.es and[.igraph.vs
Usage
.nei(...).innei(...).outnei(...).inc(...).from(...).to(...)Arguments
... | Not used, here for compatibility. |
Details
See[.igraph.vs and[.igraph.es.
Value
An error
Edges of a graph
Description
An edge sequence is a vector containing numeric edge ids, with a specialclass attribute that allows custom operations: selecting subsets ofedges based on attributes, or graph structure, creating theintersection, union of edges, etc.
Usage
E(graph, P = NULL, path = NULL, directed = TRUE)Arguments
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 thirdand 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 graphhas multiple edges, one of them will be chosen arbitrarily tobe included in the edge sequence. |
directed | Whether to consider edge directions in the |
Details
Edge sequences are usually used as igraph function arguments thatrefer to edges of a graph.
An edge sequence is tied to the graph it refers to: it really denotedthe specific edges of that graph, and cannot be used together withanother graph.
An edge sequence is most often created by theE() function. Theresult includes edges in increasing edge id order by default (if. noneof theP andpath arguments are used). An edgesequence can be indexed by a numeric vector, just like a regular Rvector. See links to other edge sequence operations below.
Value
An edge sequence of the graph.
Indexing edge sequences
Edge sequences mostly behave like regular vectors, but there are someadditional indexing operations that are specific for them;e.g. selecting edges based on graph structure, or based on edgeattributes. See[.igraph.es for details.
Querying or setting attributes
Edge sequences can be used to query or set attributes for theedges in the sequence. See$.igraph.es() for details.
See Also
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()
Examples
# Edges of an unnamed graphg <- make_ring(10)E(g)# Edges of a named graphg2 <- make_ring(10) %>% set_vertex_attr("name", value = letters[1:10])E(g2)Vertices of a graph
Description
Create a vertex sequence (vs) containing all vertices of a graph.
Usage
V(graph)Arguments
graph | The graph |
Details
A vertex sequence is just what the name says it is: a sequence ofvertices. Vertex sequences are usually used as igraph function argumentsthat refer to vertices of a graph.
A vertex sequence is tied to the graph it refers to: it really denotedthe specific vertices of that graph, and cannot be used together withanother graph.
At the implementation level, a vertex sequence is simply a vectorcontaining numeric vertex ids, but it has a special class attributewhich makes it possible to perform graph specific operations on it, likeselecting a subset of the vertices based on graph structure, or vertexattributes.
A vertex sequence is most often created by theV() function. Theresult of this includes all vertices in increasing vertex id order. Avertex sequence can be indexed by a numeric vector, just like a regularR vector. See[.igraph.vs and additional links to othervertex sequence operations below.
Value
A vertex sequence containing all vertices, in the orderof their numeric vertex ids.
Indexing vertex sequences
Vertex sequences mostly behave like regular vectors, but there are someadditional indexing operations that are specific for them;e.g. selecting vertices based on graph structure, or based on vertexattributes. See[.igraph.vs for details.
Querying or setting attributes
Vertex sequences can be used to query or set attributes for thevertices in the sequence. See$.igraph.vs() for details.
See Also
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()
Examples
# Vertex ids of an unnamed graphg <- make_ring(10)V(g)# Vertex ids of a named graphg2 <- make_ring(10) %>% set_vertex_attr("name", value = letters[1:10])V(g2)Query and manipulate a graph as it were an adjacency matrix
Description
Query and manipulate a graph as it were an adjacency matrix
Usage
## 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]Arguments
x | The graph. |
i | Index. Vertex ids or names or logical vectors. See detailsbelow. |
j | Index. Vertex ids or names or logical vectors. See detailsbelow. |
... | Currently ignored. |
from | A numeric or character vector giving vertex ids ornames. Together with the |
to | A numeric or character vector giving vertex ids ornames. Together with the |
sparse | Logical scalar, whether to return sparse matrices. |
edges | Logical scalar, whether to return edge ids. |
drop | Ignored. |
attr | If not |
Details
The single bracket indexes the (possibly weighted) adjacency matrix ofthe graph. Here is what you can do with it:
Check whether there is an edge between two vertices (
vandw) in the graph:graph[v, w]
A numeric scalar is returned, one if the edge exists, zerootherwise.
Extract the (sparse) adjacency matrix of the graph, or part ofit:
graph[]graph[1:3,5:6]graph[c(1,3,5),]
The first variants returns the full adjacency matrix, the othertwo return part of it.
The
fromandtoarguments can be used to checkthe existence of many edges. In this case, bothfromandtomust be present and they must have the same length. Theymust contain vertex ids or names. A numeric vector is returned, ofthe same length asfromandto, it contains onesfor 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 edgeweights. For non-esistent edges zero weights are returned. Otheredge attributes can be queried as well, by giving theattrargument.Querying edge ids instead of the existance of edges or edgeattributes. E.g.
graph[1, 2, edges=TRUE]
returns the id of the edge between vertices 1 and 2, or zero ifthere is no such edge.
Adding one or more edges to a graph. For this the element(s) ofthe imaginary adjacency matrix must be set to a non-zero numericvalue (or
TRUE):graph[1, 2] <- 1graph[1:3,1] <- 1graph[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
attrargumentcontains the name of the edge attribute to set, so it does nothave to be ‘weight’:graph[1, 2, attr="weight"]<- 5graph[from=1:3, to=c(2,3,5)] <- c(1,-1,4)
If an edge is already present in the network, then only itsweights or other attribute are updated. If the graph is alreadyweighted, then the
attr="weight"setting is implicit, andone does not need to give it explicitly.Deleting edges. The replacement syntax allow the deletion ofedges, by specifying
FALSEorNULLas thereplacement value:graph[v, w] <- FALSE
removes the edge from vertex
vto vertexw.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
vandware 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 ‘[[’.
Value
A scalar or matrix. See details below.
See Also
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
Description
Query and manipulate a graph as it were an adjacency list
Usage
## S3 method for class 'igraph'x[[i, j, from, to, ..., directed = TRUE, edges = FALSE, exact = TRUE]]Arguments
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 ornames. Together with the |
to | A numeric or character vector giving vertex ids ornames. Together with the |
... | Additional arguments are not used currently. |
directed | Logical scalar, whether to consider edge directionsin directed graphs. It is ignored for undirected graphs. |
edges | Logical scalar, whether to return edge ids. |
exact | Ignored. |
Details
The double bracket operator indexes the (imaginary) adjacency listof the graph. This can used for the following operations:
Querying the adjacent vertices for one or morevertices:
graph[[1:3,]]graph[[,1:3]]
The first form gives the successors, the second the predecessorsor the 1:3 vertices. (For undirected graphs they are equivalent.)
Querying the incident edges for one or more vertices,if the
edgesargument is set toTRUE: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
vto verticesw.
The alternative argument namesfrom andto can be usedinstead of the usuali andj, to make the code morereadable:
graph[[from = 1:3]]graph[[from = v, to = w, edges = TRUE]]
‘[[’ operators allows logical indices and negative indicesas well, with the usual R semantics.
Vertex names are also supported, so instead of a numeric vertex id avertex can also be given to ‘[’ and ‘[[’.
See Also
Other structural queries:[.igraph(),adjacent_vertices(),are_adjacent(),ends(),get_edge_ids(),gorder(),gsize(),head_of(),incident(),incident_edges(),is_directed(),neighbors(),tail_of()
Add edges to a graph
Description
add.edges() was renamed toadd_edges() to create a moreconsistent API.
Usage
add.edges(graph, edges, ..., attr = list())Arguments
graph | The input graph |
edges | The edges to add, a vertex sequence with even numberof vertices. |
... | Additional arguments, they must be named,and they will be added as edge attributes, for the newly addededges. See also details below. |
attr | A named list, its elements will be addedas edge attributes, for the newly added edges. See also detailsbelow. |
Various vertex shapes when plotting igraph graphs
Description
add.vertex.shape() was renamed toadd_shape() to create a moreconsistent API.
Usage
add.vertex.shape( shape, clip = shape_noclip, plot = shape_noplot, parameters = list())Arguments
shape | Character scalar, name of a vertex shape. If it is |
clip | An R function object, the clipping function. |
plot | An R function object, the plotting function. |
parameters | Named list, additional plot/vertex/edgeparameters. The element named define the new parameters, and theelements themselves define their default values.Vertex parameters should have a prefix‘ |
Add vertices to a graph
Description
add.vertices() was renamed toadd_vertices() to create a moreconsistent API.
Usage
add.vertices(graph, nv, ..., attr = list())Arguments
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 addedvertices. See also details below. |
attr | A named list, its elements will be addedas vertex attributes, for the newly added vertices. See also detailsbelow. |
Add edges to a graph
Description
The new edges are given as a vertex sequence, e.g. internalnumeric vertex ids, or vertex names. The first edge points fromedges[1] toedges[2], the second fromedges[3]toedges[4], etc.
Usage
add_edges(graph, edges, ..., attr = list())Arguments
graph | The input graph |
edges | The edges to add, a vertex sequence with even numberof vertices. |
... | Additional arguments, they must be named,and they will be added as edge attributes, for the newly addededges. See also details below. |
attr | A named list, its elements will be addedas edge attributes, for the newly added edges. See also detailsbelow. |
Details
If attributes are supplied, and they are not present in the graph,their values for the original edges of the graph are set toNA.
Value
The graph, with the edges (and attributes) added.
See Also
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()
Examples
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
Description
Add layout to graph
Usage
add_layout_(graph, ..., overwrite = TRUE)Arguments
graph | The input graph. |
... | Additional arguments are passed to |
overwrite | Whether to overwrite the layout of the graph,if it already has one. |
Value
The input graph, with the layout added.
See Also
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()
Examples
(make_star(11) + make_star(11)) %>% add_layout_(as_star(), component_wise()) %>% plot()Add vertices to a graph
Description
If attributes are supplied, and they are not present in the graph,their values for the original vertices of the graph are set toNA.
Usage
add_vertices(graph, nv, ..., attr = list())Arguments
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 addedvertices. See also details below. |
attr | A named list, its elements will be addedas vertex attributes, for the newly added vertices. See also detailsbelow. |
Value
The graph, with the vertices (and attributes) added.
See Also
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()
Examples
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 ))gV(g)[[]]plot(g)Find triangles in graphs
Description
adjacent.triangles() was renamed tocount_triangles() to create a moreconsistent API.
Usage
adjacent.triangles(graph, vids = V(graph))Arguments
graph | The input graph. It might be directed, but edge directions areignored. |
vids | The vertices to query, all of them by default. This might be avector of numeric ids, or a character vector of symbolic vertex names fornamed graphs. |
Adjacent vertices of multiple vertices in a graph
Description
This function is similar toneighbors(), but it queriesthe adjacent vertices for multiple vertices at once.
Usage
adjacent_vertices(graph, v, mode = c("out", "in", "all", "total"))Arguments
graph | Input graph. |
v | The vertices to query. |
mode | Whether to query outgoing (‘out’), incoming(‘in’) edges, or both types (‘all’). This isignored for undirected graphs. |
Value
A list of vertex sequences.
See Also
Other structural queries:[.igraph(),[[.igraph(),are_adjacent(),ends(),get_edge_ids(),gorder(),gsize(),head_of(),incident(),incident_edges(),is_directed(),neighbors(),tail_of()
Examples
g <- make_graph("Zachary")adjacent_vertices(g, c(1, 34))Generate an evolving random graph with preferential attachment and aging
Description
aging.ba.game() was renamed tosample_pa_age() to create a moreconsistent API.
Usage
aging.ba.game( 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)Arguments
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 firstvertex). This argument is used only if both the |
aging.bin | The number of bins to use for measuring the age ofvertices, see details below. |
out.dist | The discrete distribution to generate the number of edges toadd in each time step if |
out.seq | The number of edges to add in each time step, a vectorcontaining as many elements as the number of vertices. See details below. |
out.pref | Logical constant, whether to include edges not initiated bythe vertex as a basis of preferential attachment. See details below. |
directed | Logical constant, whether to generate a directed graph. Seedetails below. |
zero.deg.appeal | The degree-dependent part of the‘attractiveness’ of the vertices with no adjacent edges. See alsodetails 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 |
Generate an evolving random graph with preferential attachment and aging
Description
aging.barabasi.game() was renamed tosample_pa_age() to create a moreconsistent API.
Usage
aging.barabasi.game( 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)Arguments
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 firstvertex). This argument is used only if both the |
aging.bin | The number of bins to use for measuring the age ofvertices, see details below. |
out.dist | The discrete distribution to generate the number of edges toadd in each time step if |
out.seq | The number of edges to add in each time step, a vectorcontaining as many elements as the number of vertices. See details below. |
out.pref | Logical constant, whether to include edges not initiated bythe vertex as a basis of preferential attachment. See details below. |
directed | Logical constant, whether to generate a directed graph. Seedetails below. |
zero.deg.appeal | The degree-dependent part of the‘attractiveness’ of the vertices with no adjacent edges. See alsodetails 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 |
Generate an evolving random graph with preferential attachment and aging
Description
aging.prefatt.game() was renamed tosample_pa_age() to create a moreconsistent API.
Usage
aging.prefatt.game( 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)Arguments
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 firstvertex). This argument is used only if both the |
aging.bin | The number of bins to use for measuring the age ofvertices, see details below. |
out.dist | The discrete distribution to generate the number of edges toadd in each time step if |
out.seq | The number of edges to add in each time step, a vectorcontaining as many elements as the number of vertices. See details below. |
out.pref | Logical constant, whether to include edges not initiated bythe vertex as a basis of preferential attachment. See details below. |
directed | Logical constant, whether to generate a directed graph. Seedetails below. |
zero.deg.appeal | The degree-dependent part of the‘attractiveness’ of the vertices with no adjacent edges. See alsodetails 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 |
Align a vertex layoutThis function centers a vertex layout on the coordinate system origin androtates the layout to achieve a visually pleasing alignment with the coordinateaxes. Doing this is particularly useful with force-directed layouts such aslayout_with_fr().
Description
Align a vertex layoutThis function centers a vertex layout on the coordinate system origin androtates the layout to achieve a visually pleasing alignment with the coordinateaxes. Doing this is particularly useful with force-directed layouts such aslayout_with_fr().
Usage
align_layout(graph, layout)Arguments
graph | The graph whose layout is to be aligned. |
layout | A matrix whose rows are the coordinates of vertices. |
Value
modified layout matrix
Examples
g <- make_lattice(c(3, 3))l1 <- layout_with_fr(g)l2 <- align_layout(g,l1)plot(g, layout = l1)plot(g, layout = l2)List all simple paths from one source
Description
This function lists all simple paths from one source vertex to anothervertex or vertices. A path is simple if contains no repeated vertices.
Usage
all_simple_paths( graph, from, to = V(graph), mode = c("out", "in", "all", "total"), cutoff = -1)Arguments
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 orfrom 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. |
Details
Note that potentially there are exponentially many paths between twovertices of a graph, and you may run out of memory when using thisfunction, if your graph is lattice-like.
This function ignores multiple and loop edges.
Value
A list of integer vectors, each integer vector is a path fromthe source vertex to one of the target vertices. A path is given by itsvertex ids.
See Also
Other paths:diameter(),distance_table(),eccentricity(),graph_center(),radius()
Examples
g <- make_ring(10)all_simple_paths(g, 1, 5)all_simple_paths(g, 1, c(3, 5))Find Bonacich alpha centrality scores of network positions
Description
alpha.centrality() was renamed toalpha_centrality() to create a moreconsistent API.
Usage
alpha.centrality( graph, nodes = V(graph), alpha = 1, loops = FALSE, exo = 1, weights = NULL, tol = 1e-07, sparse = TRUE)Arguments
graph | The input graph, can be directed or undirected. In undirectedgraphs, edges are treated as if they were reciprocal directed ones. |
nodes | Vertex sequence, the vertices for which the alpha centralityvalues are returned. (For technical reasons they will be calculated for allvertices, anyway.) |
alpha | Parameter specifying the relative importance of endogenousversus exogenous factors in the determination of centrality. See detailsbelow. |
loops | Whether to eliminate loop edges from the graph before thecalculation. |
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 everyvertex. Note that too long vectors will be truncated and too short vectorswill be replicated to match the number of vertices. |
weights | A character scalar that gives the name of the edge attributeto 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 thecalculation. The ‘Matrix’ package is required for sparse matrixsupport |
Find Bonacich alpha centrality scores of network positions
Description
alpha_centrality() calculates the alpha centrality of some (or all)vertices in a graph.
Usage
alpha_centrality( graph, nodes = V(graph), alpha = 1, loops = FALSE, exo = 1, weights = NULL, tol = 1e-07, sparse = TRUE)Arguments
graph | The input graph, can be directed or undirected. In undirectedgraphs, edges are treated as if they were reciprocal directed ones. |
nodes | Vertex sequence, the vertices for which the alpha centralityvalues are returned. (For technical reasons they will be calculated for allvertices, anyway.) |
alpha | Parameter specifying the relative importance of endogenousversus exogenous factors in the determination of centrality. See detailsbelow. |
loops | Whether to eliminate loop edges from the graph before thecalculation. |
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 everyvertex. Note that too long vectors will be truncated and too short vectorswill be replicated to match the number of vertices. |
weights | A character scalar that gives the name of the edge attributeto 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 thecalculation. The ‘Matrix’ package is required for sparse matrixsupport |
Details
The alpha centrality measure can be considered as a generalization ofeigenvector centrality to directed graphs. It was proposed by Bonacich in2001 (see reference below).
The alpha centrality of the vertices in a graph is defined as the solutionof the following matrix equation:
x=\alpha A^T x+e,
whereA is the (not necessarily symmetric) adjacency matrix of thegraph,e is the vector of exogenous sources of status of thevertices and\alpha is the relative importance of theendogenous versus exogenous factors.
Value
A numeric vector contaning the centrality scores for the selectedvertices.
Warning
Singular adjacency matrices cause problems for thisalgorithm, the routine may fail is certain cases.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
Bonacich, P. and Lloyd, P. (2001). “Eigenvector-likemeasures of centrality for asymmetric relations”Social Networks,23, 191-201.
See Also
eigen_centrality() andpower_centrality()
Centrality measuresauthority_score(),betweenness(),closeness(),diversity(),eigen_centrality(),harmonic_centrality(),hits_scores(),page_rank(),power_centrality(),spectrum(),strength(),subgraph_centrality()
Examples
# The examples from Bonacich's paperg.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)Are two vertices adjacent?
Description
are.connected() was renamed toare_adjacent() to create a moreconsistent API.
Usage
are.connected(graph, v1, v2)Arguments
graph | The graph. |
v1 | The first vertex, tail in directed graphs. |
v2 | The second vertex, head in directed graphs. |
Are two vertices adjacent?
Description
The order of the vertices only matters in directed graphs,where the existence of a directed(v1, v2) edge is queried.
Usage
are_adjacent(graph, v1, v2)Arguments
graph | The graph. |
v1 | The first vertex, tail in directed graphs. |
v2 | The second vertex, head in directed graphs. |
Value
A logical scalar,TRUE if edge(v1, v2) exists in the graph.
Related documentation in the C library
See Also
Other structural queries:[.igraph(),[[.igraph(),adjacent_vertices(),ends(),get_edge_ids(),gorder(),gsize(),head_of(),incident(),incident_edges(),is_directed(),neighbors(),tail_of()
Examples
ug <- make_ring(10)ugare_adjacent(ug, 1, 2)are_adjacent(ug, 2, 1)dg <- make_ring(10, directed = TRUE)dgare_adjacent(ug, 1, 2)are_adjacent(ug, 2, 1)ARPACK eigenvector calculation
Description
Interface to the ARPACK library for calculating eigenvectors of sparsematrices
Usage
arpack_defaults()arpack( func, extra = NULL, sym = FALSE, options = arpack_defaults(), env = parent.frame(), complex = !sym)Arguments
func | The function to perform the matrix-vector multiplication. ARPACKrequires 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. Alwayssupply |
options | Options to ARPACK, a named list to overwrite some of thedefault option values. See details below. |
env | The environment in which |
complex | Whether to convert the eigenvectors returned by ARPACK into Rcomplex vectors. By default this is not done for symmetric problems (theseonly have real eigenvectors/values), but only non-symmetric ones. If youhave a non-symmetric problem, but you're sure that the results will be real,then supply |
Details
ARPACK is a library for solving large scale eigenvalue problems. Thepackage is designed to compute a few eigenvalues and correspondingeigenvectors of a generaln byn matrixA. It is mostappropriate for large sparse or structured matricesA where structuredmeans that a matrix-vector productw <- Av requires ordernrather than the usual ordern^2 floating point operations.
This function is an interface to ARPACK. igraph does not contain all ARPACKroutines, only the ones dealing with symmetric and non-symmetric eigenvalueproblems using double precision real numbers.
The eigenvalue calculation in ARPACK (in the simplest case) involves thecalculation of theAv product whereA is the matrix we work withandv is an arbitrary vector. The function supplied in thefunargument is expected to perform this product. If the product can be doneefficiently, e.g. if the matrix is sparse, thenarpack() is usuallyable to calculate the eigenvalues very quickly.
Theoptions argument specifies what kind of calculation to perform.It is a list with the following members, they correspond directly to ARPACKparameters. On input it has the following fields:
- bmat
Character constant, possible values:‘
I’, standard eigenvalue problem,Ax=\lambda x; and‘G’, generalized eigenvalue problem,Ax=\lambda B x.Currently only ‘I’ is supported.- n
Numeric scalar. The dimension of the eigenproblem.You only need to set this if you call
arpack()directly.(I.e. not needed foreigen_centrality(),page_rank(), etc.)- which
Specify which eigenvalues/vectors to compute,character constant with exactly two characters.Possible values for symmetric input matrices:
- "LA"
Compute
nevlargest (algebraic) eigenvalues.- "SA"
Compute
nevsmallest (algebraic) eigenvalues.- "LM"
Compute
nevlargest (in magnitude) eigenvalues.- "SM"
Compute
nevsmallest (in magnitude) eigenvalues.- "BE"
Compute
neveigenvalues, half from each end of the spectrum.Whennevis odd, compute one more from the high end than from the low end.
Possible values for non-symmetric input matrices:
- "LM"
Compute
neveigenvalues of largest magnitude.- "SM"
Compute
neveigenvalues of smallest magnitude.- "LR"
Compute
neveigenvalues of largest real part.- "SR"
Compute
neveigenvalues of smallest real part.- "LI"
Compute
neveigenvalues of largest imaginary part.- "SI"
Compute
neveigenvalues of smallest imaginary part.
This parameter is sometimes overwritten by the various functions,e.g.
page_rank()always sets ‘LM’.- nev
Numeric scalar. The number of eigenvalues to be computed.
- tol
Numeric scalar. Stopping criterion:the relative accuracy of the Ritz value is considered acceptableif its error is less than
toltimes its estimated value.If this is set to zero then machine precision is used.- ncv
Number of Lanczos vectors to be generated.
- ldv
Numberic scalar. It should be set to zero in the current implementation.
- ishift
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
T.Please always set this to one.- maxiter
Maximum number of Arnoldi update iterations allowed.
- nb
Blocksize to be used in the recurrence. Please always leave this on the default value, one.
- mode
The type of the eigenproblem to be solved. Possible values if the input matrix is symmetric:
- 1
Ax=\lambda x,Ais symmetric.- 2
Ax=\lambda Mx,Ais symmetric,Mis symmetric positive definite.- 3
Kx=\lambda Mx,Kis symmetric,Mis symmetric positive semi-definite.- 4
Kx=\lambda KGx,Kis symmetric positive semi-definite,KGis symmetric indefinite.- 5
Ax=\lambda Mx,Ais symmetric,Mis symmetric positive semi-definite. (Cayley transformed mode.)
Please note that only
mode==1was tested and other values might not work properly.Possible values if the input matrix is not symmetric:- 1
Ax=\lambda x.- 2
Ax=\lambda Mx,Mis symmetric positive definite.- 3
Ax=\lambda Mx,Mis symmetric semi-definite.- 4
Ax=\lambda Mx,Mis symmetric semi-definite.
Please note that only
mode==1was tested and other values might not work properly.- start
Not used currently. Later it be used to set a starting vector.
- sigma
Not used currently.
- sigmai
Not use currently.
:On output the following additional fields are added:
- info
Error flag of ARPACK. Possible values:
- 0
Normal exit.
- 1
Maximum number of iterations taken.
- 3
No shifts could be applied during a cycleof the implicitly restarted Arnoldi iteration.One possibility is to increase the size of
ncvrelative tonev.
ARPACK can return more error conditions than these,but they are converted to regular igraph errors.
- iter
Number of Arnoldi iterations taken.
- nconv
Number of “converged” Ritz values.This represents the number of Ritz values that satisfy the convergence critetion.
- numop
Total number of matrix-vector multiplications.
- numopb
Not used currently.
- numreo
Total number of steps of re-orthogonalization.
Please see the ARPACK documentation for additional details.
Value
A named list with the following members:
- values
Numeric vector, the desired eigenvalues.
- vectors
Numeric matrix, the desired eigenvectors as columns.If
complex=TRUE(the default for non-symmetric problems), then the matrix is complex.- options
A named list with the supplied
optionsand some information about the performed calculation,including an ARPACK exit code.See the details above.
Author(s)
Rich Lehoucq, Kristi Maschhoff, Danny Sorensen, Chao Yang forARPACK, Gabor Csardicsardi.gabor@gmail.com for the R interface.
References
D.C. Sorensen, Implicit Application of Polynomial Filters in ak-Step Arnoldi Method.SIAM J. Matr. Anal. Apps., 13 (1992), pp357-385.
R.B. Lehoucq, Analysis and Implementation of an Implicitly Restarted ArnoldiIteration.Rice University Technical Report TR95-13, Department ofComputational and Applied Mathematics.
B.N. Parlett & Y. Saad, Complex Shift and Invert Strategies for RealMatrices.Linear Algebra and its Applications, vol 88/89, pp 575-595,(1987).
See Also
eigen_centrality(),page_rank(),hub_score(),cluster_leading_eigen() are some of thefunctions in igraph that use ARPACK.
Examples
# Identity matrixf <- function(x, extra = NULL) xarpack(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 operationf <- 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 checkeigen(laplacian_matrix(make_star(10, mode = "undirected")))## First three eigenvalues of the adjacency matrix of a graph## We need the 'Matrix' package for thislibrary("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 and bridges of a graph
Description
articulation.points() was renamed toarticulation_points() to create a moreconsistent API.
Usage
articulation.points(graph)Arguments
graph | The input graph. It is treated as an undirected graph, even ifit is directed. |
Articulation points and bridges of a graph
Description
articulation_points() finds the articulation points (or cut vertices)
Usage
articulation_points(graph)bridges(graph)Arguments
graph | The input graph. It is treated as an undirected graph, even ifit is directed. |
Details
Articulation points or cut vertices are vertices whose removal increases thenumber of connected components in a graph. Similarly, bridges or cut-edgesare edges whose removal increases the number of connected components in agraph. If the original graph was connected, then the removal of a singlearticulation point or a single bridge makes it disconnected. If a graphcontains no articulation points, then its vertex connectivity is at leasttwo.
Value
Forarticulation_points(), a numeric vector giving the vertexIDs of the articulation points of the input graph. Forbridges(), anumeric vector giving the edge IDs of the bridges of the input graph.
Related documentation in the C library
articulation_points(),bridges().
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
biconnected_components(),components(),is_connected(),vertex_connectivity(),edge_connectivity()
Connected componentsbiconnected_components(),component_distribution(),decompose(),is_biconnected()
Examples
g <- disjoint_union(make_full_graph(5), make_full_graph(5))clu <- components(g)$membershipg <- add_edges(g, c(match(1, clu), match(2, clu)))articulation_points(g)g <- make_graph("krackhardt_kite")bridges(g)Convert between directed and undirected graphs
Description
as.directed() was renamed toas_directed() to create a moreconsistent API.
Usage
as.directed(graph, mode = c("mutual", "arbitrary", "random", "acyclic"))Arguments
graph | The graph to convert. |
mode | Character constant, defines the conversion algorithm. For |
Conversion to igraph
Description
These functions convert various objects to igraph graphs.
Usage
as.igraph(x, ...)Arguments
x | The object to convert. |
... | Additional arguments. None currently. |
Details
You can useas.igraph() to convert various objects to igraph graphs.Right now the following objects are supported:
codeigraphHRGThese objects are created by the
fit_hrg()andconsensus_tree()functions.
Value
All these functions return an igraph graph.
Author(s)
Gabor Csardicsardi.gabor@gmail.com.
Examples
g <- make_full_graph(5) + make_full_graph(5)hrg <- fit_hrg(g)as.igraph(hrg)Convert igraph objects to adjacency or edge list matrices
Description
Get adjacency or edgelist representation of the network stored as anigraph object.
Usage
## S3 method for class 'igraph'as.matrix(x, matrix.type = c("adjacency", "edgelist"), ...)Arguments
x | object of class |
matrix.type | character, type of matrix to return, currently "adjacency"or "edgelist" are supported |
... | other arguments to/from other methods |
Details
Ifmatrix.type is"edgelist", then a two-column numeric edge listmatrix is returned. The value ofattrname is ignored.
Ifmatrix.type is"adjacency", then a square adjacency matrix isreturned. For adjacency matrices, you can use theattr keyword argumentto use the values of an edge attribute in the matrix cells. See thedocumentation ofas_adjacency_matrix for more details.
Other arguments passed through... are passed to eitheras_adjacency_matrix() oras_edgelist()depending on the value ofmatrix.type.
Value
Depending on the value ofmatrix.type either a squareadjacency matrix or a two-column numeric matrix representing the edgelist.
Author(s)
Michal Bojanowski, originally from theintergraph package
See Also
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()
Examples
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")Convert between undirected and unundirected graphs
Description
as.undirected() was renamed toas_undirected() to create a moreconsistent API.
Usage
as.undirected( graph, mode = c("collapse", "each", "mutual"), edge.attr.comb = igraph_opt("edge.attr.comb"))Arguments
graph | The graph to convert. |
mode | Character constant, defines the conversion algorithm. For |
edge.attr.comb | Specifies what to do with edge attributes, if |
Convert a graph to an adjacency matrix
Description
We plan to remove
as_adj() in favor of the more explicitly namedas_adjacency_matrix() so please useas_adjacency_matrix() instead.
Usage
as_adj( graph, type = c("both", "upper", "lower"), attr = NULL, edges = deprecated(), names = TRUE, sparse = igraph_opt("sparsematrices"))Arguments
Adjacency lists
Description
Create adjacency lists from a graph, either for adjacent edges or forneighboring vertices
Usage
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"))Arguments
graph | The input graph. |
mode | Character scalar, it gives what kind of adjacent edges/verticesto include in the lists. ‘ |
loops | Character scalar, one of |
multiple | Logical scalar, set to |
Details
as_adj_list() returns a list of numeric vectors, which include the idsof neighbor vertices (according to themode argument) of allvertices.
as_adj_edge_list() returns a list of numeric vectors, which include theids of adjacent edges (according to themode argument) of allvertices.
Ifigraph_opt("return.vs.es") is true (default), the numericvectors of the adjacency lists are coerced toigraph.vs, this can bea very expensive operation on large graphs.
Value
A list ofigraph.vs or a list of numeric vectors depending onthe value ofigraph_opt("return.vs.es"), see details for performancecharacteristics.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
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()
Examples
g <- make_ring(10)as_adj_list(g)as_adj_edge_list(g)Convert a graph to an adjacency matrix
Description
Sometimes it is useful to work with a standard representation of agraph, like an adjacency matrix.
Usage
as_adjacency_matrix( graph, type = c("both", "upper", "lower"), attr = NULL, edges = deprecated(), names = TRUE, sparse = igraph_opt("sparsematrices"))Arguments
Details
as_adjacency_matrix() returns the adjacency matrix of a graph, aregular matrix ifsparse isFALSE, or a sparse matrix, asdefined in the ‘Matrix’ package, ifsparse ifTRUE.
Value
Avcount(graph) byvcount(graph) (usually) numericmatrix.
See Also
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()
Examples
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")Bipartite adjacency matrix of a bipartite graph
Description
This function can return a sparse or dense bipartite adjacency matrix of a bipartitenetwork. The bipartite adjacency matrix is ann timesm matrix,nandm are the number of vertices of the two kinds.
Usage
as_biadjacency_matrix( graph, types = NULL, attr = NULL, names = TRUE, sparse = FALSE)Arguments
graph | The input graph. The direction of the edges is ignored indirected graphs. |
types | An optional vertex type vector to use instead of the |
attr | Either |
names | Logical scalar, if |
sparse | Logical scalar, if it is |
Details
Bipartite graphs have atype vertex attribute in igraph, this isboolean andFALSE for the vertices of the first kind andTRUEfor 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 usethis naming to avoid confusion with the edge-vertex incidence matrix.
Value
A sparse or dense matrix.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
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()
Examples
g <- make_bipartite_graph(c(0, 1, 0, 1, 0, 0), c(1, 2, 2, 3, 3, 4))as_biadjacency_matrix(g)Creating igraph graphs from data frames or vice-versa
Description
This function creates an igraph graph from one or two data frames containingthe (symbolic) edge list and edge/vertex attributes.
Usage
as_data_frame(x, what = c("edges", "vertices", "both"))graph_from_data_frame(d, directed = TRUE, vertices = NULL)from_data_frame(...)Arguments
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 twocolumns. Additional columns are considered as edge attributes. Sinceversion 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 |
Details
graph_from_data_frame() creates igraph graphs from one or two data frames.It has two modes of operation, depending whether theverticesargument isNULL or not.
Ifvertices isNULL, then the first two columns ofdare 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.
Ifvertices is notNULL, then it must be a data frame givingvertex metadata. The first column ofvertices is assumed to containsymbolic vertex names, this will be added to the graphs as the‘name’ vertex attribute. Other columns will be added asadditional vertex attributes. Ifvertices is notNULL then thesymbolic edge list given ind is checked to contain only vertex nameslisted invertices.
Typically, the data frames are exported from some spreadsheet software likeExcel and are imported into R viaread.table(),read.delim() orread.csv().
All edges in the data frame are included in the graph, which may includemultiple parallel edges and loops.
as_data_frame() converts the igraph graph into one or more dataframes, depending on thewhat argument.
If thewhat argument isedges (the default), then the edges ofthe graph and also the edge attributes are returned. The edges will be inthe first two columns, namedfrom andto. (This also denotesedge direction for directed graphs.) For named graphs, the vertex nameswill 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 tohave an edge attribute namedfrom orto, because then thecolumn named in the data frame will not be unique. The edges are listed inthe order of their numeric ids.
If thewhat argument isvertices, then vertex attributes arereturned. Vertices are listed in the order of their numeric vertex ids.
If thewhat argument isboth, then both vertex and edge datais returned, in a list with named entriesvertices andedges.
Value
An igraph graph object forgraph_from_data_frame(), and either adata frame or a list of two data frames namededges andvertices foras.data.frame.
Note
Forgraph_from_data_frame()NA elements in the first twocolumns ‘d’ are replaced by the string “NA” before creatingthe graph. This means that allNAs will correspond to a singlevertex.
NA elements in the first column of ‘vertices’ are alsoreplaced by the string “NA”, but the rest of ‘vertices’ is nottouched. In other words, vertex names (=the first column) cannot beNA, but other vertex attributes can.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
graph_from_literal()for another way to create graphs,read.table() to read in tablesfrom 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()
Examples
## 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 operationas_data_frame(g, what = "vertices")as_data_frame(g, what = "edges")Convert between directed and undirected graphs
Description
as_directed() converts an undirected graph to directed,as_undirected() does the opposite, it converts a directed graph toundirected.
Usage
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"))Arguments
graph | The graph to convert. |
mode | Character constant, defines the conversion algorithm. For |
edge.attr.comb | Specifies what to do with edge attributes, if |
Details
Conversion algorithms foras_directed():
- "arbitrary"
The number of edges in the graph stays the same, anarbitrarily directed edge is created for each undirected edge, but thedirection of the edge is deterministic (i.e. it always points the sameway if you call the function multiple times).
- "mutual"
Two directed edges are created for each undirectededge, one in each direction.
- "random"
The number of edges in the graph stays the same, anda randomly directed edge is created for each undirected edge. Youwill get different results if you call the function multiple timeswith the same graph.
- "acyclic"
The number of edges in the graph stays the same, anda directed edge is created for each undirected edge such that theresulting graph is guaranteed to be acyclic. This is achieved by ensuringthat edges always point from a lower index vertex to a higher index.Note that the graph may include cycles of length 1 if the originalgraph contained loop edges.
Conversion algorithms foras_undirected():
- "each"
The number of edges remains constant, an undirected edgeis created for each directed one, this version might create graphs withmultiple edges.
- "collapse"
One undirected edge will be createdfor each pair of vertices which are connected with at least one directededge, no multiple edges will be created.
- "mutual"
Oneundirected edge will be created for each pair of mutual edges. Non-mutualedges are ignored. This mode might create multiple edges if there are morethan one mutual edge pairs between the same pair of vertices.
Value
A new graph object.
Related documentation in the C library
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
simplify() for removing multiple and/or loop edges froma 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()
Examples
g <- make_ring(10)as_directed(g, "mutual")g2 <- make_star(10)as_undirected(g)# Combining edge attributesg3 <- 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)Convert a graph to an edge list
Description
Sometimes it is useful to work with a standard representation of agraph, like an edge list.
Usage
as_edgelist(graph, names = TRUE)Arguments
graph | The graph to convert. |
names | Whether to return a character matrix containing vertexnames (i.e. the |
Details
as_edgelist() returns the list of edges in a graph.
Value
Aecount(graph) by 2 numeric matrix.
See Also
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()
Examples
g <- sample_gnp(10, 2 / 10)as_edgelist(g)V(g)$name <- LETTERS[seq_len(gorder(g))]as_edgelist(g)Convert igraph graphs to graphNEL objects from the graph package
Description
The graphNEL class is defined in thegraph package, it is anotherway to represent graphs. These functions are provided to convert betweenthe igraph and the graphNEL objects.
Usage
as_graphnel(graph)Arguments
graph | An igraph graph object. |
Details
as_graphnel() converts an igraph graph to a graphNEL graph. Itconverts all graph/vertex/edge attributes. If the igraph graph has avertex attribute ‘name’, then it will be used to assignvertex names in the graphNEL graph. Otherwise numeric igraph vertex idswill be used for this purpose.
Value
as_graphnel() returns a graphNEL graph object.
See Also
graph_from_graphnel() for the other direction,as_adjacency_matrix(),graph_from_adjacency_matrix(),as_adj_list() andgraph_from_adj_list() forother 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()
Examples
## Undirectedg <- make_ring(10)V(g)$name <- letters[1:10]GNEL <- as_graphnel(g)g2 <- graph_from_graphnel(GNEL)g2## Directedg3 <- make_star(10, mode = "in")V(g3)$name <- letters[1:10]GNEL2 <- as_graphnel(g3)g4 <- graph_from_graphnel(GNEL2)g4Convert a vertex or edge sequence to an ordinary vector
Description
Convert a vertex or edge sequence to an ordinary vector
Usage
as_ids(seq)## S3 method for class 'igraph.vs'as_ids(seq)## S3 method for class 'igraph.es'as_ids(seq)Arguments
seq | The vertex or edge sequence. |
Details
For graphs without names, a numeric vector is returned, containing theinternal numeric vertex or edge ids.
For graphs with names, and vertex sequences, the vertex names arereturned in a character vector.
For graphs with names and edge sequences, a character vector isreturned, with the ‘bar’ notation:a|b means an edge fromvertexa to vertexb.
Value
A character or numeric vector, see details below.
See Also
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()
Examples
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))As incidence matrix
Description
as_incidence_matrix() was renamed toas_biadjacency_matrix() to create a moreconsistent API.
Usage
as_incidence_matrix(...)Details
Some authors refer to the bipartite adjacency matrix as the"bipartite incidence matrix". igraph 1.6.0 and later does not usethis naming to avoid confusion with the edge-vertex incidence matrix.
Convert a graph to a long data frame
Description
A long data frame contains all metadata about both the verticesand edges of the graph. It contains one row for each edge, andall metadata about that edge and its incident vertices are includedin that row. The names of the columns that contain the metadataof the incident vertices are prefixed withfrom_ andto_.The first two columns are always namedfrom andto andthey contain the numeric ids of the incident vertices. The rows arelisted in the order of numeric vertex ids.
Usage
as_long_data_frame(graph)Arguments
graph | Input graph |
Value
A long data frame.
See Also
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()
Examples
g <- make_( ring(10), with_vertex_(name = letters[1:10], color = "red"), with_edge_(weight = 1:10, color = "green"))as_long_data_frame(g)Declare a numeric vector as a membership vector
Description
This is useful if you want to use functions defined onmembership vectors, but your membership vector does notcome from an igraph clustering method.
Usage
as_membership(x)Arguments
x | The input vector. |
Value
The input vector, with themembership class added.
See Also
Community detectioncluster_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()
Examples
## Compare to the correct clusteringg <- (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))as_phylo
Description
as_phylo methods were renamedas.phylofor more consistency with other R methods.
Usage
as_phylo(x, ...)Arguments
x | object to be coerced |
... | further arguments to be passed to or from other methods. |
Assortativity coefficient
Description
The assortativity coefficient is positive if similar vertices (based on someexternal property) tend to connect to each, and negative otherwise.
Usage
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)Arguments
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 whencalculating assortativity for a directed graph.Supply |
directed | Logical scalar, whether to consider edge directions fordirected 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 thevalues at the two ends of edges. |
types1,types2 | |
types | Vector giving the vertex types. They as assumed to be integernumbers, starting with one. Non-integer values are converted to integerswith |
Details
The assortativity coefficient measures the level of homophyly of the graph,based on some vertex labeling or values assigned to vertices. If thecoefficient is high, that means that connected vertices tend to have thesame labels or similar assigned values.
M.E.J. Newman defined two kinds of assortativity coefficients, the first oneis for categorical labels of vertices.assortativity_nominal()calculates this measure. It is defined as
r=\frac{\sum_i e_{ii}-\sum_i a_i b_i}{1-\sum_i a_i b_i}
wheree_{ij} is the fraction of edges connecting vertices oftypei andj,a_i=\sum_j e_{ij} andb_j=\sum_i e_{ij}.
The second assortativity variant is based on values assigned to thevertices.assortativity() calculates this measure. It is defined as
r=\frac1{\sigma_q^2}\sum_{jk} jk(e_{jk}-q_j q_k)
for undirected graphs (q_i=\sum_j e_{ij}) and as
r=\frac1{\sigma_o\sigma_i}\sum_{jk}jk(e_{jk}-q_j^o q_k^i)
for directed ones. Hereq_i^o=\sum_j e_{ij},q_i^i=\sum_j e_{ji}, moreover,\sigma_q,\sigma_o and\sigma_i are the standard deviations ofq,q^o andq^i, respectively.
The reason of the difference is that in directed networks the relationshipis not symmetric, so it is possible to assign different values to theoutgoing and the incoming end of the edges.
assortativity_degree() uses vertex degree as vertex valuesand callsassortativity().
Undirected graphs are effectively treated as directed ones with all-reciprocal edges.Thus, self-loops are taken into account twice in undirected graphs.
Value
A single real number.
Related documentation in the C library
assortativity(),assortativity_nominal(),assortativity_degree().
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
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
Examples
# random network, close to zeroassortativity_degree(sample_gnp(10000, 3 / 10000))# BA model, tends to be dissortativeassortativity_degree(sample_pa(10000, m = 4))Assortativity coefficient
Description
assortativity.degree() was renamed toassortativity_degree() to create a moreconsistent API.
Usage
assortativity.degree(graph, directed = TRUE)Arguments
graph | The input graph, it can be directed or undirected. |
directed | Logical scalar, whether to consider edge directions fordirected graphs.This argument is ignored for undirected graphs.Supply |
Assortativity coefficient
Description
assortativity.nominal() was renamed toassortativity_nominal() to create a moreconsistent API.
Usage
assortativity.nominal(graph, types, directed = TRUE, normalized = TRUE)Arguments
graph | The input graph, it can be directed or undirected. |
types | Vector giving the vertex types. They as assumed to be integernumbers, starting with one. Non-integer values are converted to integerswith |
directed | Logical scalar, whether to consider edge directions fordirected 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 thevalues at the two ends of edges. |
Trait-based random generation
Description
asymmetric.preference.game() was renamed tosample_asym_pref() to create a moreconsistent API.
Usage
asymmetric.preference.game( nodes, types, type.dist.matrix = matrix(1, types, types), pref.matrix = matrix(1, types, types), loops = FALSE)Arguments
nodes | The number of vertices in the graphs. |
types | The number of different vertex types. |
type.dist.matrix | The joint distribution of the in- and out-vertextypes. |
pref.matrix | A square matrix giving the preferences of the vertextypes. The matrix has ‘types’ rows and columns. When generatingan undirected graph, it must be symmetric. |
loops | Logical constant, whether self-loops are allowed in the graph. |
Kleinberg's hub and authority centrality scores.
Description
authority.score() was renamed toauthority_score() to create a moreconsistent API.
Usage
authority.score( graph, scale = TRUE, weights = NULL, options = arpack_defaults())Arguments
graph | The input graph. |
scale | Logical scalar, whether to scale the result to have a maximumscore of one. If no scaling is used then the result vector has unit lengthin the Euclidean norm. |
weights | Optional positive weight vector for calculating weightedscores. If the graph has a |
options | A named list, to override some ARPACK options. See |
Kleinberg's authority centrality scores.
Description
Kleinberg's authority centrality scores.
Kleinberg's hub centrality scores.
Usage
authority_score( graph, scale = TRUE, weights = NULL, options = arpack_defaults())hub_score(graph, scale = TRUE, weights = NULL, options = arpack_defaults())Arguments
graph | The input graph. |
scale | Logical scalar, whether to scale the result to have a maximumscore of one. If no scaling is used then the result vector has unit lengthin the Euclidean norm. |
weights | Optional positive weight vector for calculating weightedscores. If the graph has a |
options | A named list, to override some ARPACK options. See |
See Also
Centrality measuresalpha_centrality(),betweenness(),closeness(),diversity(),eigen_centrality(),harmonic_centrality(),hits_scores(),page_rank(),power_centrality(),spectrum(),strength(),subgraph_centrality()
Optimal edge curvature when plotting graphs
Description
autocurve.edges() was renamed tocurve_multiple() to create a moreconsistent API.
Usage
autocurve.edges(graph, start = 0.5)Arguments
graph | The input graph. |
start | The curvature at the two extreme edges. All edges will have acurvature between |
Generating set of the automorphism group of a graph
Description
Compute the generating set of the automorphism group of a graph.
Usage
automorphism_group( graph, colors = NULL, sh = c("fm", "f", "fs", "fl", "flm", "fsm"), details = FALSE)Arguments
graph | The input graph, it is treated as undirected. |
colors | The colors of the individual vertices of the graph; onlyvertices having the same color are allowed to match each other in anautomorphism. When omitted, igraph uses the |
sh | The splitting heuristics for the BLISS algorithm. Possible valuesare:‘ |
details | Specifies whether to provide additional details about theBLISS internals in the result. |
Details
An automorphism of a graph is a permutation of its vertices which brings thegraph into itself. The automorphisms of a graph form a group and there existsa subset of this group (i.e. a set of permutations) such that every otherpermutation can be expressed as a combination of these permutations. Thesepermutations are called the generating set of the automorphism group.
This function calculates a possible generating set of the automorphism ofa graph using the BLISS algorithm. See also the BLISS homepage athttp://www.tcs.hut.fi/Software/bliss/index.html. The calculatedgenerating set is not necessarily minimal, and it may depend on the splittingheuristics used by BLISS.
Value
Whendetails isFALSE, a list of vertex permutationsthat form a generating set of the automorphism group of the input graph.Whendetails isTRUE, a named list with two members:
- generators
Returns the generators themselves
- info
Additional information about the BLISS internals.See
count_automorphisms()for more details.
Related documentation in the C library
Author(s)
Tommi Junttila (https://users.ics.aalto.fi/tjunttil/) for BLISS,Gabor Csardicsardi.gabor@gmail.com for the igraph glue code andTamas Nepuszntamas@gmail.com for this manual page.
References
Tommi Junttila and Petteri Kaski: Engineering an EfficientCanonical Labeling Tool for Large and Sparse Graphs,Proceedings ofthe Ninth Workshop on Algorithm Engineering and Experiments and the FourthWorkshop on Analytic Algorithms and Combinatorics. 2007.
See Also
canonical_permutation(),permute(),count_automorphisms()
Other graph automorphism:count_automorphisms()
Examples
## A ring has n*2 automorphisms, and a possible generating set is one that## "turns" the ring by one vertex to the left or rightg <- make_ring(10)automorphism_group(g)Number of automorphisms
Description
automorphisms() was renamed tocount_automorphisms() to create a moreconsistent API.
Usage
automorphisms( graph, colors = NULL, sh = c("fm", "f", "fs", "fl", "flm", "fsm"))Arguments
graph | The input graph, it is treated as undirected. |
colors | The colors of the individual vertices of the graph; onlyvertices having the same color are allowed to match each other in anautomorphism. When omitted, igraph uses the |
sh | The splitting heuristics for the BLISS algorithm. Possible valuesare:‘ |
Shortest (directed or undirected) paths between vertices
Description
average.path.length() was renamed tomean_distance() to create a moreconsistent API.
Usage
average.path.length( graph, weights = NULL, directed = TRUE, unconnected = TRUE, details = FALSE)Arguments
graph | The graph to work on. |
weights | Possibly a numeric vector giving edge weights. If this is |
directed | Whether to consider directed paths in directed graphs,this argument is ignored for undirected graphs. |
unconnected | What to do if the graph is unconnected (notstrongly connected if directed paths are considered). If TRUE, onlythe lengths of the existing paths are considered and averaged; ifFALSE, the length of the missing paths are considered as having infinitelength, making the mean distance infinite as well. |
details | Whether to provide additional details in the result.Functions accepting this argument (like |
Generate random graphs using preferential attachment
Description
ba.game() was renamed tosample_pa() to create a moreconsistent API.
Usage
ba.game( 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)Arguments
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 Thisargument is only used if both |
out.dist | Numeric vector, the distribution of the number of edges toadd in each time step. This argument is only used if the |
out.seq | Numeric vector giving the number of edges to add in each timestep. Its first element is ignored as no edges are added in the first timestep. |
out.pref | Logical, if true the total degree is used for calculatingthe citation probability, otherwise the in-degree is used. |
zero.appeal | The ‘attractiveness’ of the vertices with noadjacent edges. See details below. |
directed | Whether to create a directed graph. |
algorithm | The algorithm to use for the graph generation. |
start.graph |
|
Generate random graphs using preferential attachment
Description
barabasi.game() was renamed tosample_pa() to create a moreconsistent API.
Usage
barabasi.game( 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)Arguments
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 Thisargument is only used if both |
out.dist | Numeric vector, the distribution of the number of edges toadd in each time step. This argument is only used if the |
out.seq | Numeric vector giving the number of edges to add in each timestep. Its first element is ignored as no edges are added in the first timestep. |
out.pref | Logical, if true the total degree is used for calculatingthe citation probability, otherwise the in-degree is used. |
zero.appeal | The ‘attractiveness’ of the vertices with noadjacent edges. See details below. |
directed | Whether to create a directed graph. |
algorithm | The algorithm to use for the graph generation. |
start.graph |
|
Vertex and edge betweenness centrality
Description
The vertex and edge betweenness are (roughly) defined by the number ofgeodesics (shortest paths) going through a vertex or an edge.
Usage
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)Arguments
graph | The graph to analyze. |
v | The vertices for which the vertex betweenness will be calculated. |
directed | Logical, whether directed paths should be considered whiledetermining the shortest paths. |
weights | Optional positive weight vector for calculating weightedbetweenness. If the graph has a |
normalized | Logical scalar, whether to normalize the betweennessscores. If
where |
cutoff | The maximum shortest path length to consider when calculatingbetweenness. If negative, then there is no such limit. |
e | The edges for which the edge betweenness will be calculated. |
Details
The vertex betweenness of vertexv is defined by
\sum_{i\ne j, i\ne v, j\ne v} g_{ivj}/g_{ij}
The edge betweenness of edgee is defined by
\sum_{i\ne j} g_{iej}/g_{ij}.
betweenness() calculates vertex betweenness,edge_betweenness()calculates edge betweenness.
Hereg_{ij} is the total number of shortest paths between verticesi andj whileg_{ivj} is the number of those shortest pathswhich pass though vertexv.
Both functions allow you to consider only paths of lengthcutoff orsmaller; this can be run for larger graphs, as the running time is notquadratic (ifcutoff is small). Ifcutoff is negative (the default),then the function calculates the exact betweenness scores. Since igraph 1.6.0,acutoff value of zero is treated literally, i.e. paths of length largerthan zero are ignored.
For calculating the betweenness a similar algorithm to the one proposed byBrandes (see References) is used.
Value
A numeric vector with the betweenness score for each vertex inv forbetweenness().
A numeric vector with the edge betweenness score for each edge ineforedge_betweenness().
Note
edge_betweenness() might give false values for graphs withmultiple edges.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
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.Journalof Mathematical Sociology 25(2):163-177, 2001.doi:10.1080/0022250X.2001.9990249
See Also
closeness(),degree(),harmonic_centrality()
Centrality measuresalpha_centrality(),authority_score(),closeness(),diversity(),eigen_centrality(),harmonic_centrality(),hits_scores(),page_rank(),power_centrality(),spectrum(),strength(),subgraph_centrality()
Examples
g <- sample_gnp(10, 3 / 10)betweenness(g)edge_betweenness(g)Breadth-first search
Description
Breadth-first search is an algorithm to traverse a graph. We start from aroot vertex and spread along every edge “simultaneously”.
Usage
bfs( graph, root, mode = c("out", "in", "all", "total"), ..., unreachable = TRUE, restricted = NULL, order = TRUE, rank = FALSE, parent = FALSE, pred = FALSE, succ = FALSE, dist = FALSE, callback = NULL, extra = NULL, rho = parent.frame(), neimode = deprecated(), father = deprecated())Arguments
Details
The callback function must have the following arguments:
- graph
The input graph is passed to the callback function here.
- data
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.
- extra
The extra argument.
The callback must returnFALSEto continue the search orTRUE to terminate it. See examples below on how touse the callback function.
Value
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
modeargument of the function call.Note that for undirected graphs this is always ‘all’, irrespectively of the supplied value.- 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.
- parent
Numeric vector. The parent of each vertex, i.e. the vertex it was discovered from.
- father
Like parent, kept for compatibility for now.
- 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
NaN.
Note thatorder,rank,parent,pred,succanddist might beNULL if their corresponding argument isFALSE, i.e. if their calculation is not requested.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
dfs() for depth-first search.
Other structural.properties:component_distribution(),connect(),constraint(),coreness(),degree(),dfs(),distance_table(),edge_density(),feedback_arc_set(),feedback_vertex_set(),girth(),is_acyclic(),is_dag(),is_matching(),k_shortest_paths(),knn(),reciprocity(),subcomponent(),subgraph(),topo_sort(),transitivity(),unfold_tree(),which_multiple(),which_mutual()
Examples
## Two ringsbfs(make_ring(10) %du% make_ring(10), root = 1, "out", order = TRUE, rank = TRUE, parent = TRUE, pred = TRUE, succ = TRUE, dist = TRUE)## How to use a callbackf <- 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 componentf <- function(graph, data, extra) { data["succ"] == -1}bfs(make_ring(10) %du% make_ring(10), root = 1, callback = f)Biconnected components
Description
biconnected.components() was renamed tobiconnected_components() to create a moreconsistent API.
Usage
biconnected.components(graph)Arguments
graph | The input graph. It is treated as an undirected graph, even ifit is directed. |
Biconnected components
Description
Finding the biconnected components of a graph
Usage
biconnected_components(graph)Arguments
graph | The input graph. It is treated as an undirected graph, even ifit is directed. |
Details
A graph is biconnected if the removal of any single vertex (and its adjacentedges) 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 itsedges: every edge is a member of exactly one biconnected component. Notethat this is not true for vertices: the same vertex can be part of manybiconnected components.
Value
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
articulation_points().
Related documentation in the C library
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
articulation_points(),components(),is_connected(),vertex_connectivity()
Connected componentsarticulation_points(),component_distribution(),decompose(),is_biconnected()
Examples
g <- disjoint_union(make_full_graph(5), make_full_graph(5))clu <- components(g)$membershipg <- add_edges(g, c(which(clu == 1), which(clu == 2)))bc <- biconnected_components(g)Decide whether a graph is bipartite
Description
bipartite.mapping() was renamed tobipartite_mapping() to create a moreconsistent API.
Usage
bipartite.mapping(graph)Arguments
graph | The input graph. |
Project a bipartite graph
Description
bipartite.projection() was renamed tobipartite_projection() to create a moreconsistent API.
Usage
bipartite.projection( graph, types = NULL, multiplicity = TRUE, probe1 = NULL, which = c("both", "true", "false"), remove.type = TRUE)Arguments
graph | The input graph. It can be directed, but edge directions areignored 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 theprojections in the resulting list. If given, then it is considered as avertex id (or a symbolic vertex name); the projection containing this vertexwill be the first one in the result list. This argument is ignored if onlyone 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 |
Project a bipartite graph
Description
bipartite.projection.size() was renamed tobipartite_projection_size() to create a moreconsistent API.
Usage
bipartite.projection.size(graph, types = NULL)Arguments
graph | The input graph. It can be directed, but edge directions areignored during the computation. |
types | An optional vertex type vector to use instead of the‘ |
Bipartite random graphs
Description
bipartite.random.game() was renamed tosample_bipartite() to create a moreconsistent API.
Usage
bipartite.random.game( n1, n2, type = c("gnp", "gnm"), p, m, directed = FALSE, mode = c("out", "in", "all"))Arguments
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 alsothe |
mode | Character scalar, specifies how to direct the edges in directedgraphs. If it is ‘out’, then directed edges point from bottomvertices to top vertices. If it is ‘in’, edges point from topvertices to bottom vertices. ‘out’ and ‘in’ do not generatemutual edges. If this argument is ‘all’, then each edge direction isconsidered independently and mutual edges might be generated. This argumentis ignored for undirected graphs. |
Bipartite random graphs
Description
Generate bipartite graphs using the Erdős-Rényi model
Usage
bipartite_gnm(...)bipartite_gnp(...)sample_bipartite_gnm( n1, n2, m, ..., directed = FALSE, mode = c("out", "in", "all"))sample_bipartite_gnp( n1, n2, p, ..., directed = FALSE, mode = c("out", "in", "all"))Arguments
... | Passed to |
n1 | Integer scalar, the number of bottom vertices. |
n2 | Integer scalar, the number of top vertices. |
m | Integer scalar, the number of edges for |
directed | Logical scalar, whether to create a directed graph. See alsothe |
mode | Character scalar, specifies how to direct the edges in directedgraphs. If it is ‘out’, then directed edges point from bottomvertices to top vertices. If it is ‘in’, edges point from topvertices to bottom vertices. ‘out’ and ‘in’ do not generatemutual edges. If this argument is ‘all’, then each edge direction isconsidered independently and mutual edges might be generated. This argumentis ignored for undirected graphs. |
p | Real scalar, connection probability for |
Details
Similarly to unipartite (one-mode) networks, we can define theG(n,p), andG(n,m) graph classes for bipartite graphs, via their generating process.InG(n,p) every possible edge between top and bottom vertices is realizedwith probabilityp, independently of the rest of the edges. InG(n,m), weuniformly choosem edges to realize.
See Also
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(),sample_tree()
Examples
## empty graphsample_bipartite_gnp(10, 5, p = 0)## full graphsample_bipartite_gnp(10, 5, p = 1)## random bipartite graphsample_bipartite_gnp(10, 5, p = .1)## directed bipartite graph, G(n,m)sample_bipartite_gnm(10, 5, m = 20, directed = TRUE, mode = "all")Decide whether a graph is bipartite
Description
This function decides whether the vertices of a network can be mapped to twovertex types in a way that no vertices of the same type are connected.
Usage
bipartite_mapping(graph)Arguments
graph | The input graph. |
Details
A bipartite graph in igraph has a ‘type’ vertex attributegiving the two vertex types.
This function simply checks whether a graphcould be bipartite. Ittries to find a mapping that gives a possible division of the vertices intotwo classes, such that no two vertices of the same class are connected by anedge.
The existence of such a mapping is equivalent of having no circuits of oddlength in the graph. A graph with loop edges cannot bipartite.
Note that the mapping is not necessarily unique, e.g. if the graph has atleast two components, then the vertices in the separate components can bemapped independently.
Value
A named list with two elements:
- res
A logical scalar,
TRUEif the can be bipartite,FALSEotherwise.- type
A possible vertex type mapping, a logical vector.If no such mapping exists, then an empty vector.
Related documentation in the C library
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
Bipartite graphsbipartite_projection(),is_bipartite(),make_bipartite_graph()
Examples
## Rings with an even number of vertices are bipartiteg <- make_ring(10)bipartite_mapping(g)## All star graphs are bipartiteg2 <- make_star(10)bipartite_mapping(g2)## A graph containing a triangle is not bipartiteg3 <- make_ring(10)g3 <- add_edges(g3, c(1, 3))bipartite_mapping(g3)Project a bipartite graph
Description
A bipartite graph is projected into two one-mode networks
Usage
bipartite_projection( graph, types = NULL, multiplicity = TRUE, probe1 = NULL, which = c("both", "true", "false"), remove.type = TRUE)bipartite_projection_size(graph, types = NULL)Arguments
graph | The input graph. It can be directed, but edge directions areignored 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 theprojections in the resulting list. If given, then it is considered as avertex id (or a symbolic vertex name); the projection containing this vertexwill be the first one in the result list. This argument is ignored if onlyone 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 |
Details
Bipartite graphs have atype vertex attribute in igraph, this isboolean andFALSE for the vertices of the first kind andTRUEfor vertices of the second kind.
bipartite_projection_size() calculates the number of vertices and edgesin the two projections of the bipartite graphs, without calculating theprojections themselves. This is useful to check how much memory theprojections would need if you have a large bipartite graph.
bipartite_projection() calculates the actual projections. You can usetheprobe1 argument to specify the order of the projections in theresult. By default vertex typeFALSE is the first andTRUE isthe second.
bipartite_projection() keeps vertex attributes.
Value
A list of two undirected graphs. See details above.
Related documentation in the C library
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
Bipartite graphsbipartite_mapping(),is_bipartite(),make_bipartite_graph()
Examples
## Projection of a full bipartite graph is a full graphg <- make_full_bipartite_graph(10, 5)proj <- bipartite_projection(g)isomorphic(proj[[1]], make_full_graph(10))isomorphic(proj[[2]], make_full_graph(5))## The projection keeps the vertex attributesM <- 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)Mg2 <- 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)Calculate Cohesive Blocks
Description
blockGraphs() was renamed tographs_from_cohesive_blocks() to create a moreconsistent API.
Usage
blockGraphs(blocks, graph)Arguments
graph | For For |
Find Bonacich Power Centrality Scores of Network Positions
Description
bonpow() was renamed topower_centrality() to create a moreconsistent API.
Usage
bonpow( graph, nodes = V(graph), loops = FALSE, exponent = 1, rescale = FALSE, tol = 1e-07, sparse = TRUE)Arguments
graph | the input graph. |
nodes | vertex sequence indicating which vertices are to be included inthe calculation. By default, all vertices are included. |
loops | boolean indicating whether or not the diagonal should betreated as valid data. Set this true if and only if the data can containloops. |
exponent | exponent (decay rate) for the Bonacich power centralityscore; can be negative |
rescale | if true, centrality scores are rescaled such that they sum to1. |
tol | tolerance for near-singularities during matrix inversion (see |
sparse | Logical scalar, whether to use sparse matrices for thecalculation. The ‘Matrix’ package is required for sparse matrixsupport |
Concatenate edge sequences
Description
Concatenate edge sequences
Usage
## S3 method for class 'igraph.es'c(..., recursive = FALSE)Arguments
... | The edge sequences to concatenate. They mustall refer to the same graph. |
recursive | Ignored, included for S3 compatibility with thebase |
Value
An edge sequence, the input sequences concatenated.
See Also
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()
Examples
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
Description
Concatenate vertex sequences
Usage
## S3 method for class 'igraph.vs'c(..., recursive = FALSE)Arguments
... | The vertex sequences to concatenate. They mustrefer to the same graph. |
recursive | Ignored, included for S3 compatibility withthe base |
Value
A vertex sequence, the input sequences concatenated.
See Also
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()
Examples
g <- make_(ring(10), with_vertex_(name = LETTERS[1:10]))c(V(g)[1], V(g)["A"], V(g)[1:4])Graph generation based on different vertex types
Description
callaway.traits.game() was renamed tosample_traits_callaway() to create a moreconsistent API.
Usage
callaway.traits.game( nodes, types, edge.per.step = 1, type.dist = rep(1, types), pref.matrix = matrix(1, types, types), directed = FALSE)Arguments
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 bestationary in time. |
pref.matrix | A matrix giving the preferences of the given vertextypes. These should be probabilities, i.e. numbers between zero and one. |
directed | Logical constant, whether to generate directed graphs. |
Canonical permutation of a graph
Description
canonical.permutation() was renamed tocanonical_permutation() to create a moreconsistent API.
Usage
canonical.permutation( graph, colors = NULL, sh = c("fm", "f", "fs", "fl", "flm", "fsm"))Arguments
graph | The input graph, treated as undirected. |
colors | The colors of the individual vertices of the graph; onlyvertices having the same color are allowed to match each other in anautomorphism. When omitted, igraph uses the |
sh | Type of the heuristics to use for the BLISS algorithm. See detailsfor possible values. |
Canonical permutation of a graph
Description
The canonical permutation brings every isomorphic graphs into the same(labeled) graph.
Usage
canonical_permutation( graph, colors = NULL, sh = c("fm", "f", "fs", "fl", "flm", "fsm"))Arguments
graph | The input graph, treated as undirected. |
colors | The colors of the individual vertices of the graph; onlyvertices having the same color are allowed to match each other in anautomorphism. When omitted, igraph uses the |
sh | Type of the heuristics to use for the BLISS algorithm. See detailsfor possible values. |
Details
canonical_permutation() computes a permutation which brings the graphinto canonical form, as defined by the BLISS algorithm. All isomorphicgraphs have the same canonical form.
See the paper below for the details about BLISS. This and more informationis available athttp://www.tcs.hut.fi/Software/bliss/index.html.
The possible values for thesh argument are:
- "f"
First non-singleton cell.
- "fl"
First largest non-singleton cell.
- "fs"
First smallest non-singleton cell.
- "fm"
First maximally non-trivially connectec non-singleton cell.
- "flm"
Largest maximally non-trivially connected non-singleton cell.
- "fsm"
Smallest maximally non-trivially connected non-singleton cell.
See the paper in references for detailsabout these.
Value
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:
- "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.
- "group_size"
The size of the automorphism group of the input graph, as a string.The string representation is necessary because the group sizecan easily exceed values that are exactly representable in floating point.
Related documentation in the C library
Author(s)
Tommi Junttila for BLISS, Gabor Csardicsardi.gabor@gmail.com for the igraph and R interfaces.
References
Tommi Junttila and Petteri Kaski: Engineering an EfficientCanonical Labeling Tool for Large and Sparse Graphs,Proceedings ofthe Ninth Workshop on Algorithm Engineering and Experiments and the FourthWorkshop on Analytic Algorithms and Combinatorics. 2007.
See Also
permute() to apply a permutation to a graph,isomorphic() for deciding graph isomorphism, possiblybased on canonical labels.
Other graph isomorphism:count_isomorphisms(),count_subgraph_isomorphisms(),graph_from_isomorphism_class(),isomorphic(),isomorphism_class(),isomorphisms(),subgraph_isomorphic(),subgraph_isomorphisms()
Examples
## Calculate the canonical form of a random graphg1 <- sample_gnm(10, 20)cp1 <- canonical_permutation(g1)cf1 <- permute(g1, cp1$labeling)## Do the same with a random permutation of itg2 <- permute(g1, sample(vcount(g1)))cp2 <- canonical_permutation(g2)cf2 <- permute(g2, cp2$labeling)## Check that they are the sameel1 <- as_edgelist(cf1)el2 <- as_edgelist(cf2)el1 <- el1[order(el1[, 1], el1[, 2]), ]el2 <- el2[order(el2[, 1], el2[, 2]), ]all(el1 == el2)Palette for categories
Description
This is a color blind friendly palette fromhttps://jfly.uni-koeln.de/color/. It has 8 colors.
Usage
categorical_pal(n)Arguments
n | The number of colors in the palette. We simply take the first |
Details
This is the suggested palette for visualizations where vertex colorsmark categories, e.g. community membership.
Value
A character vector of RGB color codes.
Examples
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)See Also
Other palettes:diverging_pal(),r_pal(),sequential_pal()
Centralize a graph according to the betweenness of vertices
Description
Seecentralize() for a summary of graph centralization.
Usage
centr_betw(graph, directed = TRUE, normalized = TRUE)Arguments
graph | The input graph. |
directed | logical scalar, whether to use directed shortest paths forcalculating betweenness. |
normalized | Logical scalar. Whether to normalize the graph levelcentrality score by dividing by the theoretical maximum. |
Value
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 scorefor a graph with the given number of vertices,using the same parameters.If the
normalizedargument wasTRUE,then the result was divided by this number.
See Also
Other centralization related:centr_betw_tmax(),centr_clo(),centr_clo_tmax(),centr_degree(),centr_degree_tmax(),centr_eigen(),centr_eigen_tmax(),centralize()
Examples
# A BA graph is quite centralizedg <- sample_pa(1000, m = 4)centr_degree(g)$centralizationcentr_clo(g, mode = "all")$centralizationcentr_betw(g, directed = FALSE)$centralizationcentr_eigen(g, directed = FALSE)$centralizationTheoretical maximum for betweenness centralization
Description
Seecentralize() for a summary of graph centralization.
Usage
centr_betw_tmax(graph = NULL, nodes = 0, directed = TRUE)Arguments
graph | The input graph. It can also be |
nodes | The number of vertices. This is ignored if the graph isgiven. |
directed | Logical scalar, whether to use directed shortest pathsfor calculating betweenness. Ignored if an undirected graph wasgiven. |
Value
Real scalar, the theoretical maximum (unnormalized) graphbetweenness centrality score for graphs with given order and otherparameters.
Related documentation in the C library
centralization_betweenness_tmax().
See Also
Other centralization related:centr_betw(),centr_clo(),centr_clo_tmax(),centr_degree(),centr_degree_tmax(),centr_eigen(),centr_eigen_tmax(),centralize()
Examples
# A BA graph is quite centralizedg <- sample_pa(1000, m = 4)centr_betw(g, normalized = FALSE)$centralization %>% `/`(centr_betw_tmax(g))centr_betw(g, normalized = TRUE)$centralizationCentralize a graph according to the closeness of vertices
Description
Seecentralize() for a summary of graph centralization.
Usage
centr_clo(graph, mode = c("out", "in", "all", "total"), normalized = TRUE)Arguments
graph | The input graph. |
mode | This is the same as the |
normalized | Logical scalar. Whether to normalize the graph levelcentrality score by dividing by the theoretical maximum. |
Value
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 scorefor a graph with the given number of vertices,using the same parameters.If the
normalizedargument wasTRUE,then the result was divided by this number.
Related documentation in the C library
See Also
Other centralization related:centr_betw(),centr_betw_tmax(),centr_clo_tmax(),centr_degree(),centr_degree_tmax(),centr_eigen(),centr_eigen_tmax(),centralize()
Examples
# A BA graph is quite centralizedg <- sample_pa(1000, m = 4)centr_degree(g)$centralizationcentr_clo(g, mode = "all")$centralizationcentr_betw(g, directed = FALSE)$centralizationcentr_eigen(g, directed = FALSE)$centralizationTheoretical maximum for closeness centralization
Description
Seecentralize() for a summary of graph centralization.
Usage
centr_clo_tmax(graph = NULL, nodes = 0, mode = c("out", "in", "all", "total"))Arguments
graph | The input graph. It can also be |
nodes | The number of vertices. This is ignored if the graph isgiven. |
mode | This is the same as the |
Value
Real scalar, the theoretical maximum (unnormalized) graphcloseness centrality score for graphs with given order and otherparameters.
Related documentation in the C library
centralization_closeness_tmax().
See Also
Other centralization related:centr_betw(),centr_betw_tmax(),centr_clo(),centr_degree(),centr_degree_tmax(),centr_eigen(),centr_eigen_tmax(),centralize()
Examples
# A BA graph is quite centralizedg <- sample_pa(1000, m = 4)centr_clo(g, normalized = FALSE)$centralization %>% `/`(centr_clo_tmax(g))centr_clo(g, normalized = TRUE)$centralizationCentralize a graph according to the degrees of vertices
Description
Seecentralize() for a summary of graph centralization.
Usage
centr_degree( graph, mode = c("all", "out", "in", "total"), loops = TRUE, normalized = TRUE)Arguments
graph | The input graph. |
mode | This is the same as the |
loops | Logical scalar, whether to consider loops edges whencalculating the degree. |
normalized | Logical scalar. Whether to normalize the graph levelcentrality score by dividing by the theoretical maximum. |
Value
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 scorefor a graph with the given number of vertices,using the same parameters.If the
normalizedargument wasTRUE,then the result was divided by this number.
Related documentation in the C library
See Also
Other centralization related:centr_betw(),centr_betw_tmax(),centr_clo(),centr_clo_tmax(),centr_degree_tmax(),centr_eigen(),centr_eigen_tmax(),centralize()
Examples
# A BA graph is quite centralizedg <- sample_pa(1000, m = 4)centr_degree(g)$centralizationcentr_clo(g, mode = "all")$centralizationcentr_betw(g, directed = FALSE)$centralizationcentr_eigen(g, directed = FALSE)$centralizationTheoretical maximum for degree centralization
Description
Seecentralize() for a summary of graph centralization.
Usage
centr_degree_tmax( graph = NULL, nodes = 0, mode = c("all", "out", "in", "total"), loops)Arguments
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 whencalculating the degree. |
Value
Real scalar, the theoretical maximum (unnormalized) graph degreecentrality score for graphs with given order and other parameters.
See Also
Other centralization related:centr_betw(),centr_betw_tmax(),centr_clo(),centr_clo_tmax(),centr_degree(),centr_eigen(),centr_eigen_tmax(),centralize()
Examples
# A BA graph is quite centralizedg <- sample_pa(1000, m = 4)centr_degree(g, normalized = FALSE)$centralization %>% `/`(centr_degree_tmax(g, loops = FALSE))centr_degree(g, normalized = TRUE)$centralizationCentralize a graph according to the eigenvector centrality of vertices
Description
Seecentralize() for a summary of graph centralization.
Usage
centr_eigen( graph, directed = FALSE, scale = deprecated(), options = arpack_defaults(), normalized = TRUE)Arguments
graph | The input graph. |
directed | logical scalar, whether to use directed shortest paths forcalculating eigenvector centrality. |
scale |
|
options | This is passed to |
normalized | Logical scalar. Whether to normalize the graph levelcentrality score by dividing by the theoretical maximum. |
Value
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
eigen_centrality()for details.- centralization
The graph level centrality index.
- theoretical_max
The same as above, the theoretical maximum centralization scorefor a graph with the same number of vertices.
Related documentation in the C library
centralization_eigenvector_centrality().
See Also
Other centralization related:centr_betw(),centr_betw_tmax(),centr_clo(),centr_clo_tmax(),centr_degree(),centr_degree_tmax(),centr_eigen_tmax(),centralize()
Examples
# A BA graph is quite centralizedg <- sample_pa(1000, m = 4)centr_degree(g)$centralizationcentr_clo(g, mode = "all")$centralizationcentr_betw(g, directed = FALSE)$centralizationcentr_eigen(g, directed = FALSE)$centralization# The most centralized graph according to eigenvector centralityg0 <- make_graph(c(2, 1), n = 10, dir = FALSE)g1 <- make_star(10, mode = "undirected")centr_eigen(g0)$centralizationcentr_eigen(g1)$centralizationTheoretical maximum for eigenvector centralization
Description
Seecentralize() for a summary of graph centralization.
Usage
centr_eigen_tmax( graph = NULL, nodes = 0, directed = FALSE, scale = deprecated())Arguments
Value
Real scalar, the theoretical maximum (unnormalized) grapheigenvector centrality score for graphs with given vertex count andother parameters.
Related documentation in the C library
centralization_eigenvector_centrality_tmax().
See Also
Other centralization related:centr_betw(),centr_betw_tmax(),centr_clo(),centr_clo_tmax(),centr_degree(),centr_degree_tmax(),centr_eigen(),centralize()
Examples
# A BA graph is quite centralizedg <- sample_pa(1000, m = 4)centr_eigen(g, normalized = FALSE)$centralization %>% `/`(centr_eigen_tmax(g))centr_eigen(g, normalized = TRUE)$centralizationCentralize a graph according to the betweenness of vertices
Description
centralization.betweenness() was renamed tocentr_betw() to create a moreconsistent API.
Usage
centralization.betweenness(graph, directed = TRUE, normalized = TRUE)Arguments
graph | The input graph. |
directed | logical scalar, whether to use directed shortest paths forcalculating betweenness. |
normalized | Logical scalar. Whether to normalize the graph levelcentrality score by dividing by the theoretical maximum. |
Theoretical maximum for betweenness centralization
Description
centralization.betweenness.tmax() was renamed tocentr_betw_tmax() to create a moreconsistent API.
Usage
centralization.betweenness.tmax(graph = NULL, nodes = 0, directed = TRUE)Arguments
graph | The input graph. It can also be |
nodes | The number of vertices. This is ignored if the graph isgiven. |
directed | Logical scalar, whether to use directed shortest pathsfor calculating betweenness. Ignored if an undirected graph wasgiven. |
Centralize a graph according to the closeness of vertices
Description
centralization.closeness() was renamed tocentr_clo() to create a moreconsistent API.
Usage
centralization.closeness( graph, mode = c("out", "in", "all", "total"), normalized = TRUE)Arguments
graph | The input graph. |
mode | This is the same as the |
normalized | Logical scalar. Whether to normalize the graph levelcentrality score by dividing by the theoretical maximum. |
Theoretical maximum for closeness centralization
Description
centralization.closeness.tmax() was renamed tocentr_clo_tmax() to create a moreconsistent API.
Usage
centralization.closeness.tmax( graph = NULL, nodes = 0, mode = c("out", "in", "all", "total"))Arguments
graph | The input graph. It can also be |
nodes | The number of vertices. This is ignored if the graph isgiven. |
mode | This is the same as the |
Centralize a graph according to the degrees of vertices
Description
centralization.degree() was renamed tocentr_degree() to create a moreconsistent API.
Usage
centralization.degree( graph, mode = c("all", "out", "in", "total"), loops = TRUE, normalized = TRUE)Arguments
graph | The input graph. |
mode | This is the same as the |
loops | Logical scalar, whether to consider loops edges whencalculating the degree. |
normalized | Logical scalar. Whether to normalize the graph levelcentrality score by dividing by the theoretical maximum. |
Theoretical maximum for degree centralization
Description
centralization.degree.tmax() was renamed tocentr_degree_tmax() to create a moreconsistent API.
Usage
centralization.degree.tmax( graph = NULL, nodes = 0, mode = c("all", "out", "in", "total"), loops = FALSE)Arguments
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 whencalculating the degree. |
Centralize a graph according to the eigenvector centrality of vertices
Description
centralization.evcent() was renamed tocentr_eigen() to create a moreconsistent API.
Usage
centralization.evcent( graph, directed = FALSE, scale = TRUE, options = arpack_defaults(), normalized = TRUE)Arguments
graph | The input graph. |
directed | logical scalar, whether to use directed shortest paths forcalculating eigenvector centrality. |
scale |
|
options | This is passed to |
normalized | Logical scalar. Whether to normalize the graph levelcentrality score by dividing by the theoretical maximum. |
Theoretical maximum for betweenness centralization
Description
centralization.evcent.tmax() was renamed tocentr_eigen_tmax() to create a moreconsistent API.
Usage
centralization.evcent.tmax( graph = NULL, nodes = 0, directed = FALSE, scale = TRUE)Arguments
Centralization of a graph
Description
Centralization is a method for creating a graph level centralizationmeasure from the centrality scores of the vertices.
Usage
centralize(scores, theoretical.max = 0, normalized = TRUE)Arguments
scores | The vertex level centrality scores. |
theoretical.max | Real scalar. The graph-level centralization measure ofthe most centralized graph with the same number of vertices as the graphunder study. This is only used if the |
normalized | Logical scalar. Whether to normalize the graph levelcentrality score by dividing by the supplied theoretical maximum. |
Details
Centralization is a general method for calculating a graph-levelcentrality score based on node-level centrality measure. The formula forthis is
C(G)=\sum_v (\max_w c_w - c_v),
wherec_v is the centrality of vertexv.
The graph-level centralization measure can be normalized by dividing by themaximum theoretical score for a graph with the same number of vertices,using the same parameters, e.g. directedness, whether we consider loopedges, etc.
For degree, closeness and betweenness the most centralized structure issome version of the star graph, in-star, out-star or undirected star.
For eigenvector centrality the most centralized structure is the graphwith a single edge (and potentially many isolates).
centralize() implements general centralization formula to calculatea graph-level score from vertex-level scores.
Value
A real scalar, the centralization of the graph from whichscores were derived.
Related documentation in the C library
References
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.
See Also
Other centralization related:centr_betw(),centr_betw_tmax(),centr_clo(),centr_clo_tmax(),centr_degree(),centr_degree_tmax(),centr_eigen(),centr_eigen_tmax()
Examples
# A BA graph is quite centralizedg <- sample_pa(1000, m = 4)centr_degree(g)$centralizationcentr_clo(g, mode = "all")$centralizationcentr_eigen(g, directed = FALSE)$centralization# Calculate centralization from pre-computed scoresdeg <- degree(g)tmax <- centr_degree_tmax(g, loops = FALSE)centralize(deg, tmax)# The most centralized graph according to eigenvector centralityg0 <- make_graph(c(2, 1), n = 10, dir = FALSE)g1 <- make_star(10, mode = "undirected")centr_eigen(g0)$centralizationcentr_eigen(g1)$centralizationCentralization of a graph
Description
centralize.scores() was renamed tocentralize() to create a moreconsistent API.
Usage
centralize.scores(scores, theoretical.max = 0, normalized = TRUE)Arguments
scores | The vertex level centrality scores. |
theoretical.max | Real scalar. The graph-level centralization measure ofthe most centralized graph with the same number of vertices as the graphunder study. This is only used if the |
normalized | Logical scalar. Whether to normalize the graph levelcentrality score by dividing by the supplied theoretical maximum. |
Random citation graphs
Description
cited.type.game() was renamed tosample_cit_types() to create a moreconsistent API.
Usage
cited.type.game( n, edges = 1, types = rep(0, n), pref = rep(1, length(types)), directed = TRUE, attr = TRUE)Arguments
n | Number of vertices. |
edges | Number of edges per step. |
types | Vector of length ‘ |
pref | Vector ( |
directed | Logical scalar, whether to generate directed networks. |
attr | Logical scalar, whether to add the vertex types to the generatedgraph as a vertex attribute called ‘ |
Random citation graphs
Description
citing.cited.type.game() was renamed tosample_cit_cit_types() to create a moreconsistent API.
Usage
citing.cited.type.game( n, edges = 1, types = rep(0, n), pref = matrix(1, nrow = length(types), ncol = length(types)), directed = TRUE, attr = TRUE)Arguments
n | Number of vertices. |
edges | Number of edges per step. |
types | Vector of length ‘ |
pref | Vector ( |
directed | Logical scalar, whether to generate directed networks. |
attr | Logical scalar, whether to add the vertex types to the generatedgraph as a vertex attribute called ‘ |
Functions to find cliques, i.e. complete subgraphs in a graph
Description
clique.number() was renamed toclique_num() to create a moreconsistent API.
Usage
clique.number(graph)Arguments
graph | The input graph. |
Functions to find cliques, i.e. complete subgraphs in a graph
Description
These functions find all, the largest or all the maximal cliques in anundirected graph. The size of the largest clique can also be calculated.
Tests if all pairs within a set of vertices are adjacent, i.e. whether theyform a clique. An empty set and singleton set are considered to be a clique.
Usage
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)is_clique(graph, candidate, directed = FALSE)Arguments
graph | The input graph. |
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 ( |
candidate | The vertex set to test for being a clique. |
directed | Whether to consider edge directions. |
Details
cliques() find all complete subgraphs in the input graph, obeying thesize limitations given in themin andmax arguments.
largest_cliques() finds all largest cliques in the input graph. Aclique is largest if there is no other clique including more vertices.
max_cliques() finds all maximal cliques in the input graph. Aclique is maximal if it cannot be extended to a larger clique. The largestcliques are always maximal, but a maximal clique is not necessarily thelargest.
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 histogramof clique sizes, between the given minimum and maximum clique size.
is_clique() tests whether all pairs within a vertex set are connected.
Value
cliques(),largest_cliques() andclique_num()return a list containing numeric vectors of vertex ids. Each list element isa clique, i.e. a vertex sequence of classigraph.vs.
max_cliques() returnsNULL, invisibly, if itsfileargument is notNULL. The output is written to the specified file inthis case.
clique_num() andcount_max_cliques() return an integerscalar.
clique_size_counts() returns a numeric vector with the clique sizes such thatthe i-th item belongs to cliques of size i. Trailing zeros are currentlytruncated, but this might change in future versions.
is_clique() returnsTRUE if the candidate vertex set formsa clique.
Related documentation in the C library
cliques(),largest_cliques(),clique_number(),largest_weighted_cliques(),weighted_clique_number(),maximal_cliques_hist(),clique_size_hist(),is_clique().
Author(s)
Tamas Nepuszntamas@gmail.com and Gabor Csardicsardi.gabor@gmail.com
References
For maximal cliques the following algorithm is implemented:David Eppstein, Maarten Loffler, Darren Strash: Listing All Maximal Cliquesin Sparse Graphs in Near-optimal Time.https://arxiv.org/abs/1006.5440
See Also
Other cliques:is_complete(),ivs(),weighted_cliques()
Examples
# this usually contains cliques of size sixg <- 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 usuallyg <- sample_gnp(100, 0.03)max_cliques(g)# Check that all returned vertex sets are indeed cliquesall(sapply(max_cliques(g), function (c) is_clique(g, c)))Closeness centrality of vertices
Description
Closeness centrality measures how many steps are required to access every othervertex from a given vertex.
Usage
closeness( graph, vids = V(graph), mode = c("out", "in", "all", "total"), weights = NULL, normalized = FALSE, cutoff = -1)Arguments
graph | The graph to analyze. |
vids | The vertices for which closeness will be calculated. |
mode | Character string, defined the types of the paths used formeasuring the distance in directed graphs. “in” measures the pathsto a vertex, “out” measures pathsfrom a vertex,all uses undirected paths. This argument is ignored for undirectedgraphs. |
weights | Optional positive weight vector for calculating weightedcloseness. If the graph has a |
normalized | Logical scalar, whether to calculate the normalizedcloseness, i.e. the inverse average distance to all reachable vertices.The non-normalized closeness is the inverse of the sum of distances toall reachable vertices. |
cutoff | The maximum path length to consider when calculating thecloseness. If zero or negative then there is no such limit. |
Details
The closeness centrality of a vertex is defined as the inverse of thesum of distances to all the other vertices in the graph:
\frac{1}{\sum_{i\ne v} d_{vi}}
If there is no (directed) path between vertexv andi, theni is omitted from the calculation. If no other vertices are reachablefromv, then its closeness is returned as NaN.
cutoff or smaller. This can be run for larger graphs, as the runningtime is not quadratic (ifcutoff is small). Ifcutoff isnegative (which is the default), then the function calculates the exactcloseness scores. Since igraph 1.6.0, acutoff value of zero is treatedliterally, i.e. path with a length greater than zero are ignored.
Closeness centrality is meaningful only for connected graphs. In disconnectedgraphs, consider using the harmonic centrality withharmonic_centrality()
Value
Numeric vector with the closeness values of all the vertices inv.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
Freeman, L.C. (1979). Centrality in Social Networks I:Conceptual Clarification.Social Networks, 1, 215-239.
See Also
Centrality measuresalpha_centrality(),authority_score(),betweenness(),diversity(),eigen_centrality(),harmonic_centrality(),hits_scores(),page_rank(),power_centrality(),spectrum(),strength(),subgraph_centrality()
Examples
g <- make_ring(10)g2 <- make_star(10)closeness(g)closeness(g2, mode = "in")closeness(g2, mode = "out")closeness(g2, mode = "all")Connected components of a graph
Description
cluster.distribution() was renamed tocomponent_distribution() to create a moreconsistent API.
Usage
cluster.distribution(graph, cumulative = FALSE, mul.size = FALSE, ...)Arguments
graph | The graph to analyze. |
cumulative | Logical, if TRUE the cumulative distirubution (relativefrequency) is calculated. |
mul.size | Logical. If TRUE the relative frequencies will be multipliedby the cluster sizes. |
... | Additional attributes to pass to |
Community structure detection based on edge betweenness
Description
Community structure detection based on the betweenness of the edgesin the network. This method is also known as the Girvan-Newmanalgorithm.
Usage
cluster_edge_betweenness( graph, weights = NULL, directed = TRUE, edge.betweenness = TRUE, merges = TRUE, bridges = TRUE, modularity = TRUE, membership = TRUE)Arguments
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 edgebetweenness for directed graphs. It is ignored for undirected graphs. |
edge.betweenness | Logical constant, whether to return the edgebetweenness of the edges at the time of their removal. |
merges | Logical constant, whether to return the merge matrixrepresenting the hierarchical community structure of the network. Thisargument is called |
bridges | Logical constant, whether to return a list the edge removalswhich actually splitted a component of the graph. |
modularity | Logical constant, whether to calculate the maximummodularity score, considering all possibly community structures along theedge-betweenness based edge removals. |
membership | Logical constant, whether to calculate the membershipvector corresponding to the highest possible modularity score. |
Details
The idea behind this method is that the betweenness of the edges connectingtwo communities is typically high, as many of the shortest paths betweenvertices in separate communities pass through them. The algorithmsuccessively removes edges with the highest betweenness, recalculatingbetweenness values after each removal. This way eventually the network splitsinto two components, then one of these components splits again, and so on,until all edges are removed. The resulting hierarhical partitioning of thevertices can be encoded as a dendrogram.
cluster_edge_betweenness() returns various information collectedthrough the run of the algorithm. Specifically,removed.edges containsthe edge IDs in order of the edges' removal;edge.betweenness containsthe betweenness of each of these at the time of their removal; andbridges contains the IDs of edges whose removal caused a split.
Value
cluster_edge_betweenness() returns acommunities() object, please see thecommunities()manual page for details.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
M Newman and M Girvan: Finding and evaluating communitystructure in networks,Physical Review E 69, 026113 (2004)
See Also
edge_betweenness() for the definition and calculationof the edge betweenness,cluster_walktrap(),cluster_fast_greedy(),cluster_leading_eigen() for other community detectionmethods.
Seecommunities() for extracting the results of the communitydetection.
Community detectionas_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()
Examples
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)ebCommunity structure via greedy optimization of modularity
Description
This function tries to find dense subgraph, also called communities ingraphs via directly optimizing a modularity score.
Usage
cluster_fast_greedy( graph, merges = TRUE, modularity = TRUE, membership = TRUE, weights = NULL)Arguments
graph | The input graph. It must be undirected and must not havemulti-edges. |
merges | Logical scalar, whether to return the merge matrix. |
modularity | Logical scalar, whether to return a vector containing themodularity after each merge. |
membership | Logical scalar, whether to calculate the membership vectorcorresponding to the maximum modularity score, considering all possiblecommunity structures along the merges. |
weights | The weights of the edges. It must be a positive numeric vector, |
Details
This function implements the fast greedy modularity optimization algorithmfor finding community structure, see A Clauset, MEJ Newman, C Moore: Findingcommunity structure in very large networks,http://www.arxiv.org/abs/cond-mat/0408187 for the details.
Value
cluster_fast_greedy() returns acommunities()object, please see thecommunities() manual page for details.
Author(s)
Tamas Nepuszntamas@gmail.com and Gabor Csardicsardi.gabor@gmail.com for the R interface.
References
A Clauset, MEJ Newman, C Moore: Finding community structure invery large networks, http://www.arxiv.org/abs/cond-mat/0408187
See Also
communities() for extracting the results.
See alsocluster_walktrap(),cluster_spinglass(),cluster_leading_eigen() andcluster_edge_betweenness(),cluster_louvain()cluster_leiden() for other methods.
Community detectionas_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()
Examples
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)Community detection algorithm based on interacting fluids
Description
The algorithm detects communities based on the simple idea ofseveral fluids interacting in a non-homogeneous environment(the graph topology), expanding and contracting based on theirinteraction and density.
Usage
cluster_fluid_communities(graph, no.of.communities)Arguments
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 begreater than 0 and fewer than number of vertices in the graph. |
Value
cluster_fluid_communities() returns acommunities()object, please see thecommunities() manual page for details.
Author(s)
Ferran Parés
References
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 SixthInternational Conference on Complex Networks and Their Applications),Springer, vol 689, p 229, doi: 10.1007/978-3-319-72150-7_19
See Also
Seecommunities() 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 detectionas_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()
Examples
g <- make_graph("Zachary")comms <- cluster_fluid_communities(g, 2)Infomap community finding
Description
Find community structure that minimizes the expected description length of arandom walker trajectory. If the graph is directed, edge directions willbe taken into account.
Usage
cluster_infomap( graph, e.weights = NULL, v.weights = NULL, nb.trials = 10, modularity = TRUE)Arguments
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 anyinteger value equal or larger than 1). |
modularity | Logical scalar, whether to calculate the modularity scoreof the detected community structure. |
Details
Please see the details of this method in the references given below.
Value
cluster_infomap() returns acommunities() object,please see thecommunities() manual page for details.
Author(s)
Martin Rosvall wrote the original C++ code. This was ported tobe more igraph-like by Emmanuel Navarro. The R interface andsome cosmetics was done by Gabor Csardicsardi.gabor@gmail.com.
References
The original paper: M. Rosvall and C. T. Bergstrom, Maps ofinformation flow reveal community structure in complex networks,PNAS105, 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 mapequation,Eur. Phys. J. Special Topics 178, 13 (2009).doi:10.1140/epjst/e2010-01179-1,https://arxiv.org/abs/0906.1405.
See Also
Other community finding methods andcommunities().
Community detectionas_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()
Examples
## Zachary's karate clubg <- make_graph("Zachary")imc <- cluster_infomap(g)membership(imc)communities(imc)Finding communities based on propagating labels
Description
This is a fast, nearly linear time algorithm for detecting communitystructure in networks. In works by labeling the vertices with unique labelsand then updating the labels by majority voting in the neighborhood of thevertex.
Usage
cluster_label_prop( graph, weights = NULL, ..., mode = c("out", "in", "all"), initial = NULL, fixed = NULL)Arguments
graph | The input graph. Note that the algorithm was originallydefined 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 thismakes sense only if you provided an initial state, otherwise this elementwill be ignored. Also note that vertices without labels cannot be fixed. |
Details
This function implements the community detection method described in:Raghavan, U.N. and Albert, R. and Kumara, S.: Near linear time algorithm todetect community structures in large-scale networks. Phys Rev E 76, 036106.(2007). This version extends the original method by the ability to take edgeweights into consideration and also by allowing some labels to be fixed.
From the abstract of the paper: “In our algorithm every node isinitialized with a unique label and at every step each node adopts the labelthat most of its neighbors currently have. In this iterative process denselyconnected groups of nodes form a consensus on a unique label to formcommunities.”
Value
cluster_label_prop() returns acommunities() object, please see thecommunities()manual page for details.
Author(s)
Tamas Nepuszntamas@gmail.com for the C implementation,Gabor Csardicsardi.gabor@gmail.com for this manual page.
References
Raghavan, U.N. and Albert, R. and Kumara, S.: Near linear timealgorithm to detect community structures in large-scale networks.PhysRev E 76, 036106. (2007)
See Also
communities() for extracting the actual results.
cluster_fast_greedy(),cluster_walktrap(),cluster_spinglass(),cluster_louvain() andcluster_leiden() for other community detection methods.
Community detectionas_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()
Examples
g <- sample_gnp(10, 5 / 10) %du% sample_gnp(9, 5 / 9)g <- add_edges(g, c(1, 12))cluster_label_prop(g)Community structure detecting based on the leading eigenvector of thecommunity matrix
Description
This function tries to find densely connected subgraphs in a graph bycalculating the leading non-negative eigenvector of the modularity matrix ofthe graph.
Usage
cluster_leading_eigen( graph, steps = -1, weights = NULL, start = NULL, options = arpack_defaults(), callback = NULL, extra = NULL, env = parent.frame())Arguments
graph | The input graph. Should be undirected as the method needs asymmetric matrix. |
steps | The number of steps to take, this is actually the number oftries 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. |
Details
The function documented in these section implements the ‘leadingeigenvector’ method developed by Mark Newman, see the reference below.
The heart of the method is the definition of the modularity matrix,B, which isB=A-P,A being the adjacency matrix of the(undirected) network, andP contains the probability that certainedges are present according to the ‘configuration model’. In otherwords, aP[i,j] element ofP is the probability that there isan edge between verticesi andj in a random network in whichthe degrees of all vertices are the same as in the input graph.
The leading eigenvector method works by calculating the eigenvector of themodularity matrix for the largest positive eigenvalue and then separatingvertices into two community based on the sign of the corresponding elementin the eigenvector. If all elements in the eigenvector are of the same signthat means that the network has no underlying comuunity structure. CheckNewman's paper to understand why this is a good method for detectingcommunity structure.
Value
cluster_leading_eigen() returns a named list with thefollowing members:
- membership
The membership vector at the end of the algorithm,when no more splits are possible.
- merges
The merges matrix starting from the statedescribed by the
membershipmember.This is a two-column matrix and each line describes a merge of two communities,the first line is the first merge and it creates community ‘N’,Nis the number of initial communities in the graph,the second line creates communityN+1, etc.- options
Information about the underlying ARPACK computation, see
arpack()for details.
Callback functions
Thecallback argument can be used tosupply a function that is called after each eigenvector calculation. Thefollowing arguments are supplied to this function:
- membership
The actual membership vector, with zero-based indexing.
- community
The community that the algorithm just tried to split, community numbering starts with zero here.
- value
The eigenvalue belonging to the leading eigenvector the algorithm just found.
- vector
The leading eigenvector the algorithm just found.
- multiplier
An R function that can be used to multiple the actual modularity matrixwith an arbitrary vector.Supply the vector as an argument to perform this multiplication.This function can be used with ARPACK.
- extra
The
extraargument that was passed tocluster_leading_eigen().
The callback function should return a scalar number. If this numberis non-zero, then the clustering is terminated.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
MEJ Newman: Finding community structure using the eigenvectorsof matrices, Physical Review E 74 036104, 2006.
See Also
modularity(),cluster_walktrap(),cluster_edge_betweenness(),cluster_fast_greedy(),as.dendrogram()
Community detectionas_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()
Examples
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)leccluster_leading_eigen(g, start = membership(lec))Finding community structure of a graph using the Leiden algorithm of Traag,van Eck & Waltman.
Description
The Leiden algorithm is similar to the Louvain algorithm,cluster_louvain(), but it is faster and yields higher qualitysolutions. It can optimize both modularity and the Constant Potts Model,which does not suffer from the resolution-limit (see preprinthttps://arxiv.org/abs/1104.3083).
Usage
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)Arguments
graph | The input graph. It must be undirected. |
objective_function | Whether to use the Constant Potts Model (CPM) ormodularity. 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. Higherresolutions lead to more smaller communities, while lower resolutions leadto 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 algorithmwill try to improve this provided membership. If no argument isprovided, the aglorithm simply starts from the singleton partition. |
n_iterations | the number of iterations to iterate the Leidenalgorithm. 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 basisof the |
Details
The Leiden algorithm consists of three phases: (1) local moving of nodes,(2) refinement of the partition and (3) aggregation of the network based onthe refined partition, using the non-refined partition to create an initialpartition for the aggregate network. In the local move procedure in theLeiden algorithm, only nodes whose neighborhood has changed are visited. Therefinement is done by restarting from a singleton partition within eachcluster and gradually merging the subclusters. When aggregating, a singlecluster may then be represented by several nodes (which are the subclustersidentified in the refinement).
The Leiden algorithm provides several guarantees. The Leiden algorithm istypically iterated: the output of one iteration is used as the input for thenext iteration. At each iteration all clusters are guaranteed to beconnected and well-separated. After an iteration in which nothing haschanged, all nodes and some parts are guaranteed to be locally optimallyassigned. Finally, asymptotically, all subsets of all clusters areguaranteed to be locally optimally assigned. For more details, please seeTraag, Waltman & van Eck (2019).
The objective function being optimized is
\frac{1}{2m} \sum_{ij} (A_{ij} - \gamma n_i n_j)\delta(\sigma_i, \sigma_j)
wherem is the total edge weight,A_{ij} is the weightof edge(i, j),\gamma is the so-called resolutionparameter,n_i is the node weight of nodei,\sigma_iis the cluster of nodei and\delta(x, y) = 1 if andonly ifx = y and0 otherwise. By settingn_i = k_i, thedegree of nodei, and dividing\gamma by2m, youeffectively obtain an expression for modularity.
Hence, the standard modularity will be optimized when you supply the degreesasvertex_weights and by supplying as a resolution parameter\frac{1}{2m}, withm the number of edges. If you do notspecify anyvertex_weights, the correct vertex weights and scaling of\gamma is determined automatically by theobjective_function argument.
Value
cluster_leiden() returns acommunities()object, please see thecommunities() manual page for details.
Author(s)
Vincent Traag
References
Traag, V. A., Waltman, L., & van Eck, N. J. (2019). From Louvainto Leiden: guaranteeing well-connected communities. Scientificreports, 9(1), 5233. doi: 10.1038/s41598-019-41695-z, arXiv:1810.08473v3 [cs.SI]
See Also
Seecommunities() 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 detectionas_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()
Examples
g <- make_graph("Zachary")# By default CPM is usedr <- quantile(strength(g))[2] / (gorder(g) - 1)# Set seed for sake of reproducibilityset.seed(1)ldc <- cluster_leiden(g, resolution = r)print(ldc)plot(ldc, g)Finding community structure by multi-level optimization of modularity
Description
This function implements the multi-level modularity optimization algorithmfor finding community structure, see references below. It is based on themodularity measure and a hierarchical approach.
Usage
cluster_louvain(graph, weights = NULL, resolution = 1)Arguments
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 toadjust the resolution parameter of the modularity function that the algorithmuses internally. Lower values typically yield fewer, larger clusters. Theoriginal definition of modularity is recovered when the resolution parameteris set to 1. |
Details
This function implements the multi-level modularity optimization algorithmfor finding community structure, see VD Blondel, J-L Guillaume, R Lambiotteand 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 vertexis moved to the community with which it achieves the highest contribution tomodularity. When no vertices can be reassigned, each community is considereda vertex on its own, and the process starts again with the mergedcommunities. The process stops when there is only a single vertex left orwhen 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.
Value
cluster_louvain() returns acommunities()object, please see thecommunities() manual page for details.
Author(s)
Tom Gregorovic, Tamas Nepuszntamas@gmail.com
References
Vincent D. Blondel, Jean-Loup Guillaume, Renaud Lambiotte,Etienne Lefebvre: Fast unfolding of communities in large networks. J. Stat.Mech. (2008) P10008
See Also
Seecommunities() 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 detectionas_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()
Examples
# This is so simple that we will have only one levelg <- 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)Optimal community structure
Description
This function calculates the optimal community structure of a graph, bymaximizing the modularity measure over all possible partitions.
Usage
cluster_optimal(graph, weights = NULL)Arguments
graph | The input graph. It may be undirected or directed. |
weights | The weights of the edges. It must be a positive numericvector, |
Details
This function calculates the optimal community structure for a graph, interms of maximal modularity score.
The calculation is done by transforming the modularity maximization into aninteger programming problem, and then calling the GLPK library to solvethat. Please the reference below for details.
Note that modularity optimization is an NP-complete problem, and all knownalgorithms for it have exponential time complexity. This means that youprobably don't want to run this function on larger graphs. Graphs with up tofifty vertices should be fine, graphs with a couple of hundred verticesmight be possible.
Value
cluster_optimal() returns acommunities() object,please see thecommunities() manual page for details.
Examples
## Zachary's karate clubg <- 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 secondsoc <- cluster_optimal(g)## Double check the resultprint(modularity(oc))print(modularity(g, membership(oc)))## Compare to the greedy optimizerfc <- cluster_fast_greedy(g)print(modularity(fc))Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
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.
See Also
communities() for the documentation of the result,modularity(). See alsocluster_fast_greedy() for afast greedy optimizer.
Community detectionas_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()
Finding communities in graphs based on statistical meachanics
Description
This function tries to find communities in graphs via a spin-glass model andsimulated annealing.
Usage
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)Arguments
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 agiven vertex without calculating all communities. Note that if this argumentis present then some other arguments are ignored. |
spins | Integer constant, the number of spins to use. This is the upperlimit for the number of communities. It is not a problem to supply a(reasonably) big number here, in which case some spin states will beunpopulated. |
parupdate | Logical constant, whether to update the spins of thevertices in parallel (synchronously) or not. This argument is ignored if thesecond form of the function is used (i.e. the ‘ |
start.temp | Real constant, the start temperature. This argument isignored if the second form of the function is used (i.e. the‘ |
stop.temp | Real constant, the stop temperature. The simulationterminates if the temperature lowers below this level. This argument isignored if the second form of the function is used (i.e. the‘ |
cool.fact | Cooling factor for the simulated annealing. This argumentis ignored if the second form of the function is used (i.e. the‘ |
update.rule | Character constant giving the ‘null-model’ of thesimulation. Possible values: “simple” and “config”.“simple” uses a random graph with the same number of edges as thebaseline probability and “config” uses a random graph with the samevertex degrees as the input graph. |
gamma | Real constant, the gamma argument of the algorithm. Thisspecifies the balance between the importance of present and non-presentedges in a community. Roughly, a comunity is a set of vertices having manyedges inside the community and few edges outside the community. The default1.0 value makes existing and non-existing links equally important. Smallervalues make the existing links, greater values the missing links moreimportant. |
implementation | Character scalar. Currently igraph contains twoimplementations for the Spin-glass community finding algorithm. The fasteroriginal implementation is the default. The other implementation, that takesinto account negative weights, can be chosen by supplying ‘neg’ here. |
gamma.minus | Real constant, the gamma.minus parameter of thealgorithm. This specifies the balance between the importance of present andnon-present negative weighted edges in a community. Smaller values ofgamma.minus, leads to communities with lesser negative intra-connectivity.If this argument is set to zero, the algorithm reduces to a graph coloringalgorithm, using the number of spins as the number of colors. This argumentis ignored if the ‘orig’ implementation is chosen. |
Details
This function tries to find communities in a graph. A community is a set ofnodes 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 negativeedges inside a community and many negative edges between communities. Notethat only the ‘neg’ implementation supports negative edge weights.
Thespinglass.cummunity function can solve two problems related tocommunity detection. If thevertex argument is not given (or it isNULL), then the regular community detection problem is solved(approximately), i.e. partitioning the vertices into communities, byoptimizing the an energy function.
If thevertex argument is given and it is notNULL, then itmust be a vertex id, and the same energy function is used to find thecommunity of the the given vertex. See also the examples below.
Value
If thevertex argument is not given, i.e. the first form isused then acluster_spinglass() returns acommunities() object.
If thevertex argument is present, i.e. the second form is used then anamed list is returned with the following components:
- community
Numeric vector giving the ids of the vertices in the same community as
vertex.- 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
vertex.- outer.links
The number of edges between the community of
vertexand the rest of the graph.
Author(s)
Jorg Reichardt for the original code and Gabor Csardicsardi.gabor@gmail.com for the igraph glue code.
Changes to the original function for including the possibility of negativeties were implemented by Vincent Traag (https://www.traag.net/).
References
J. Reichardt and S. Bornholdt: Statistical Mechanics ofCommunity 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 innetworks,Phys. Rev. E 69, 026113 (2004)
V.A. Traag and Jeroen Bruggeman: Community detection in networks withpositive and negative links,https://arxiv.org/abs/0811.2329 (2008).
See Also
Community detectionas_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()
Examples
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)Community structure via short random walks
Description
This function tries to find densely connected subgraphs, also calledcommunities in a graph via random walks. The idea is that short random walkstend to stay in the same community.
Usage
cluster_walktrap( graph, weights = NULL, steps = 4, merges = TRUE, modularity = TRUE, membership = TRUE)Arguments
graph | The input graph. Edge directions are ignored in directedgraphs. |
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 theresult. |
modularity | Logical scalar, whether to include the vector of themodularity scores in the result. If the |
membership | Logical scalar, whether to calculate the membership vectorfor the split corresponding to the highest modularity value. |
Details
This function is the implementation of the Walktrap community findingalgorithm, see Pascal Pons, Matthieu Latapy: Computing communities in largenetworks using random walks, https://arxiv.org/abs/physics/0512106
Value
cluster_walktrap() returns acommunities()object, please see thecommunities() manual page for details.
Author(s)
Pascal Pons (http://psl.pons.free.fr/) and Gabor Csardicsardi.gabor@gmail.com for the R and igraph interface
References
Pascal Pons, Matthieu Latapy: Computing communities in largenetworks using random walks, https://arxiv.org/abs/physics/0512106
See Also
Seecommunities() on getting the actual membershipvector, merge matrix, modularity score, etc.
modularity() andcluster_fast_greedy(),cluster_spinglass(),cluster_leading_eigen(),cluster_edge_betweenness(),cluster_louvain(),andcluster_leiden() for other community detectionmethods.
Community detectionas_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()
Examples
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)Connected components of a graph
Description
clusters() was renamed tocomponents() to create a moreconsistent API.
Usage
clusters(graph, mode = c("weak", "strong"))Arguments
graph | The graph to analyze. |
mode | Character string, either “weak” or “strong”. Fordirected graphs “weak” implies weakly, “strong” stronglyconnected components to search. It is ignored for undirected graphs. |
Cocitation coupling
Description
Two vertices are cocited if there is another vertex citing both of them.cocitation() simply counts how many types two vertices are cocited. Thebibliographic coupling of two vertices is the number of other vertices theyboth cite,bibcoupling() calculates this.
Usage
cocitation(graph, v = V(graph))bibcoupling(graph, v = V(graph))Arguments
graph | The graph object to analyze |
v | Vertex sequence or numeric vector, the vertex ids for which thecocitation or bibliographic coupling values we want to calculate. Thedefault is all vertices. |
Details
cocitation() calculates the cocitation counts for the vertices in thev argument and all vertices in the graph.
bibcoupling() calculates the bibliographic coupling for vertices inv and all vertices in the graph.
Calculating the cocitation or bibliographic coupling for only one vertexcosts the same amount of computation as for all vertices. This might changein the future.
Value
A numeric matrix withlength(v) lines andvcount(graph) columns. Element(i,j) contains the cocitationor bibliographic coupling for verticesv[i] andj.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
Other cocitation:similarity()
Examples
g <- make_kautz_graph(2, 3)cocitation(g)bibcoupling(g)Functions to deal with the result of network community detection
Description
code.length() was renamed tocode_len() to create a moreconsistent API.
Usage
code.length(communities)Calculate Cohesive Blocks
Description
cohesive.blocks() was renamed tocohesive_blocks() to create a moreconsistent API.
Usage
cohesive.blocks(graph, labels = TRUE)Arguments
graph | For For |
labels | Logical scalar, whether to add the vertex labels to the resultobject. These labels can be then used when reporting and plotting thecohesive blocks. |
Calculate Cohesive Blocks
Description
Calculates cohesive blocks for objects of classigraph.
Usage
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)Arguments
graph | For For |
labels | Logical scalar, whether to add the vertex labels to the resultobject. These labels can be then used when reporting and plotting thecohesive 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. (Symboliccolor names (e.g. ‘red’, ‘blue’, etc.) , RGB colors (e.g.‘#FF9900FF’), integer numbers referring to the current palette. Bydefault the given |
mark.groups | A list of vertex sets to mark on the plot by circlingthem. By default all cohesive blocks are marked, except the onecorresponding 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 projectfile containing all the data, or to create separated files for each item.See details below. |
Details
Cohesive blocking is a method of determining hierarchical subsets of graphvertices based on their structural cohesion (or vertex connectivity). For agiven graphG, a subset of its verticesS\subset V(G) is saidto be maximallyk-cohesive if there is no superset ofS withvertex connectivity greater than or equal tok. Cohesive blocking is aprocess through which, given ak-cohesive set of vertices, maximallyl-cohesive subsets are recursively identified withl>k. Thus ahierarchy of vertex subsets is found, with the entire graphG at itsroot.
The functioncohesive_blocks() implements cohesive blocking. Itreturns acohesiveBlocks object.cohesiveBlocks should behandled as an opaque class, i.e. its internal structure should not beaccessed directly, but through the functions listed here.
The functionlength can be used oncohesiveBlocks objects andit gives the number of blocks.
The functionblocks() returns the actual blocks stored in thecohesiveBlocks object. They are returned in a list of numericvectors, each containing vertex ids.
The functiongraphs_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 functioncohesion() returns a numeric vector, the cohesion of thedifferent blocks. The order of the blocks is the same as for theblocks() andgraphs_from_cohesive_blocks() functions.
The block hierarchy can be queried using thehierarchy() function. Itreturns an igraph graph, its vertex ids are ordered according the order ofthe blocks in theblocks() andgraphs_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 theactive graphics device, by callingigraph.plot.
Theexport_pajek() function can be used to export the graph and itscohesive blocks in Pajek format. It can either export a single Pajek projectfile with all the information, or a set of files, depending on itsproject.file argument. Ifproject.file isTRUE, thenthe following information is written to the file (or connection) given inthefile argument: (1) the input graph, together with its attributes,seewrite_graph() for details; (2) the hierarchy graph; and (3)one binary partition for each cohesive block. Ifproject.file isFALSE, then thefile argument must be a character scalar andit is used as the base name for the generated files. Iffile 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’ isthe number of the block, starting with one.
max_cohesion() returns the maximal cohesion of each vertex, i.e. thecohesion of the most cohesive block of the vertex.
The generic functionsummary() works oncohesiveBlocks objectsand it prints a one line summary to the terminal.
The generic functionprint() is also defined oncohesiveBlocksobjects and it is invoked automatically if the name of thecohesiveBlocks 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 fiveblocks. The first block always corresponds to the whole graph, even if itscohesion is zero. Then cohesion of the block and the number of vertices inthe block are shown. The last part is only printed if the display is wideenough 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 functionplot() plots the graph, showing one or morecohesive blocks in it.
Value
cohesive_blocks() returns acohesiveBlocks object.
blocks() returns a list of numeric vectors, containing vertex ids.
graphs_from_cohesive_blocks() returns a list of igraph graphs, corresponding to thecohesive blocks.
cohesion() returns a numeric vector, the cohesion of each block.
hierarchy() returns an igraph graph, the representation of the cohesiveblock hierarchy.
parent() returns a numeric vector giving the parent block of eachcohesive block, in the block hierarchy. The block at the root of thehierarchy has no parent and0 is returned for it.
plot_hierarchy(),plot() andexport_pajek() returnNULL,invisibly.
max_cohesion() returns a numeric vector with one entry for each vertex,giving the cohesion of its most cohesive block.
print() andsummary() return thecohesiveBlocks objectitself, invisibly.
length returns a numeric scalar, the number of blocks.
Author(s)
Gabor Csardicsardi.gabor@gmail.com for the currentimplementation, Peter McMahan (https://socialsciences.uchicago.edu/news/alumni-profile-peter-mcmahan-phd17-sociology)wrote the first version in R.
References
J. Moody and D. R. White. Structural cohesion and embeddedness:A hierarchical concept of social groups.American SociologicalReview, 68(1):103–127, Feb 2003,doi:10.2307/3088904.
See Also
Examples
## The graph from the Moody-White papermw <- 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 cohesionmwBlocksblocks(mwBlocks)cohesion(mwBlocks)# Save results in a Pajek filefile <- tempfile(fileext = ".paj")export_pajek(mwBlocks, mw, file = file)if (!interactive()) { unlink(file)}# Plot the resultsplot(mwBlocks, mw)## The science camp networkcamp <- 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)campBlocksplot(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"))Compares community structures using various metrics
Description
This function assesses the distance between two community structures.
Usage
compare( comm1, comm2, method = c("vi", "nmi", "split.join", "rand", "adjusted.rand"))Arguments
comm1 | A |
comm2 | A |
method | Character scalar, the comparison method to use. Possiblevalues: ‘vi’ is the variation of information (VI) metric of Meila(2003), ‘nmi’ is the normalized mutual information measure proposedby Danon et al. (2005), ‘split.join’ is the split-join distance ofcan Dongen (2000), ‘rand’ is the Rand index of Rand (1971),‘adjusted.rand’ is the adjusted Rand index by Hubert and Arabie(1985). |
Value
A real number.
Author(s)
Tamas Nepuszntamas@gmail.com
References
Meila M: Comparing clusterings by the variation of information.In: Scholkopf B, Warmuth MK (eds.).Learning Theory and KernelMachines: 16th Annual Conference on Computational Learning Theory and 7thKernel Workshop, COLT/Kernel 2003, Washington, DC, USA. Lecture Notes inComputer Science, vol. 2777, Springer, 2003. ISBN: 978-3-540-40720-1.
Danon L, Diaz-Guilera A, Duch J, Arenas A: Comparing community structureidentification.J Stat Mech P09008, 2005.
van Dongen S: Performance criteria for graph clustering and Markov clusterexperiments. Technical Report INS-R0012, National Research Institute forMathematics 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 ofClassification 2:193-218, 1985.
See Also
Community detectionas_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()
Examples
g <- make_graph("Zachary")sg <- cluster_spinglass(g)le <- cluster_leading_eigen(g)compare(sg, le, method = "rand")compare(membership(sg), membership(le))Complementer of a graph
Description
A complementer graph contains all edges that were not present in the inputgraph.
Usage
complementer(graph, loops = FALSE)Arguments
graph | The input graph, can be directed or undirected. |
loops | Logical constant, whether to generate loop edges. |
Details
complementer() creates the complementer of a graph. Only edgeswhich arenot present in the original graph will be included in thenew graph.
complementer() keeps graph and vertex attriubutes, edgeattributes are lost.
Value
A new graph object.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
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()
Examples
## Complementer of a ringg <- make_ring(10)complementer(g)## A graph and its complementer give together the full graphg <- make_ring(10)gc <- complementer(g)gu <- union(g, gc)guisomorphic(gu, make_full_graph(vcount(g)))Connected components of a graph
Description
Calculate the maximal (weakly or strongly) connected components of a graph
Usage
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"))Arguments
graph | The graph to analyze. |
cumulative | Logical, if TRUE the cumulative distirubution (relativefrequency) is calculated. |
mul.size | Logical. If TRUE the relative frequencies will be multipliedby the cluster sizes. |
... | Additional attributes to pass to |
mode | Character string, either “weak” or “strong”. Fordirected graphs “weak” implies weakly, “strong” stronglyconnected components to search. It is ignored for undirected graphs. |
Details
is_connected() decides whether the graph is weakly or stronglyconnected. The null graph is considered disconnected.
components() finds the maximal (weakly or strongly) connected componentsof a graph.
count_components() does almost the same ascomponents() but returns onlythe number of clusters found instead of returning the actual clusters.
component_distribution() creates a histogram for the maximal connectedcomponent sizes.
largest_component() returns the largest connected component of a graph. Fordirected graphs, optionally the largest weakly or strongly connected component.In case of a tie, the first component by vertex ID order is returned. VertexIDs 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 consecutivedepth-first searches.
Value
Foris_connected() a logical constant.
Forcomponents() 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.
Forcount_components() an integer constant is returned.
Forcomponent_distribution() a numeric vector with the relativefrequencies. The length of the vector is the size of the largest componentplus one. Note that (for currently unknown reasons) the first element of thevector is the number of clusters of size zero, so this is always zero.
Forlargest_component() the largest connected component of the graph.
Related documentation in the C library
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
decompose(),subcomponent(),groups()
Connected componentsarticulation_points(),biconnected_components(),decompose(),is_biconnected()
Other structural.properties:bfs(),connect(),constraint(),coreness(),degree(),dfs(),distance_table(),edge_density(),feedback_arc_set(),feedback_vertex_set(),girth(),is_acyclic(),is_dag(),is_matching(),k_shortest_paths(),knn(),reciprocity(),subcomponent(),subgraph(),topo_sort(),transitivity(),unfold_tree(),which_multiple(),which_mutual()
Examples
g <- sample_gnp(20, 1 / 20)clu <- components(g)groups(clu)largest_component(g)Component-wise layout
Description
This is a layout modifier function, and it can be usedto calculate the layout separately for each componentof the graph.
Usage
component_wise(merge_method = "dla")Arguments
merge_method | Merging algorithm, the |
See Also
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()
Examples
g <- make_ring(10) + make_ring(10)g %>% add_layout_(in_circle(), component_wise()) %>% plot()Compose two graphs as binary relations
Description
Relational composition of two graph.
Usage
compose(g1, g2, byname = "auto")Arguments
g1 | The first input graph. |
g2 | The second input graph. |
byname | A logical scalar, or the character scalar |
Details
compose() creates the relational composition of two graphs. Thenew graph will contain an (a,b) edge only if there is a vertex c, such thatedge (a,c) is included in the first graph and (c,b) is included in thesecond graph. The corresponding operator is%c%.
The function gives an error if one of the input graphs is directed and theother is undirected.
If thebyname argument isTRUE (orauto and the graphsare all named), then the operation is performed based on symbolic vertexnames. Otherwise numeric vertex ids are used.
compose() keeps the attributes of both graphs. All graph, vertexand edge attributes are copied to the result. If an attribute is present inmultiple graphs and would result a name clash, then this attribute isrenamed by adding suffixes: _1, _2, etc.
Thename vertex attribute is treated specially if the operation isperformed based on symbolic vertex names. In this casename must bepresent 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 andseveral 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 areupdated accordingly.
Also note that the function may generate multigraphs, if there are more thanone way to find edges (a,b) in g1 and (b,c) in g2 for an edge (a,c) in theresult. Seesimplify() if you want to get rid of the multipleedges.
The function may create loop edges, if edges (a,b) and (b,a) are present ing1 and g2, respectively, then (a,a) is included in the result. Seesimplify() if you want to get rid of the self-loops.
Value
A new graph object.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
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()
Examples
g1 <- make_ring(10)g2 <- make_star(10, mode = "undirected")gc <- compose(g1, g2)print_all(gc)print_all(simplify(gc))Neighborhood of graph vertices
Description
These functions find the vertices not farther than a given limit fromanother fixed vertex, these are called the neighborhood of the vertex.Note thatego() andneighborhood(),ego_size() andneighborhood_size(),make_ego_graph() andmake_neighborhood()_graph(),are synonyms (aliases).
Usage
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)Arguments
graph | The input graph. |
order | Integer giving the order of the neighborhood. Negative valuesindicate an infinite order. |
mode | Character constant, it specifies how to use the direction ofthe edges if a directed graph is analyzed. For ‘out’ only theoutgoing edges are followed, so all vertices reachable from the sourcevertex in at most |
nodes | The vertices for which the calculation is performed. |
mindist | The minimum distance to include the vertex in the result. |
Details
The neighborhood of a given orderr of a vertexv includes allvertices which are closer tov than the order. I.e. order 0 is alwaysv itself, order 1 isv plus its immediate neighbors, order 2is 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 givenorder, for each given vertex.
make_ego_graph()/make_neighborhood()_graph() (synonyms) is creates (sub)graphs from all neighborhoods ofthe given vertices with the given order parameter. This function preservesthe vertex, edge and graph attributes.
connect() creates a new graph by connecting each vertex toall other vertices in its neighborhood.
Value
ego_size()/neighborhood_size()returns with an integer vector.ego()/neighborhood()(synonyms) returns A list ofigraph.vsor a list of numericvectors depending on the value ofigraph_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.
Author(s)
Gabor Csardicsardi.gabor@gmail.com, the first version wasdone by Vincent Matossian
See Also
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(),feedback_vertex_set(),girth(),is_acyclic(),is_dag(),is_matching(),k_shortest_paths(),knn(),reciprocity(),subcomponent(),subgraph(),topo_sort(),transitivity(),unfold_tree(),which_multiple(),which_mutual()
Examples
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 preservedV(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 neighborhoodg <- make_ring(10)g <- connect(g, 2)Neighborhood of graph vertices
Description
connect.neighborhood() was renamed toconnect() to create a moreconsistent API.
Usage
connect.neighborhood(graph, order, mode = c("all", "out", "in", "total"))Arguments
graph | The input graph. |
order | Integer giving the order of the neighborhood. Negative valuesindicate an infinite order. |
mode | Character constant, it specifies how to use the direction ofthe edges if a directed graph is analyzed. For ‘out’ only theoutgoing edges are followed, so all vertices reachable from the sourcevertex in at most |
Create a consensus tree from several hierarchical random graph models
Description
consensus_tree() creates a consensus tree from several fittedhierarchical random graph models, using phylogeny methods. If thehrg()argument is given andstart is set toTRUE, then it startssampling from the given HRG. Otherwise it optimizes the HRG log-likelihoodfirst, and then samples starting from the optimum.
Usage
consensus_tree(graph, hrg = NULL, start = FALSE, num.samples = 10000)Arguments
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 thesupplied |
num.samples | Number of samples to use for consensus generation ormissing edge prediction. |
Value
consensus_tree() returns a list of two objects. The firstis anigraphHRGConsensus object, the second is anigraphHRG object. TheigraphHRGConsensus object has thefollowing 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 splitoccurred in the generated network samples, for each internal vertices.The order is the same as in the
parentsvector.
Related documentation in the C library
See Also
Other hierarchical random graph functions:fit_hrg(),hrg(),hrg-methods,hrg_tree(),predict_edges(),print.igraphHRG(),print.igraphHRGConsensus(),sample_hrg()
The igraph console
Description
The igraph console is a GUI window that shows what the currently runningigraph function is doing.
Usage
console()Details
The console can be started by calling theconsole() function.Then it stays open, until the user closes it.
Another way to start it to set theverbose igraph option to“tkconsole” viaigraph_options(). Then the console (re)openseach time an igraph function supporting it starts; to close it, set theverbose option to another value.
The console is written in Tcl/Tk and required thetcltk package.
Value
NULL, invisibly.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
igraph_options() and theverbose option.
Burt's constraint
Description
Given a graph,constraint() calculates Burt's constraint for eachvertex.
Usage
constraint(graph, nodes = V(graph), weights = NULL)Arguments
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 |
Details
Burt's constraint is higher if ego has less, or mutuallystronger related (i.e. more redundant) contacts. Burt's measure ofconstraint,C_i, of vertexi's ego networkV_i, is defined for directed and valued graphs,
C_i=\sum_{j \in V_i \setminus \{i\}} (p_{ij}+\sum_{q \in V_i \setminus \{i,j\}} p_{iq} p_{qj})^2
for a graph of order (i.e. number of vertices)N, whereproportional tie strengths are defined as
p_{ij} = \frac{a_{ij}+a_{ji}}{\sum_{k \in V_i \setminus \{i\}}(a_{ik}+a_{ki})},
a_{ij} are elements ofA and the latter being thegraph adjacency matrix. For isolated vertices, constraint is undefined.
Value
A numeric vector of constraint scores
Author(s)
Jeroen Bruggeman(https://sites.google.com/site/jebrug/jeroen-bruggeman-social-science)and Gabor Csardicsardi.gabor@gmail.com
References
Burt, R.S. (2004). Structural holes and good ideas.American Journal of Sociology 110, 349-399.
See Also
Other structural.properties:bfs(),component_distribution(),connect(),coreness(),degree(),dfs(),distance_table(),edge_density(),feedback_arc_set(),feedback_vertex_set(),girth(),is_acyclic(),is_dag(),is_matching(),k_shortest_paths(),knn(),reciprocity(),subcomponent(),subgraph(),topo_sort(),transitivity(),unfold_tree(),which_multiple(),which_mutual()
Examples
g <- sample_gnp(20, 5 / 20)constraint(g)Contract several vertices into a single one
Description
This function creates a new graph, by merging several vertices into one. Thevertices in the new graph correspond to sets of vertices in the input graph.
Usage
contract(graph, mapping, vertex.attr.comb = igraph_opt("vertex.attr.comb"))Arguments
graph | The input graph, it can be directed or undirected. |
mapping | A numeric vector that specifies the mapping. Its elementscorrespond to the vertices, and for each element the id in the new graph isgiven. |
vertex.attr.comb | Specifies how to combine the vertex attributes inthe new graph. Please see |
Details
The attributes of the graph are kept. Graph and edge attributes areunchanged, vertex attributes are combined, according to thevertex.attr.comb parameter.
Value
A new graph object.
Related documentation in the C library
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
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()
Examples
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)Contract several vertices into a single one
Description
contract.vertices() was renamed tocontract() to create a moreconsistent API.
Usage
contract.vertices( graph, mapping, vertex.attr.comb = igraph_opt("vertex.attr.comb"))Arguments
graph | The input graph, it can be directed or undirected. |
mapping | A numeric vector that specifies the mapping. Its elementscorrespond to the vertices, and for each element the id in the new graph isgiven. |
vertex.attr.comb | Specifies how to combine the vertex attributes inthe new graph. Please see |
Convex hull of a set of vertices
Description
convex.hull() was renamed toconvex_hull() to create a moreconsistent API.
Usage
convex.hull(data)Arguments
data | The data points, a numeric matrix with two columns. |
Convex hull of a set of vertices
Description
Calculate the convex hull of a set of points, i.e. the covering polygon thathas the smallest area.
Usage
convex_hull(data)Arguments
data | The data points, a numeric matrix with two columns. |
Value
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.
Related documentation in the C library
Author(s)
Tamas Nepuszntamas@gmail.com
References
Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, andClifford Stein. Introduction to Algorithms, Second Edition. MIT Press andMcGraw-Hill, 2001. ISBN 0262032937. Pages 949-955 of section 33.3: Findingthe convex hull.
See Also
Other other:running_mean(),sample_seq()
Examples
M <- cbind(runif(100), runif(100))convex_hull(M)K-core decomposition of graphs
Description
The k-core of graph is a maximal subgraph in which each vertex has at leastdegree k. The coreness of a vertex is k if it belongs to the k-core but notto the (k+1)-core.
Usage
coreness(graph, mode = c("all", "out", "in"))Arguments
graph | The input graph, it can be directed or undirected |
mode | The type of the core in directed graphs. Character constant,possible values: |
Details
The k-core of a graph is the maximal subgraph in which every vertex has atleast degree k. The cores of a graph form layers: the (k+1)-core is always asubgraph of the k-core.
This function calculates the coreness for each vertex.
Value
Numeric vector of integer numbers giving the coreness of eachvertex.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
Vladimir Batagelj, Matjaz Zaversnik: An O(m) Algorithm for CoresDecomposition of Networks, 2002
Seidman S. B. (1983) Network structure and minimum degree,SocialNetworks, 5, 269–287.
See Also
Other structural.properties:bfs(),component_distribution(),connect(),constraint(),degree(),dfs(),distance_table(),edge_density(),feedback_arc_set(),feedback_vertex_set(),girth(),is_acyclic(),is_dag(),is_matching(),k_shortest_paths(),knn(),reciprocity(),subcomponent(),subgraph(),topo_sort(),transitivity(),unfold_tree(),which_multiple(),which_mutual()
Examples
g <- make_ring(10)g <- add_edges(g, c(1, 2, 2, 3, 1, 3))coreness(g) # small core triangle in a ringFind the multiple or loop edges in a graph
Description
count.multiple() was renamed tocount_multiple() to create a moreconsistent API.
Usage
count.multiple(graph, eids = E(graph))Arguments
graph | The input graph. |
eids | The edges to which the query is restricted. By default this isall edges in the graph. |
Number of automorphisms
Description
Calculate the number of automorphisms of a graph, i.e. the number ofisomorphisms to itself.
Usage
count_automorphisms( graph, colors = NULL, sh = c("fm", "f", "fs", "fl", "flm", "fsm"))Arguments
graph | The input graph, it is treated as undirected. |
colors | The colors of the individual vertices of the graph; onlyvertices having the same color are allowed to match each other in anautomorphism. When omitted, igraph uses the |
sh | The splitting heuristics for the BLISS algorithm. Possible valuesare:‘ |
Details
An automorphism of a graph is a permutation of its vertices which brings thegraph into itself.
This function calculates the number of automorphism of a graph using theBLISS algorithm. See also the BLISS homepage athttp://www.tcs.hut.fi/Software/bliss/index.html. If you need theautomorphisms themselves, useautomorphism_group() to obtaina compact representation of the automorphism group.
Value
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.
Related documentation in the C library
Author(s)
Tommi Junttila (https://users.ics.aalto.fi/tjunttil/) for BLISSand Gabor Csardicsardi.gabor@gmail.com for the igraph glue codeand this manual page.
References
Tommi Junttila and Petteri Kaski: Engineering an EfficientCanonical Labeling Tool for Large and Sparse Graphs,Proceedings ofthe Ninth Workshop on Algorithm Engineering and Experiments and the FourthWorkshop on Analytic Algorithms and Combinatorics. 2007.
See Also
canonical_permutation(),permute(),andautomorphism_group() for a compact representation of allautomorphisms
Other graph automorphism:automorphism_group()
Examples
## 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 automorphismsg <- make_full_graph(4)count_automorphisms(g, colors = c(1, 2, 1, 2))Count the number of isomorphic mappings between two graphs
Description
Count the number of isomorphic mappings between two graphs
Usage
count_isomorphisms(graph1, graph2, method = "vf2", ...)Arguments
graph1 | The first graph. |
graph2 | The second graph. |
method | Currently only ‘vf2’ is supported, see |
... | Passed to the individual methods. |
Value
Number of isomorphic mappings between the two graphs.
References
LP Cordella, P Foggia, C Sansone, and M Vento: An improved algorithmfor matching large graphs,Proc. of the 3rd IAPR TC-15 Workshopon Graphbased Representations in Pattern Recognition, 149–159, 2001.
See Also
Other graph isomorphism:canonical_permutation(),count_subgraph_isomorphisms(),graph_from_isomorphism_class(),isomorphic(),isomorphism_class(),isomorphisms(),subgraph_isomorphic(),subgraph_isomorphisms()
Examples
# colored graph isomorphismg1 <- 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 defaultcount_isomorphisms(g1, g2)# ignore colorscount_isomorphisms(g1, g2, vertex.color1 = NULL, vertex.color2 = NULL)Graph motifs
Description
Graph motifs are small connected induced subgraphs with a well-definedstructure. These functions search a graph for various motifs.
Usage
count_motifs(graph, size = 3, cut.prob = NULL)Arguments
graph | Graph object, the input graph. |
size | The size of the motif. |
cut.prob | Numeric vector giving the probabilities that the searchgraph is cut at a certain level. Its length should be the same as the sizeof the motif (the |
Details
count_motifs() calculates the total number of motifs of a givensize in graph.
Value
count_motifs() returns a numeric scalar.
See Also
Other graph motifs:dyad_census(),motifs(),sample_motifs()
Examples
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 ofanother graph
Description
Count the isomorphic mappings between a graph and the subgraphs ofanother graph
Usage
count_subgraph_isomorphisms(pattern, target, method = c("lad", "vf2"), ...)Arguments
pattern | The smaller graph, it might be directed orundirected. Undirected graphs are treated as directed graphs withmutual edges. |
target | The bigger graph, it might be directed orundirected. Undirected graphs are treated as directed graphs withmutual edges. |
method | The method to use. Possible values:‘lad’, ‘vf2’. See their details below. |
... | Additional arguments, passed to the various methods. |
Value
Logical scalar,TRUE if thepattern isisomorphic to a (possibly induced) subgraph oftarget.
‘lad’ method
This is the LAD algorithm by Solnon, see the reference below. It hasthe following extra arguments:
- domains
If not
NULL, then it specifies matching restrictions.It must be a list oftargetvertex sets, given as numeric vertex ids or symbolic vertex names.The length of the list must bevcount(pattern)and for each vertex inpatternit gives the allowed matching vertices intarget.Defaults toNULL.- induced
Logical scalar, whether to search for an induced subgraph. It is
FALSEby default.- time.limit
The processor time limit for the computation, in seconds. It defaults to
Inf, which means no limit.
‘vf2’ method
This method uses the VF2 algorithm by Cordella, Foggia et al., seereferences below. It supports vertex and edge colors and have thefollowing extra arguments:
- vertex.color1, vertex.color2
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
NULLfor both of these arguments.See also examples below.- edge.color1, edge.color2
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
NULLfor both of these arguments.
References
LP Cordella, P Foggia, C Sansone, and M Vento: An improved algorithmfor matching large graphs,Proc. of the 3rd IAPR TC-15 Workshopon Graphbased Representations in Pattern Recognition, 149–159, 2001.
C. Solnon: AllDifferent-based Filtering for Subgraph Isomorphism,Artificial Intelligence 174(12-13):850–864, 2010.
See Also
Other graph isomorphism:canonical_permutation(),count_isomorphisms(),graph_from_isomorphism_class(),isomorphic(),isomorphism_class(),isomorphisms(),subgraph_isomorphic(),subgraph_isomorphisms()
Creates a communities object.
Description
create.communities() was renamed tomake_clusters() to create a moreconsistent API.
Usage
create.communities( graph, membership = NULL, algorithm = NULL, merges = NULL, modularity = TRUE)Arguments
graph | The graph of the community structure. |
membership | The membership vector of the community structure, anumeric vector denoting the id of the community for each vertex. Itmight be |
algorithm | Character string, the algorithm that generatedthe community structure, it can be arbitrary. |
merges | A merge matrix, for hierarchical community structures (or |
modularity | Modularity value of the community structure. If thisis |
Optimal edge curvature when plotting graphs
Description
If graphs have multiple edges, then drawing them as straight lines does notshow them when plotting the graphs; they will be on top of each other. Onesolution is to bend the edges, with diffenent curvature, so that all of themare visible.
Usage
curve_multiple(graph, start = 0.5)Arguments
graph | The input graph. |
start | The curvature at the two extreme edges. All edges will have acurvature between |
Details
curve_multiple() calculates the optimaledge.curved vector forplotting a graph with multiple edges, so that all edges are visible.
Value
A numeric vector, its length is the number of edges in the graph.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
igraph.plotting for all plotting parameters,plot.igraph(),tkplot() andrglplot()for plotting functions.
Examples
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)Functions to deal with the result of network community detection
Description
cutat() was renamed tocut_at() to create a moreconsistent API.
Usage
cutat(communities, no, steps)Arguments
no | Integer scalar, the desired number of communities. If too low ortwo high, then an error message is given. Exactly one of |
steps | The number of merge operations to perform to produce thecommunities. Exactly one of |
Decompose a graph into components
Description
Creates a separate graph for each connected component of a graph.
Usage
decompose(graph, mode = c("weak", "strong"), max.comps = NA, min.vertices = 0)Arguments
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 shouldcontain in order to place it in the result list. E.g. supply 2 here to ignoreisolate vertices. |
Value
A list of graph objects.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
is_connected() to decide whether a graph is connected,components() to calculate the connected components of a graph.
Connected componentsarticulation_points(),biconnected_components(),component_distribution(),is_biconnected()
Examples
# the diameter of each component in a random graphg <- sample_gnp(1000, 1 / 1000)components <- decompose(g, min.vertices = 2)sapply(components, diameter)Decompose a graph into components
Description
decompose.graph() was renamed todecompose() to create a moreconsistent API.
Usage
decompose.graph( graph, mode = c("weak", "strong"), max.comps = NA, min.vertices = 0)Arguments
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 shouldcontain in order to place it in the result list. E.g. supply 2 here to ignoreisolate vertices. |
Degree and degree distribution of the vertices
Description
The degree of a vertex is its most basic structural property, the number ofits adjacent edges.
Usage
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, ...)Arguments
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” forin-degree or “total” for the sum of the two. For undirected graphsthis 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 tobe calculated. |
Value
Fordegree() a numeric vector of the same length as argumentv.
Fordegree_distribution() a numeric vector of the same length as themaximum degree plus one. The first element is the relative frequency zerodegree vertices, the second vertices with degree one, etc.
Formax_degree(), the largest degree in the graph. When no vertices areselected, or when the input is the null graph, zero is returned as thisis the smallest possible degree.
Related documentation in the C library
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
Other structural.properties:bfs(),component_distribution(),connect(),constraint(),coreness(),dfs(),distance_table(),edge_density(),feedback_arc_set(),feedback_vertex_set(),girth(),is_acyclic(),is_dag(),is_matching(),k_shortest_paths(),knn(),reciprocity(),subcomponent(),subgraph(),topo_sort(),transitivity(),unfold_tree(),which_multiple(),which_mutual()
Examples
g <- make_ring(10)degree(g)g2 <- sample_gnp(1000, 10 / 1000)max_degree(g2)degree_distribution(g2)Degree and degree distribution of the vertices
Description
degree.distribution() was renamed todegree_distribution() to create a moreconsistent API.
Usage
degree.distribution(graph, cumulative = FALSE, ...)Arguments
graph | The graph to analyze. |
cumulative | Logical; whether the cumulative degree distribution is tobe calculated. |
... | These dots are for future extensions and must be empty. |
Generate random graphs with a given degree sequence
Description
degree.sequence.game() was renamed tosample_degseq() to create a moreconsistent API.
Usage
degree.sequence.game( out.deg, in.deg = NULL, method = c("simple", "vl", "simple.no.multiple", "simple.no.multiple.uniform"))Arguments
out.deg | Numeric vector, the sequence of degrees (for undirectedgraphs) or out-degrees (for directed graphs). For undirected graphs its sumshould 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. |
Delete edges from a graph
Description
delete.edges() was renamed todelete_edges() to create a moreconsistent API.
Usage
delete.edges(graph, edges)Arguments
graph | The input graph. |
edges | The edges to remove, specified as an edge sequence. Typicallythis is either a numeric vector containing edge IDs, or a character vectorcontaining the IDs or names of the source and target vertices, separated by |
Delete vertices from a graph
Description
delete.vertices() was renamed todelete_vertices() to create a moreconsistent API.
Usage
delete.vertices(graph, v)Arguments
graph | The input graph. |
v | The vertices to remove, a vertex sequence. |
Delete an edge attribute
Description
Delete an edge attribute
Usage
delete_edge_attr(graph, name)Arguments
graph | The graph |
name | The name of the edge attribute to delete. |
Value
The graph, with the specified edge attribute removed.
See Also
Vertex, edge and graph attributesdelete_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(),set_vertex_attrs(),vertex_attr(),vertex_attr<-(),vertex_attr_names()
Examples
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
Description
Delete edges from a graph
Usage
delete_edges(graph, edges)Arguments
graph | The input graph. |
edges | The edges to remove, specified as an edge sequence. Typicallythis is either a numeric vector containing edge IDs, or a character vectorcontaining the IDs or names of the source and target vertices, separated by |
Value
The graph, with the edges removed.
See Also
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()
Examples
g <- make_ring(10) %>% delete_edges(seq(1, 9, by = 2))gg <- make_ring(10) %>% delete_edges("10|1")gg <- make_ring(5)g <- delete_edges(g, get_edge_ids(g, c(1, 5, 4, 5)))gDelete a graph attribute
Description
Delete a graph attribute
Usage
delete_graph_attr(graph, name)Arguments
graph | The graph. |
name | Name of the attribute to delete. |
Value
The graph, with the specified attribute removed.
See Also
Vertex, edge and graph attributesdelete_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(),set_vertex_attrs(),vertex_attr(),vertex_attr<-(),vertex_attr_names()
Examples
g <- make_ring(10)graph_attr_names(g)g2 <- delete_graph_attr(g, "name")graph_attr_names(g2)Delete a vertex attribute
Description
Delete a vertex attribute
Usage
delete_vertex_attr(graph, name)Arguments
graph | The graph |
name | The name of the vertex attribute to delete. |
Value
The graph, with the specified vertex attribute removed.
See Also
Vertex, edge and graph attributesdelete_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(),set_vertex_attrs(),vertex_attr(),vertex_attr<-(),vertex_attr_names()
Examples
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
Description
Delete vertices from a graph
Usage
delete_vertices(graph, v)Arguments
graph | The input graph. |
v | The vertices to remove, a vertex sequence. |
Value
The graph, with the vertices removed.
See Also
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()
Examples
g <- make_ring(10) %>% set_vertex_attr("name", value = LETTERS[1:10])gV(g)g2 <- delete_vertices(g, c(1, 5)) %>% delete_vertices("B")g2V(g2)Community structure dendrogram plots
Description
dendPlot() was renamed toplot_dendrogram() to create a moreconsistent API.
Usage
dendPlot(x, mode = igraph_opt("dend.plot.type"), ...)Arguments
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 plottingfunction. |
Depth-first search
Description
Depth-first search is an algorithm to traverse a graph. It starts from aroot vertex and tries to go quickly as far from as possible.
Usage
dfs( graph, root, mode = c("out", "in", "all", "total"), ..., unreachable = TRUE, order = TRUE, order.out = FALSE, parent = FALSE, dist = FALSE, in.callback = NULL, out.callback = NULL, extra = NULL, rho = parent.frame(), neimode = deprecated(), father = deprecated())Arguments
Details
The callback functions must have the following arguments:
- graph
The input graph is passed to the callback function here.
- data
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.
- extra
The extra argument.
The callback must return FALSE to continue the search or TRUEto terminate it. See examples below on how to use the callback functions.
Value
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
modeargument of the function call.Note that for undirected graphs this is always ‘all’, irrespectively of the supplied value.- 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.
- parent
Numeric vector. The parent of each vertex, i.e. the vertex it was discovered from.
- father
Like parent, kept for compatibility for now.
- dist
Numeric vector, for each vertex its distance from the root of the search tree.
Note thatorder,order.out,parent, anddistmight beNULL if their corresponding argument isFALSE, i.e.if their calculation is not requested.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
bfs() for breadth-first search.
Other structural.properties:bfs(),component_distribution(),connect(),constraint(),coreness(),degree(),distance_table(),edge_density(),feedback_arc_set(),feedback_vertex_set(),girth(),is_acyclic(),is_dag(),is_matching(),k_shortest_paths(),knn(),reciprocity(),subcomponent(),subgraph(),topo_sort(),transitivity(),unfold_tree(),which_multiple(),which_mutual()
Examples
## A graph with two separate treesdfs( graph = make_tree(10) %du% make_tree(10), root = 1, mode = "out", unreachable = TRUE, order = TRUE, order.out = TRUE, parent = TRUE)## How to use a callbackf.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( graph = make_tree(10), root = 1, mode = "out", in.callback = f.in, out.callback = f.out)## Terminate after the first component, using a callbackf.out <- function(graph, data, extra) { data["vid"] == 1}tmp <- dfs( graph = make_tree(10) %du% make_tree(10), root = 1, out.callback = f.out)Diameter of a graph
Description
The diameter of a graph is the length of the longest geodesic.
Usage
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)Arguments
graph | The graph to analyze. |
directed | Logical, whether directed or undirected paths are to beconsidered. This is ignored for undirected graphs. |
unconnected | Logical, what to do if the graph is unconnected. IfFALSE, the function will return a number that is one larger the largestpossible diameter, which is always the number of vertices. If TRUE, thediameters of the connected components will be calculated and the largest onewill be returned. |
weights | Optional positive weight vector for calculating weighteddistances. If the graph has a |
Details
The diameter is calculated by using a breadth-first search like method.
get_diameter() returns a path with the actual diameter. If there aremany shortest paths of the length of the diameter, then it returns the firstone found.
farthest_vertices() returns two vertex ids, the vertices which areconnected by the diameter path.
Value
A numeric constant fordiameter(), a numeric vector forget_diameter().farthest_vertices() returns a list with twoentries:
verticesThe two vertices that are the farthest.
distanceTheir distance.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
Other paths:all_simple_paths(),distance_table(),eccentricity(),graph_center(),radius()
Examples
g <- make_ring(10)g2 <- delete_edges(g, c(1, 2, 1, 10))diameter(g2, unconnected = TRUE)diameter(g2, unconnected = FALSE)## Weighted diameterset.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)Difference of two sets
Description
This is an S3 generic function. Seemethods("difference")for the actual implementations for various S3 classes. Initiallyit is implemented for igraph graphs (difference of edges in two graphs),and igraph vertex and edge sequences. Seedifference.igraph(), anddifference.igraph.vs().
Usage
difference(...)Arguments
... | Arguments, their number and interpretation depends onthe function that implements |
Value
Depends on the function that implements this method.
See Also
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()
Difference of graphs
Description
The difference of two graphs are created.
Usage
## S3 method for class 'igraph'difference(big, small, byname = "auto", ...)Arguments
big | The left hand side argument of the minus operator. A directed orundirected graph. |
small | The right hand side argument of the minus operator. A directedot undirected graph. |
byname | A logical scalar, or the character scalar |
... | Ignored, included for S3 compatibility. |
Details
difference() creates the difference of two graphs. Only edgespresent in the first graph but not in the second will be be included in thenew graph. The corresponding operator is%m%.
If thebyname argument isTRUE (orauto and the graphsare all named), then the operation is performed based on symbolic vertexnames. Otherwise numeric vertex ids are used.
difference() keeps all attributes (graph, vertex and edge) of thefirst graph.
Note thatbig andsmall must both be directed or both beundirected, otherwise an error message is given.
Value
A new graph object.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
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()
Examples
## Create a wheel graphwheel <- union( make_ring(10), make_star(11, center = 11, mode = "undirected"))V(wheel)$name <- letters[seq_len(vcount(wheel))]## Subtract a star graph from itsstar <- make_star(6, center = 6, mode = "undirected")V(sstar)$name <- letters[c(1, 3, 5, 7, 9, 11)]G <- wheel %m% sstarprint_all(G)plot(G, layout = layout_nicely(wheel))Difference of edge sequences
Description
Difference of edge sequences
Usage
## S3 method for class 'igraph.es'difference(big, small, ...)Arguments
big | The ‘big’ edge sequence. |
small | The ‘small’ edge sequence. |
... | Ignored, included for S3 signature compatibility. |
Details
They must belong to the same graph. Note that this function has‘set’ semantics and the multiplicity of edges is lost in theresult.
Value
An edge sequence that contains only edges that are part ofbig, but not part ofsmall.
See Also
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()
Examples
g <- make_(ring(10), with_vertex_(name = LETTERS[1:10]))difference(V(g), V(g)[6:10])Difference of vertex sequences
Description
Difference of vertex sequences
Usage
## S3 method for class 'igraph.vs'difference(big, small, ...)Arguments
big | The ‘big’ vertex sequence. |
small | The ‘small’ vertex sequence. |
... | Ignored, included for S3 signature compatibility. |
Details
They must belong to the same graph. Note that this function has‘set’ semantics and the multiplicity of vertices is lost in theresult.
Value
A vertex sequence that contains only vertices that are part ofbig, but not part ofsmall.
See Also
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()
Examples
g <- make_(ring(10), with_vertex_(name = LETTERS[1:10]))difference(V(g), V(g)[6:10])Dimensionality selection for singular values using profile likelihood.
Description
Select the number of significant singular values, by finding the‘elbow’ of the scree plot, in a principled way.
Usage
dim_select(sv)Arguments
sv | A numeric vector, the ordered singular values. |
Details
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 adjacencymatrix. The singular values are assumed to be generated from a Gaussianmixture distribution with two components that have different means and samevariance. The dimensionalityd is chosen to maximize the likelihoodwhen thed largest singular values are assigned to one component ofthe mixture and the rest of the singular values assigned to the othercomponent.
This function can also be used for the general separation problem, where weassume that the left and the right of the vector are coming from two Normaldistributions, with different means, and we want to know their border. Seeexamples below.
Value
A numeric scalar, the estimate ofd.
Related documentation in the C library
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
M. Zhu, and A. Ghodsi (2006). Automatic dimensionality selectionfrom the scree plot via the use of profile likelihood.ComputationalStatistics and Data Analysis, Vol. 51, 918–930.
See Also
Other embedding:embed_adjacency_matrix(),embed_laplacian_matrix()
Examples
# Generate the two groups of singular values with# Gaussian mixture of two components that have different meanssing.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 lengthlpvs <- 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 distributionlpvs.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)Disjoint union of graphs
Description
The union of two or more graphs are created. The graphs are assumed to havedisjoint vertex sets.
Usage
disjoint_union(...)x %du% yArguments
... | Graph objects or lists of graph objects. |
x,y | Graph objects. |
Details
disjoint_union() creates a union of two or more disjoint graphs.Thus first the vertices in the second, third, etc. graphs are relabeled tohave completely disjoint graphs. Then a simple union is created. Thisfunction can also be used via the%du% operator.
disjoint_union() handles graph, vertex and edge attributes. Inparticular, it merges vertex and edge attributes using thevctrs::vec_c()function. For graphs that lack some vertex/edge attribute, the correspondingvalues in the new graph are set to a missing value (NA for scalar attributes,NULL for list attributes). Graph attributes are simplycopied to the result. If this would result a name clash, then they arerenamed by adding suffixes: _1, _2, etc.
Note that if both graphs have vertex names (i.e. aname vertexattribute), then the concatenated vertex names might be non-unique in theresult. A warning is given if this happens.
An error is generated if some input graphs are directed and others areundirected.
Value
A new graph object.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
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()
Examples
## A star and a ringg1 <- 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)Shortest (directed or undirected) paths between vertices
Description
distances() calculates the length of all the shortest paths fromor to the vertices in the network.shortest_paths() calculates oneshortest path (the path itself, and not just its length) from or to thegiven vertex.
Usage
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)Arguments
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 (notstrongly connected if directed paths are considered). If TRUE, onlythe lengths of the existing paths are considered and averaged; ifFALSE, the length of the missing paths are considered as having infinitelength, 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 becalculated. |
to | Numeric vector, the vertices to which the shortest paths will becalculated. By default it includes all vertices. Note that for |
mode | Character constant, gives whether the shortest paths to or fromthe given vertices should be calculated for directed graphs. If |
algorithm | Which algorithm to use for the calculation. By defaultigraph tries to select the fastest suitable algorithm. If there are noweights, then an unweighted breadth-first search is used, otherwise if allweights are positive, then Dijkstra's algorithm is used. If there arenegative weights and we do the calculation for more than 100 sources, thenJohnson's algorithm is used. Otherwise the Bellman-Ford algorithm is used.You can override igraph's choice by explicitly giving this parameter. Notethat 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 beused, regardless of this argument. |
from | Numeric constant, the vertex from or to the shortest paths willbe calculated. Note that right now this is not a vector of vertex ids, butonly a single vertex. |
output | Character scalar, defines how to report the shortest paths.“vpath” means that the vertices along the paths are reported, thisform was used prior to igraph version 0.6. “epath” means that theedges along the paths are reported. “both” means that both forms arereturned, in a named list with components “vpath” and “epath”. |
predecessors | Logical scalar, whether to return the predecessor vertexfor each vertex. The predecessor of vertex |
inbound.edges | Logical scalar, whether to return the inbound edge foreach vertex. The inbound edge of vertex |
Details
The shortest path, or geodesic between two pair of vertices is a path withthe minimal number of vertices. The functions documented in this manual pageall calculate shortest paths between vertex pairs.
distances() calculates the lengths of pairwise shortest paths froma set of vertices (from) to another set of vertices (to). Ituses different algorithms, depending on thealgorithm argument andtheweight edge attribute of the graph. The implemented algorithmsare breadth-first search (‘unweighted’), this only works forunweighted graphs; the Dijkstra algorithm (‘dijkstra’), thisworks 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 algorithmwith expected quadratic running time (‘floyd-warshall’). The latterthree algorithms work with arbitraryedge weights, but (naturally) only for graphs that don't have a negativecycle. Note that a negative-weight edge in an undirected graph impliessuch a cycle. Johnson's algorithm performs better than the Bellman-Fordone when many source (and target) vertices are given, with all-pairsshortest path length calculations being the typical use case.
igraph can choose automatically between algorithms, and chooses the mostefficient one that is appropriate for the supplied weights (if any). Forautomatic algorithm selection, supply ‘automatic’ as thealgorithm argument. (This is also the default.)
shortest_paths() calculates a single shortest path (i.e. the pathitself, not just its length) between the source vertex given infrom,to the target vertices given into.shortest_paths() usesbreadth-first search for unweighted graphs and Dijkstra's algorithm forweighted graphs. The latter only works if the edge weights are non-negative.
all_shortest_paths() calculatesall shortest paths betweenpairs of vertices, including several shortest paths of the same length.More precisely, it computerd all shortest path starting atfrom, andending at any vertex given into. It uses a breadth-first search forunweighted graphs and Dijkstra's algorithm for weighted ones. The latteronly supports non-negative edge weights. Caution: in multigraphs, theresult size is exponentially large in the number of vertex pairs withmultiple edges between them.
mean_distance() calculates the average path length in a graph, bycalculating the shortest paths between all pairs of vertices (both ways fordirected graphs). It uses a breadth-first search for unweighted graphs andDijkstra's algorithm for weighted ones. The latter only supports non-negativeedge weights.
distance_table() calculates a histogram, by calculating the shortestpath length between each pair of vertices. For directed graphs bothdirections are considered, so every pair of vertices appears twice in thehistogram.
Value
Fordistances() a numeric matrix withlength(to)columns andlength(v) rows. The shortest path length from a vertex toitself is always zero. For unreachable verticesInf is included.
Forshortest_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, thepredecessor of each vertex in the |
inbound_edges | Numeric vector, the inbound edgefor each vertex, or |
Forall_shortest_paths() a list is returned:
- vpaths
This is a list.Each list element contains the vertices of a shortest path from
fromto a vertex into.The shortest paths to the same vertex are collected into consecutive elements of the list.- epaths
This is a list similar to vpaths, but the vectors of the listcontain the edge ids along the shortest paths, instead of the vertex ids.
- nrgeo
A vector in which each element is the number of shortest paths (geodesics)from
fromto the corresponding vertex into.- res
Deprecated
Formean_distance() a single number is returned ifdetails=FALSE,or a named list with two entries:
resthe mean distance as a numeric scalar
unconnectedthe number of unconnected vertex pairs, also as a numeric scalar.
distance_table() returns a named list with two entries:
resa numeric vector, the histogram of distances
unconnecteda 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
n(n-1)for directed graphsandn(n-1)/2for undirected graphs.
Related documentation in the C library
path_length_hist(),average_path_length_dijkstra().
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
West, D.B. (1996).Introduction to Graph Theory. UpperSaddle River, N.J.: Prentice Hall.
See Also
Other structural.properties:bfs(),component_distribution(),connect(),constraint(),coreness(),degree(),dfs(),edge_density(),feedback_arc_set(),feedback_vertex_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()
Examples
g <- make_ring(10)distances(g)shortest_paths(g, 5)all_shortest_paths(g, 1, 6:8)mean_distance(g)## Weighted shortest pathsel <- 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")Diverging palette
Description
This is the ‘PuOr’ palette fromhttps://colorbrewer2.org/.It has at most eleven colors.
Usage
diverging_pal(n)Arguments
n | The number of colors in the palette. The maximum is elevencurrently. |
Details
This is similar tosequential_pal(), but it also putsemphasis on the mid-range values, plus the the two extreme ends.Use this palette, if you have such a quantity to mark with vertexcolors.
Value
A character vector of RGB color codes.
See Also
Other palettes:categorical_pal(),r_pal(),sequential_pal()
Examples
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)Graph diversity
Description
Calculates a measure of diversity for all vertices.
Usage
diversity(graph, weights = NULL, vids = V(graph))Arguments
graph | The input graph. Edge directions are ignored. |
weights |
|
vids | The vertex ids for which to calculate the measure. |
Details
The diversity of a vertex is defined as the (scaled) Shannon entropy of theweights of its incident edges:
D(i)=\frac{H(i)}{\log k_i}
and
H(i)=-\sum_{j=1}^{k_i} p_{ij}\log p_{ij},
where
p_{ij}=\frac{w_{ij}}{\sum_{l=1}^{k_i}}V_{il},
andk_i is the (total) degree of vertexi,w_{ij} is the weight of the edge(s) between verticesi andj.
For vertices with degree less than two the function returnsNaN.
Value
A numeric vector, its length is the number of vertices.
Related documentation in the C library
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
Nathan Eagle, Michael Macy and Rob Claxton: Network Diversityand Economic Development,Science328, 1029–1031, 2010.
See Also
Centrality measuresalpha_centrality(),authority_score(),betweenness(),closeness(),eigen_centrality(),harmonic_centrality(),hits_scores(),page_rank(),power_centrality(),spectrum(),strength(),subgraph_centrality()
Examples
g1 <- sample_gnp(20, 2 / 20)g2 <- sample_gnp(20, 2 / 20)g3 <- sample_gnp(20, 5 / 20)E(g1)$weight <- 1E(g2)$weight <- runif(ecount(g2))E(g3)$weight <- runif(ecount(g3))diversity(g1)diversity(g2)diversity(g3)Dominator tree
Description
dominator.tree() was renamed todominator_tree() to create a moreconsistent API.
Usage
dominator.tree(graph, root, mode = c("out", "in", "all", "total"))Arguments
graph | A directed graph. If it is not a flowgraph, and it containssome vertices not reachable from the root vertex, then these vertices willbe collected and returned as part of the result. |
root | The id of the root (or source) vertex, this will be the root ofthe tree. |
mode | Constant, must be ‘ |
Dominator tree
Description
Dominator tree of a directed graph.
Usage
dominator_tree(graph, root, mode = c("out", "in", "all", "total"))Arguments
graph | A directed graph. If it is not a flowgraph, and it containssome vertices not reachable from the root vertex, then these vertices willbe collected and returned as part of the result. |
root | The id of the root (or source) vertex, this will be the root ofthe tree. |
mode | Constant, must be ‘ |
Details
A flowgraph is a directed graph with a distinguished start (or root) vertexr, such that for any vertexv, there is a path fromr tov. A vertexv dominates another vertexw (not equal tov), if every path fromr tow containsv. Vertexv is the immediate dominator orw,v=\textrm{idom}(w), ifv dominatesw and everyother dominator ofw dominatesv. The edges{(\textrm{idom}(w), w)| w \ne r} form adirected tree, rooted atr, called the dominator tree of the graph.Vertexv dominates vertexw if and only ifv is anancestor ofw in the dominator tree.
This function implements the Lengauer-Tarjan algorithm to construct thedominator tree of a directed graph. For details see the reference below.
Value
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
NaN.For the root vertex itself it contains minus one.- 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.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
Thomas Lengauer, Robert Endre Tarjan: A fast algorithm forfinding dominators in a flowgraph,ACM Transactions on ProgrammingLanguages and Systems (TOPLAS) I/1, 121–141, 1979.
See Also
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()
Examples
## The example from the paperg <- 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 pronouns
Description
The.data and.env pronouns make it explicit where to look up attributenames when indexingV(g) orE(g), i.e. the vertex or edge sequence of agraph. These pronouns are inspired by.data and.env inrlang - thanksto Michał Bojanowski for bringing these to our attention.
The rules are simple:
.dataretrieves attributes from the graph whose vertex or edge sequenceis being evaluated..envretrieves variables from the calling environment.
Note that.data and.env are injected dynamically into the environmentwhere the indexing expressions are evaluated; you cannot get access to theseobjects outside the context of an indexing expression. To avoid warningsprinted byR CMD check when code containing.data and.env is checked,you can import.data and.env fromigraph if needed. Alternatively,you can declare them explicitly withutils::globalVariables() to silencethe warnings.
Dyad census of a graph
Description
dyad.census() was renamed todyad_census() to create a moreconsistent API.
Usage
dyad.census(graph)Arguments
graph | The input graph. A warning is given if it is not directed. |
Dyad census of a graph
Description
Classify dyads in a directed graphs. The relationship between each pair ofvertices is measured. It can be in three states: mutual, asymmetric ornon-existent.
Usage
dyad_census(graph)Arguments
graph | The input graph. A warning is given if it is not directed. |
Value
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.
Related documentation in the C library
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
Holland, P.W. and Leinhardt, S. A Method for Detecting Structurein Sociometric Data.American Journal of Sociology, 76, 492–513.1970.
Wasserman, S., and Faust, K.Social Network Analysis: Methods andApplications. Cambridge: Cambridge University Press. 1994.
See Also
triad_census() for the same classification, but withtriples.
Other graph motifs:count_motifs(),motifs(),sample_motifs()
Examples
g <- sample_pa(100)dyad_census(g)Rewires the endpoints of the edges of a graph to a random vertex
Description
This function can be used together withrewire().This method rewires the endpoints of the edges with a constant probabilityuniformly randomly to a new vertex in a graph.
Usage
each_edge( prob, loops = FALSE, multiple = FALSE, mode = c("all", "out", "in", "total"))Arguments
prob | The rewiring probability, a real number between zero and one. |
loops | Logical scalar, whether loop edges are allowed in the rewiredgraph. |
multiple | Logical scalar, whether multiple edges are allowed in thegenerated graph. |
mode | Character string, specifies which endpoint of the edges to rewirein directed graphs. ‘all’ rewires both endpoints, ‘in’ rewiresthe start (tail) of each directed edge, ‘out’ rewires the end (head)of each directed edge. Ignored for undirected graphs. |
Details
Note that this method might create graphs with multiple and/or loop edges.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
Other rewiring functions:keeping_degseq(),rewire()
Examples
# Some random shortcuts shorten the distances on a latticeg <- 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 distributiong <- sample_pa(1000)g2 <- g %>% rewire(each_edge(mode = "in", multiple = TRUE, prob = 0.2))degree(g, mode = "in") == degree(g2, mode = "in")Eccentricity of the vertices in a graph
Description
The eccentricity of a vertex is its shortest path distance from the farthestother node in the graph.
Usage
eccentricity( graph, vids = V(graph), ..., weights = NULL, mode = c("all", "out", "in", "total"))Arguments
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 fromthe given vertices should be calculated for directed graphs. If |
Details
The eccentricity of a vertex is calculated by measuring the shortestdistance 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.
Value
eccentricity() returns a numeric vector, containing theeccentricity score of each given vertex.
Related documentation in the C library
References
Harary, F. Graph Theory. Reading, MA: Addison-Wesley, p. 35,1994.
See Also
radius() for a related concept,distances() for general shortest path calculations.
Other paths:all_simple_paths(),diameter(),distance_table(),graph_center(),radius()
Examples
g <- make_star(10, mode = "undirected")eccentricity(g)Helper function for adding and deleting edges
Description
This is a helper function that simplifies adding and deletingedges to/from graphs.
Usage
edge(...)edges(...)Arguments
... | See details below. |
Details
edges() is an alias foredge().
When adding edges via+, all unnamed arguments ofedge() (oredges()) are concatenated, and then passed toadd_edges(). They are interpreted as pairs of vertex ids,and an edge will added between each pair. Named arguments will beused as edge attributes for the new edges.
When deleting edges via-, all arguments ofedge() (oredges()) are concatenated viac() and passed todelete_edges().
Value
A special object that can be used with together withigraph graphs and the plus and minus operators.
See Also
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()
Examples
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)Vertex and edge betweenness centrality
Description
edge.betweenness() was renamed toedge_betweenness() to create a moreconsistent API.
Usage
edge.betweenness( graph, e = E(graph), directed = TRUE, weights = NULL, cutoff = -1)Arguments
graph | The graph to analyze. |
e | The edges for which the edge betweenness will be calculated. |
directed | Logical, whether directed paths should be considered whiledetermining the shortest paths. |
weights | Optional positive weight vector for calculating weightedbetweenness. If the graph has a |
cutoff | The maximum shortest path length to consider when calculatingbetweenness. If negative, then there is no such limit. |
Community structure detection based on edge betweenness
Description
edge.betweenness.community() was renamed tocluster_edge_betweenness() to create a moreconsistent API.
Usage
edge.betweenness.community( graph, weights = NULL, directed = TRUE, edge.betweenness = TRUE, merges = TRUE, bridges = TRUE, modularity = TRUE, membership = TRUE)Arguments
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 edgebetweenness for directed graphs. It is ignored for undirected graphs. |
edge.betweenness | Logical constant, whether to return the edgebetweenness of the edges at the time of their removal. |
merges | Logical constant, whether to return the merge matrixrepresenting the hierarchical community structure of the network. Thisargument is called |
bridges | Logical constant, whether to return a list the edge removalswhich actually splitted a component of the graph. |
modularity | Logical constant, whether to calculate the maximummodularity score, considering all possibly community structures along theedge-betweenness based edge removals. |
membership | Logical constant, whether to calculate the membershipvector corresponding to the highest possible modularity score. |
Edge connectivity
Description
edge.connectivity() was renamed toedge_connectivity() to create a moreconsistent API.
Usage
edge.connectivity(graph, source = NULL, target = NULL, checks = TRUE)Arguments
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 connectedand also the degree of the vertices. If the graph is not (strongly)connected then the connectivity is obviously zero. Otherwise if the minimumdegree is one then the edge connectivity is also one. It is a good idea toperform these checks, as they can be done quickly compared to theconnectivity calculation itself. They were suggested by Peter McMahan,thanks Peter. |
Edge connectivity
Description
edge.disjoint.paths() was renamed toedge_connectivity() to create a moreconsistent API.
Usage
edge.disjoint.paths(graph, source = NULL, target = NULL, checks = TRUE)Arguments
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 connectedand also the degree of the vertices. If the graph is not (strongly)connected then the connectivity is obviously zero. Otherwise if the minimumdegree is one then the edge connectivity is also one. It is a good idea toperform these checks, as they can be done quickly compared to theconnectivity calculation itself. They were suggested by Peter McMahan,thanks Peter. |
Query edge attributes of a graph
Description
Query edge attributes of a graph
Usage
edge_attr(graph, name, index = E(graph))Arguments
graph | The graph |
name | The name of the attribute to query. If missing, thenall edge attributes are returned in a list. |
index | An optional edge sequence to query edge attributesfor a subset of edges. |
Value
The value of the edge attribute, or the list of alledge attributes ifname is missing.
See Also
Vertex, edge and graph attributesdelete_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(),set_vertex_attrs(),vertex_attr(),vertex_attr<-(),vertex_attr_names()
Examples
g <- make_ring(10) %>% set_edge_attr("weight", value = 1:10) %>% set_edge_attr("color", value = "red")gplot(g, edge.width = E(g)$weight)Set one or more edge attributes
Description
Set one or more edge attributes
Usage
edge_attr(graph, name, index = E(graph)) <- valueArguments
graph | The graph. |
name | The name of the edge attribute to set. If missing,then |
index | An optional edge sequence to set the attributesof a subset of edges. |
value | The new value of the attribute(s) for all(or |
Value
The graph, with the edge attribute(s) added or set.
See Also
Vertex, edge and graph attributesdelete_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(),set_vertex_attrs(),vertex_attr(),vertex_attr<-(),vertex_attr_names()
Examples
g <- make_ring(10)edge_attr(g) <- list( name = LETTERS[1:10], color = rep("green", gsize(g)))edge_attr(g, "label") <- E(g)$namegplot(g)List names of edge attributes
Description
List names of edge attributes
Usage
edge_attr_names(graph)Arguments
graph | The graph. |
Value
Character vector, the names of the edge attributes.
See Also
Vertex, edge and graph attributesdelete_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(),set_vertex_attrs(),vertex_attr(),vertex_attr<-(),vertex_attr_names()
Examples
g <- make_ring(10) %>% set_edge_attr("label", value = letters[1:10])edge_attr_names(g)plot(g)Edge connectivity
Description
The edge connectivity of a graph or two vertices, this is recently alsocalled group adhesion.
Usage
edge_connectivity(graph, source = NULL, target = NULL, checks = TRUE)edge_disjoint_paths(graph, source = NULL, target = NULL)adhesion(graph, checks = TRUE)Arguments
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 connectedand also the degree of the vertices. If the graph is not (strongly)connected then the connectivity is obviously zero. Otherwise if the minimumdegree is one then the edge connectivity is also one. It is a good idea toperform these checks, as they can be done quickly compared to theconnectivity calculation itself. They were suggested by Peter McMahan,thanks Peter. |
Value
A scalar real value.
edge_connectivity() Edge connectivity
The edge connectivity of a pair of vertices (source andtarget) is the minimum number of edges needed to remove to eliminateall (directed) paths fromsource totarget.edge_connectivity() calculates this quantity if both thesourceandtarget arguments are given (and notNULL).
The edge connectivity of a graph is the minimum of the edge connectivity ofevery (ordered) pair of vertices in the graph.edge_connectivity()calculates this quantity if neither thesource nor thetargetarguments are given (i.e. they are bothNULL).
edge_disjoint_paths() The maximum number of edge-disjoint paths between two vertices
A set of paths between two vertices is called edge-disjoint if they do notshare any edges. The maximum number of edge-disjoint paths are calculatedby this function using maximum flow techniques. Directed paths areconsidered in directed graphs.
A set of edge disjoint paths between two vertices is a set of paths betweenthem containing no common edges. The maximum number of edge disjoint pathsbetween two vertices is the same as their edge connectivity.
When there are no direct edges between the source and the target, the numberof vertex-disjoint paths is the same as the vertex connectivity ofthe two vertices. When some edges are present, each one of themcontributes one extra path.
adhesion() Adhesion of a graph
The adhesion of a graph is the minimum number of edges needed to remove toobtain a graph which is not strongly connected. This is the same as the edgeconnectivity of the graph.
All three functions
The three functions documented on this page calculate similar properties,more precisely the most general isedge_connectivity(), the others areincluded only for having more descriptive function names.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
Douglas R. White and Frank Harary (2001): The cohesiveness of blocks insocial networks: node connectivity and conditional density,Sociological Methodology, vol. 31, 2001, pp. 305–59.
See Also
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()
Examples
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)Graph density
Description
The density of a graph is the ratio of the actual number of edges and thelargest possible number of edges in the graph, assuming that no multi-edgesare present.
Usage
edge_density(graph, loops = FALSE)Arguments
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 thegraph. If this parameter is set to FALSE yet the graph contains self-loops,the result will not be meaningful. |
Details
The concept of density is ill-defined for multigraphs. Note that this functiondoes not check whether the graph has multi-edges and will return meaninglessresults for such graphs.
Value
A real constant. This function returnsNaN (=0.0/0.0) for anempty graph with zero vertices.
Related documentation in the C library
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
Wasserman, S., and Faust, K. (1994). Social Network Analysis:Methods and Applications. Cambridge: Cambridge University Press.
See Also
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(),feedback_vertex_set(),girth(),is_acyclic(),is_dag(),is_matching(),k_shortest_paths(),knn(),reciprocity(),subcomponent(),subgraph(),topo_sort(),transitivity(),unfold_tree(),which_multiple(),which_mutual()
Examples
edge_density(make_empty_graph(n = 10)) # empty graphs have density 0edge_density(make_full_graph(n = 10)) # complete graphs have density 1edge_density(sample_gnp(n = 100, p = 0.4)) # density will be close to p# loop edgesg <- make_graph(c(1, 2, 2, 2, 2, 3)) # graph with a self-loopedge_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 differentEigenvector centrality of vertices
Description
eigen_centrality() takes a graph (graph) and returns theeigenvector centralities of the verticesv within it.
Usage
eigen_centrality( graph, directed = FALSE, scale = deprecated(), weights = NULL, options = arpack_defaults())Arguments
graph | Graph to be analyzed. |
directed | Logical scalar, whether to consider direction of the edgesin directed graphs. It is ignored for undirected graphs. |
scale | |
weights | A numerical vector or |
options | A named list, to override some ARPACK options. See |
Details
Eigenvector centrality scores correspond to the values of the principaleigenvector of the graph's adjacency matrix; these scores may, in turn, beinterpreted as arising from a reciprocal process in which the centrality ofeach actor is proportional to the sum of the centralities of those actors towhom he or she is connected. In general, vertices with high eigenvectorcentralities are those which are connected to many other vertices which are,in turn, connected to many others (and so on). The perceptive may realizethat this implies that the largest values will be obtained by individuals inlarge cliques (or high-density substructures). This is also intelligiblefrom an algebraic point of view, with the first eigenvector being closelyrelated to the best rank-1 approximation of the adjacency matrix (arelationship which is easy to see in the special case of a diagonalizablesymmetric real matrix via theSLS^-1decomposition).
The adjacency matrix used in the eigenvector centrality calculation assumesthat loop edges are countedtwice in undirected graphs; this is becauseeach loop edge hastwo 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 iscalculated. In other words, the centrality of a vertex is proportional tothe 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 connectedcomponents, and the eigenvector centrality calculated for each separately.This function does not verify that the graph is connected. If it is not, inthe undirected case the scores of all but one component will be zeros.
Also note that the adjacency matrix of a directed acyclic graph or theadjacency 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 eigenvectorcentralities will all be equal for an empty graph and will all be zeros fora directed acyclic graph. Such pathological cases can be detected by checkingwhether the eigenvalue is very close to zero.
From igraph version 0.5 this function uses ARPACK for the underlyingcomputation, seearpack() for more about ARPACK in igraph.
Value
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
arpack()for the details.
Related documentation in the C library
Author(s)
Gabor Csardicsardi.gabor@gmail.com and Carter T. Butts(https://www.faculty.uci.edu/profile.cfm?faculty_id=5057) for themanual page.
References
Bonacich, P. (1987). Power and Centrality: A Family ofMeasures.American Journal of Sociology, 92, 1170-1182.
See Also
Centrality measuresalpha_centrality(),authority_score(),betweenness(),closeness(),diversity(),harmonic_centrality(),hits_scores(),page_rank(),power_centrality(),spectrum(),strength(),subgraph_centrality()
Examples
# Generate some test datag <- make_ring(10, directed = FALSE)# Compute eigenvector centrality scoreseigen_centrality(g)Spectral Embedding of Adjacency Matrices
Description
Spectral decomposition of the adjacency matrices of graphs.
Usage
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())Arguments
graph | The input graph, directed or undirected. |
no | An integer scalar. This value is the embedding dimension of thespectral embedding. Should be smaller than the number of vertices. Thelargest |
weights | Optional positive weight vector for calculating a weightedembedding. If the graph has a |
which | Which eigenvalues (or singular values, for directed graphs) touse. ‘lm’ means the ones with the largest magnitude, ‘la’ isthe ones (algebraic) largest, and ‘sa’ is the (algebraic) smallesteigenvalues. The default is ‘lm’. Note that for directed graphs‘la’ and ‘lm’ are the equivalent, because the singular valuesare used for the ordering. |
scaled | Logical scalar, if |
cvec | A numeric vector, its length is the number vertices in thegraph. This vector is added to the diagonal of the adjacency matrix. |
options | A named list containing the parameters for the SVDcomputation algorithm in ARPACK. By default, the list of values is assignedthe values given by |
Details
This function computes ano-dimensional Euclidean representation ofthe graph based on its adjacency matrix,A. This representation iscomputed via the singular value decomposition of the adjacency matrix,A=UDV^T.In the case, where the graph is a random dot product graphgenerated using latent position vectors inR^{no} for each vertex, theembedding will provide an estimate of these latent vectors.
For undirected graphs the latent positions are calculated asX=U^{no}D^{1/2}, whereU^{no} equalsto the firstno columns ofU, andD^{1/2} isa diagonal matrix containing the topno singular values on thediagonal.
For directed graphs the embedding is defined as the pairX=U^{no}D^{1/2} andY=V^{no}D^{1/2}. (For undirected graphsU=V, so it is enough to keep oneof them.)
Value
A list containing with entries:
- X
Estimated latent positions,an
ntimesnomatrix,nis the number of vertices.- Y
NULLfor undirected graphs, the second half of the latentpositions for directed graphs, anntimesnomatrix,nis the number of vertices.- 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 ARPACKcomputation. See
arpack()for the details.
Related documentation in the C library
adjacency_spectral_embedding().
References
Sussman, D.L., Tang, M., Fishkind, D.E., Priebe, C.E. AConsistent Adjacency Spectral Embedding for Stochastic Blockmodel Graphs,Journal of the American Statistical Association, Vol. 107(499), 2012
See Also
Other embedding:dim_select(),embed_laplacian_matrix()
Examples
## A small graphlpvs <- 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 Embedding of the Laplacian of a Graph
Description
Spectral decomposition of Laplacian matrices of graphs.
Usage
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())Arguments
graph | The input graph, directed or undirected. |
no | An integer scalar. This value is the embedding dimension of thespectral embedding. Should be smaller than the number of vertices. Thelargest |
weights | Optional positive weight vector for calculating a weightedembedding. If the graph has a |
which | Which eigenvalues (or singular values, for directed graphs) touse. ‘lm’ means the ones with the largest magnitude, ‘la’ isthe ones (algebraic) largest, and ‘sa’ is the (algebraic) smallesteigenvalues. The default is ‘lm’. Note that for directed graphs‘la’ and ‘lm’ are the equivalent, because the singular valuesare used for the ordering. |
type | The type of the Laplacian to use. Various definitions exist forthe Laplacian of a graph, and one can choose between them with thisargument. Possible values:
The default (i.e. type |
scaled | Logical scalar, if |
options | A named list containing the parameters for the SVDcomputation algorithm in ARPACK. By default, the list of values is assignedthe values given by |
Details
This function computes ano-dimensional Euclidean representation ofthe graph based on its Laplacian matrix,L. This representation iscomputed via the singular value decomposition of the Laplacian matrix.
They are essentially doing the same asembed_adjacency_matrix(),but work on the Laplacian matrix, instead of the adjacency matrix.
Value
A list containing with entries:
- X
Estimated latent positions,an
ntimesnomatrix,nis the number of vertices.- Y
NULLfor undirected graphs, the second half of the latentpositions for directed graphs, anntimesnomatrix,nis the number of vertices.- 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 ARPACKcomputation. See
arpack()for the details.
Related documentation in the C library
laplacian_spectral_embedding().
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
Sussman, D.L., Tang, M., Fishkind, D.E., Priebe, C.E. AConsistent Adjacency Spectral Embedding for Stochastic Blockmodel Graphs,Journal of the American Statistical Association, Vol. 107(499), 2012
See Also
embed_adjacency_matrix(),sample_dot_product()
Other embedding:dim_select(),embed_adjacency_matrix()
Examples
## A small graphlpvs <- 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
Description
Incident vertices of some graph edges
Usage
ends(graph, es, names = TRUE)Arguments
graph | The input graph |
es | The sequence of edges to query |
names | Whether to return vertex names ornumeric vertex ids. By default vertex names are used. |
Value
A two column matrix of vertex names or vertex ids.
See Also
Other structural queries:[.igraph(),[[.igraph(),adjacent_vertices(),are_adjacent(),get_edge_ids(),gorder(),gsize(),head_of(),incident(),incident_edges(),is_directed(),neighbors(),tail_of()
Examples
g <- make_ring(5)ends(g, E(g))Generate random graphs according to the Erdős-Rényi model
Description
Since igraph version 0.8.0, botherdos.renyi.game() andrandom.graph.game() are deprecated, andsample_gnp() andsample_gnm() should be used instead. See these for more details.
random.graph.game() is an (also deprecated) alias to this function.
Usage
erdos.renyi.game( n, p.or.m, type = c("gnp", "gnm"), directed = FALSE, loops = FALSE)Arguments
n | The number of vertices in the graph. |
p.or.m | Either the probability for drawing an edge between twoarbitrary vertices ( |
type | The type of the random graph to create, either |
directed | Logical, whether the graph will be directed, defaults to |
loops | Logical, whether to add loop edges, defaults to |
Value
A graph object.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
Erdős, P. and Rényi, A., On random graphs,PublicationesMathematicae 6, 290–297 (1959).
See Also
Random graph models (games)bipartite_gnm(),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(),sample_tree()
Examples
g <- erdos.renyi.game(1000, 1 / 1000)degree_distribution(g)Graph generation based on different vertex types
Description
establishment.game() was renamed tosample_traits() to create a moreconsistent API.
Usage
establishment.game( nodes, types, k = 1, type.dist = rep(1, types), pref.matrix = matrix(1, types, types), directed = FALSE)Arguments
nodes | The number of vertices in the graph. |
types | The number of different vertex types. |
k | The number of trials per time step, see details below. |
type.dist | The distribution of the vertex types. This is assumed to bestationary in time. |
pref.matrix | A matrix giving the preferences of the given vertextypes. These should be probabilities, i.e. numbers between zero and one. |
directed | Logical constant, whether to generate directed graphs. |
Deprecated version ofbetweenness()
Description
Usebetweenness() with thecutoff argument instead.
Usage
estimate_betweenness( graph, vids = V(graph), directed = TRUE, cutoff, weights = NULL)Arguments
graph | The graph to analyze. |
vids | The vertices for which the vertex betweenness estimation will becalculated. |
directed | Logical, whether directed paths should be considered whiledetermining the shortest paths. |
cutoff | The maximum shortest path length to consider when calculatingbetweenness. If negative, then there is no such limit. |
weights | Optional positive weight vector for calculating weightedbetweenness. If the graph has a |
Deprecated version ofcloseness()
Description
Usecloseness() with thecutoff argument instead.
Usage
estimate_closeness( graph, vids = V(graph), mode = c("out", "in", "all", "total"), cutoff, weights = NULL, normalized = FALSE)Arguments
graph | The graph to analyze. |
vids | The vertices for which closeness will be calculated. |
mode | Character string, defined the types of the paths used formeasuring the distance in directed graphs. “in” measures the pathsto a vertex, “out” measures pathsfrom a vertex,all uses undirected paths. This argument is ignored for undirectedgraphs. |
cutoff | The maximum path length to consider when calculating thecloseness. If zero or negative then there is no such limit. |
weights | Optional positive weight vector for calculating weightedcloseness. If the graph has a |
normalized | Logical scalar, whether to calculate the normalizedcloseness, i.e. the inverse average distance to all reachable vertices.The non-normalized closeness is the inverse of the sum of distances toall reachable vertices. |
Deprecated version ofedge_betweenness()
Description
Useedge_betweenness() with thecutoff argument instead.
Usage
estimate_edge_betweenness( graph, e = E(graph), directed = TRUE, cutoff, weights = NULL)Arguments
graph | The graph to analyze. |
e | The edges for which the edge betweenness will be calculated. |
directed | Logical, whether directed paths should be considered whiledetermining the shortest paths. |
cutoff | The maximum shortest path length to consider when calculatingbetweenness. If negative, then there is no such limit. |
weights | Optional positive weight vector for calculating weightedbetweenness. If the graph has a |
Find Eigenvector Centrality Scores of Network Positions
Description
evcent() was renamed toeigen_centrality() to create a moreconsistent API.
Usage
evcent( graph, directed = FALSE, scale = TRUE, weights = NULL, options = arpack_defaults())Arguments
graph | Graph to be analyzed. |
directed | Logical scalar, whether to consider direction of the edgesin directed graphs. It is ignored for undirected graphs. |
scale | |
weights | A numerical vector or |
options | A named list, to override some ARPACK options. See |
Calculate Cohesive Blocks
Description
exportPajek() was renamed toexport_pajek() to create a moreconsistent API.
Usage
exportPajek(blocks, graph, file, project.file = TRUE)Arguments
graph | For For |
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 projectfile containing all the data, or to create separated files for each item.See details below. |
Diameter of a graph
Description
farthest.nodes() was renamed tofarthest_vertices() to create a moreconsistent API.
Usage
farthest.nodes(graph, directed = TRUE, unconnected = TRUE, weights = NULL)Arguments
graph | The graph to analyze. |
directed | Logical, whether directed or undirected paths are to beconsidered. This is ignored for undirected graphs. |
unconnected | Logical, what to do if the graph is unconnected. IfFALSE, the function will return a number that is one larger the largestpossible diameter, which is always the number of vertices. If TRUE, thediameters of the connected components will be calculated and the largest onewill be returned. |
weights | Optional positive weight vector for calculating weighteddistances. If the graph has a |
Community structure via greedy optimization of modularity
Description
fastgreedy.community() was renamed tocluster_fast_greedy() to create a moreconsistent API.
Usage
fastgreedy.community( graph, merges = TRUE, modularity = TRUE, membership = TRUE, weights = NULL)Arguments
graph | The input graph. It must be undirected and must not havemulti-edges. |
merges | Logical scalar, whether to return the merge matrix. |
modularity | Logical scalar, whether to return a vector containing themodularity after each merge. |
membership | Logical scalar, whether to calculate the membership vectorcorresponding to the maximum modularity score, considering all possiblecommunity structures along the merges. |
weights | The weights of the edges. It must be a positive numeric vector, |
Finding a feedback arc set in a graph
Description
A feedback arc set of a graph is a subset of edges whose removal breaks allcycles in the graph.
Usage
feedback_arc_set(graph, weights = NULL, algo = c("approx_eades", "exact_ip"))Arguments
graph | The input graph |
weights | Potential edge weights. If the graph has an edgeattribute called ‘ |
algo | Specifies the algorithm to use. “ |
Details
Feedback arc sets are typically used in directed graphs. The removal of afeedback arc set of a directed graph ensures that the remaining graph is adirected acyclic graph (DAG). For undirected graphs, the removal of a feedbackarc set ensures that the remaining graph is a forest (i.e. every connectedcomponent is a tree).
Value
An edge sequence (by default, but see thereturn.vs.es optionofigraph_options()) containing the feedback arc set.
Related documentation in the C library
References
Peter Eades, Xuemin Lin and W.F.Smyth: A fast and effectiveheuristic for the feedback arc set problem.Information Processing Letters47:6, pp. 319-323, 1993
See Also
Other structural.properties:bfs(),component_distribution(),connect(),constraint(),coreness(),degree(),dfs(),distance_table(),edge_density(),feedback_vertex_set(),girth(),is_acyclic(),is_dag(),is_matching(),k_shortest_paths(),knn(),reciprocity(),subcomponent(),subgraph(),topo_sort(),transitivity(),unfold_tree(),which_multiple(),which_mutual()
Graph cyclesfeedback_vertex_set(),find_cycle(),girth(),has_eulerian_path(),is_acyclic(),is_dag(),simple_cycles()
Examples
g <- sample_gnm(20, 40, directed = TRUE)feedback_arc_set(g)feedback_arc_set(g, algo = "approx_eades")Finding a feedback vertex set in a graph
Description
A feedback vertex set of a graph is a subset of vertices whose removal breaksall cycles in the graph. Finding aminimum feedback vertex set is anNP-complete problem, both on directed and undirected graphs.
Usage
feedback_vertex_set(graph, weights = NULL, algo = c("exact_ip"))Arguments
graph | The input graph |
weights | Potential vertex weights. If the graph has a vertexattribute called ‘ |
algo | Specifies the algorithm to use. Currently, “ |
Value
A vertex sequence (by default, but see thereturn.vs.es optionofigraph_options()) containing the feedback vertex set.
Related documentation in the C library
See Also
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(),which_mutual()
Graph cyclesfeedback_arc_set(),find_cycle(),girth(),has_eulerian_path(),is_acyclic(),is_dag(),simple_cycles()
Examples
g <- make_lattice(c(3,3))feedback_vertex_set(g)Finds a cycle in a graph, if there is one
Description
This function returns a cycle of the graph, in terms of both its verticesand edges. If the graph is acyclic, it returns empty vertex and edgesequences.
Useis_acyclic() to determine if a graph has cycles, without returninga specific cycle.
Usage
find_cycle(graph, mode = c("out", "in", "all", "total"))Arguments
graph | The input graph. |
mode | Character constant specifying how to handle directed graphs. |
Value
A list of integer vectors, each integer vector is a path fromthe source vertex to one of the target vertices. A path is given by itsvertex ids.
Related documentation in the C library
See Also
Graph cyclesfeedback_arc_set(),feedback_vertex_set(),girth(),has_eulerian_path(),is_acyclic(),is_dag(),simple_cycles()
Examples
g <- make_lattice(c(3, 3))find_cycle(g)# Empty results are returned for acyclic graphsfind_cycle(sample_tree(5))Fit a hierarchical random graph model
Description
fit_hrg() fits a HRG to a given graph. It takes the specifiedsteps number of MCMC steps to perform the fitting, or a convergencecriteria if the specified number of steps is zero.fit_hrg() can startfrom a given HRG, if this is given in thehrg() argument and thestart argument isTRUE. It can be converted to thehclust class usingas.hclust() provided in this package.
Usage
fit_hrg(graph, hrg = NULL, start = FALSE, steps = 0)Arguments
graph | The graph to fit the model to. Edge directions are ignored indirected graphs. |
hrg | A hierarchical random graph model, in the form of an |
start | Logical, whether to start the fitting/sampling from thesupplied |
steps | The number of MCMC steps to make. If this is zero, then theMCMC procedure is performed until convergence. |
Value
fit_hrg() returns anigraphHRG object. This is a listwith 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
leftvector.- 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.
References
A. Clauset, C. Moore, and M.E.J. Newman. Hierarchical structureand the prediction of missing links in networks.Nature 453, 98–101(2008);
A. Clauset, C. Moore, and M.E.J. Newman. Structural Inference of Hierarchiesin Networks. In E. M. Airoldi et al. (Eds.): ICML 2006 Ws,LectureNotes in Computer Science 4503, 1–13. Springer-Verlag, Berlin Heidelberg(2007).
See Also
Other hierarchical random graph functions:consensus_tree(),hrg(),hrg-methods,hrg_tree(),predict_edges(),print.igraphHRG(),print.igraphHRGConsensus(),sample_hrg()
Examples
## A graph with two dense groupsg <- sample_gnp(10, p = 1 / 2) + sample_gnp(10, p = 1 / 2)hrg <- fit_hrg(g)hrgsummary(as.hclust(hrg))## The consensus tree for itconsensus_tree(g, hrg = hrg, start = TRUE)## Prediction of missing edgesg2 <- make_full_graph(4) + (make_full_graph(4) - path(1, 2))predict_edges(g2)Fitting a power-law distribution function to discrete data
Description
fit_power_law() fits a power-law distribution to a data set.
Usage
fit_power_law( x, xmin = NULL, start = 2, force.continuous = FALSE, implementation = c("plfit", "R.mle"), p.value = FALSE, p.precision = NULL, ...)Arguments
x | The data to fit, a numeric vector. For implementation‘ |
xmin | Numeric scalar, or |
start | Numeric scalar. The initial value of the exponent for theminimizing function, for the ‘ |
force.continuous | Logical scalar. Whether to force a continuousdistribution for the ‘ |
implementation | Character scalar. Which implementation to use. Seedetails below. |
p.value | Set to |
p.precision | The desired precision of the p-value calculation. Theprecision ultimately depends on the number of resampling attempts. Thenumber of resampling trials is determined by 0.25 divided by the squareof the required precision. For instance, a required precision of 0.01means that 2500 samples will be drawn. |
... | Additional arguments, passed to the maximum likelihoodoptimizing function, |
Details
This function fits a power-law distribution to a vector containing samplesfrom a distribution (that is assumed to follow a power-law of course). In apower-law distribution, it is generally assumed thatP(X=x) isproportional tox^{-\alpha}, wherex is a positivenumber and\alpha is greater than 1. In many real-world cases,the power-law behaviour kicks in only above a threshold valuex_\text{min}. The goal of this function is to determine\alpha ifx_\text{min} is given, or to determinex_\text{min} and the corresponding value of\alpha.
fit_power_law() provides two maximum likelihood implementations. Iftheimplementation argument is ‘R.mle’, then the BFGSoptimization (seestats4::mle()) algorithm is applied. The additionalarguments are passed to the mle function, so it is possible to change theoptimization method and/or its parameters. This implementation cannot to fit thex_\text{min} argument, so use the‘plfit’ implementation if you want to do that.
The ‘plfit’ implementation also uses the maximum likelihoodprinciple to determine\alpha for a givenx_\text{min};Whenx_\text{min} is not given in advance, the algorithm will attemptto find its optimal value for which thep-value of a Kolmogorov-Smirnovtest between the fitted distribution and the original sample is the largest.The function uses the method of Clauset, Shalizi and Newman to calculate theparameters of the fitted distribution. See references below for the details.
Passp.value = TRUE to include the p-value in the output.This is not returned by default because the computation may be slow.
Value
Depends on theimplementation argument. If it is‘R.mle’, then an object with class ‘mle’. It canbe used to calculate confidence intervals and log-likelihood. Seestats4::mle-class() for details.
Ifimplementation is ‘plfit’, then the result is anamed list with entries:
- continuous
Logical scalar, whether thefitted 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 thepower-law distribution was fitted. In other words, only the values largerthan
xminwere used from the input vector.- logLik
Numeric scalar, the log-likelihood of the fitted parameters.
- KS.stat
Numeric scalar, the test statistic of a Kolmogorov-Smirnov testthat compares the fitted distribution with the input vector.Smaller scores denote better fit.
- KS.p
Only for
p.value = TRUE. Numeric scalar, the p-value of the Kolmogorov-Smirnovtest. Small p-values (less than 0.05) indicate that the test rejected thehypothesis that the original data could have been drawn from the fittedpower-law distribution.
Author(s)
Tamas Nepuszntamas@gmail.com and Gabor Csardicsardi.gabor@gmail.com
References
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-lawdistributions in empirical data. SIAM Review 51(4):661-703, 2009.
See Also
Examples
# This should approximately yield the correct exponent 3g <- sample_pa(1000) # increase this number to have a better estimated <- degree(g, mode = "in")fit1 <- fit_power_law(d + 1, 10)fit2 <- fit_power_law(d + 1, 10, implementation = "R.mle")fit1$alphastats4::coef(fit2)fit1$logLikstats4::logLik(fit2)Forest Fire Network Model
Description
forest.fire.game() was renamed tosample_forestfire() to create a moreconsistent API.
Usage
forest.fire.game(nodes, fw.prob, bw.factor = 1, ambs = 1, directed = TRUE)Arguments
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 burningprobability is calculated as |
ambs | The number of ambassador vertices. |
directed | Logical scalar, whether to create a directed graph. |
Graph from incidence matrix
Description
graph_from_incidence_matrix() was renamed tograph_from_biadjacency_matrix() to create a moreconsistent API.
Usage
from_incidence_matrix(...)Details
Some authors refer to the bipartite adjacency matrix as the"bipartite incidence matrix". igraph 1.6.0 and later does not usethis naming to avoid confusion with the edge-vertex incidence matrix.
Convert a graph to an adjacency matrix
Description
get.adjacency() was renamed toas_adjacency_matrix() to create a moreconsistent API.
Usage
get.adjacency( graph, type = c("both", "upper", "lower"), attr = NULL, edges = FALSE, names = TRUE, sparse = igraph_opt("sparsematrices"))Arguments
Adjacency lists
Description
get.adjedgelist() was renamed toas_adj_edge_list() to create a moreconsistent API.
Usage
get.adjedgelist( graph, mode = c("all", "out", "in", "total"), loops = c("twice", "once", "ignore"))Arguments
graph | The input graph. |
mode | Character scalar, it gives what kind of adjacent edges/verticesto include in the lists. ‘ |
loops | Character scalar, one of |
Adjacency lists
Description
get.adjlist() was renamed toas_adj_list() to create a moreconsistent API.
Usage
get.adjlist( graph, mode = c("all", "out", "in", "total"), loops = c("twice", "once", "ignore"), multiple = TRUE)Arguments
graph | The input graph. |
mode | Character scalar, it gives what kind of adjacent edges/verticesto include in the lists. ‘ |
loops | Character scalar, one of |
multiple | Logical scalar, set to |
Shortest (directed or undirected) paths between vertices
Description
get.all.shortest.paths() was renamed toall_shortest_paths() to create a moreconsistent API.
Usage
get.all.shortest.paths( graph, from, to = V(graph), mode = c("out", "all", "in"), weights = NULL)Arguments
graph | The graph to work on. |
from | Numeric constant, the vertex from or to the shortest paths willbe calculated. Note that right now this is not a vector of vertex ids, butonly a single vertex. |
to | Numeric vector, the vertices to which the shortest paths will becalculated. By default it includes all vertices. Note that for |
mode | Character constant, gives whether the shortest paths to or fromthe given vertices should be calculated for directed graphs. If |
weights | Possibly a numeric vector giving edge weights. If this is |
Creating igraph graphs from data frames or vice-versa
Description
get.data.frame() was renamed toas_data_frame() to create a moreconsistent API.
Usage
get.data.frame(x, what = c("edges", "vertices", "both"))Arguments
x | An igraph object. |
what | Character constant, whether to return info about vertices,edges, or both. The default is ‘edges’. |
Diameter of a graph
Description
get.diameter() was renamed toget_diameter() to create a moreconsistent API.
Usage
get.diameter(graph, directed = TRUE, unconnected = TRUE, weights = NULL)Arguments
graph | The graph to analyze. |
directed | Logical, whether directed or undirected paths are to beconsidered. This is ignored for undirected graphs. |
unconnected | Logical, what to do if the graph is unconnected. IfFALSE, the function will return a number that is one larger the largestpossible diameter, which is always the number of vertices. If TRUE, thediameters of the connected components will be calculated and the largest onewill be returned. |
weights | Optional positive weight vector for calculating weighteddistances. If the graph has a |
Incident vertices of some graph edges
Description
Useends().
Usage
get.edge(graph, id)Arguments
graph | The input graph |
Query edge attributes of a graph
Description
get.edge.attribute() was renamed toedge_attr() to create a moreconsistent API.
Usage
get.edge.attribute(graph, name, index = E(graph))Arguments
graph | The graph |
name | The name of the attribute to query. If missing, thenall edge attributes are returned in a list. |
index | An optional edge sequence to query edge attributesfor a subset of edges. |
Find the edge ids based on the incident vertices of the edges
Description
get.edge.ids() was renamed toget_edge_ids() to create a moreconsistent API.
Usage
get.edge.ids(graph, vp, directed = TRUE, error = FALSE, multi = deprecated())Arguments
graph | The input graph. |
vp | The incident vertices, given as a two-column data frame, two-column matrix,or vector of vertex ids or symbolic vertex names.For a vector, the values are interpreted pairwise, i.e. the first and second are used forthe first edge, the third and fourth for the second, etc. |
directed | Logical scalar, whether to consider edge directions indirected graphs. This argument is ignored for undirected graphs. |
error | Logical scalar, whether to report an error if an edge is notfound in the graph. If |
multi |
Convert a graph to an edge list
Description
get.edgelist() was renamed toas_edgelist() to create a moreconsistent API.
Usage
get.edgelist(graph, names = TRUE)Arguments
graph | The graph to convert. |
names | Whether to return a character matrix containing vertexnames (i.e. the |
Graph attributes of a graph
Description
get.graph.attribute() was renamed tograph_attr() to create a moreconsistent API.
Usage
get.graph.attribute(graph, name)Arguments
graph | Input graph. |
name | The name of attribute to query. If missing, then allattributes are returned in a list. |
Bipartite adjacency matrix of a bipartite graph
Description
get.incidence() was renamed toas_biadjacency_matrix() to create a moreconsistent API.
Usage
get.incidence(graph, types = NULL, attr = NULL, names = TRUE, sparse = FALSE)Arguments
graph | The input graph. The direction of the edges is ignored indirected graphs. |
types | An optional vertex type vector to use instead of the |
attr | Either |
names | Logical scalar, if |
sparse | Logical scalar, if it is |
Shortest (directed or undirected) paths between vertices
Description
get.shortest.paths() was renamed toshortest_paths() to create a moreconsistent API.
Usage
get.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"))Arguments
graph | The graph to work on. |
from | Numeric constant, the vertex from or to the shortest paths willbe calculated. Note that right now this is not a vector of vertex ids, butonly a single vertex. |
to | Numeric vector, the vertices to which the shortest paths will becalculated. By default it includes all vertices. Note that for |
mode | Character constant, gives whether the shortest paths to or fromthe given vertices should be calculated for directed graphs. If |
weights | Possibly a numeric vector giving edge weights. If this is |
output | Character scalar, defines how to report the shortest paths.“vpath” means that the vertices along the paths are reported, thisform was used prior to igraph version 0.6. “epath” means that theedges along the paths are reported. “both” means that both forms arereturned, in a named list with components “vpath” and “epath”. |
predecessors | Logical scalar, whether to return the predecessor vertexfor each vertex. The predecessor of vertex |
inbound.edges | Logical scalar, whether to return the inbound edge foreach vertex. The inbound edge of vertex |
algorithm | Which algorithm to use for the calculation. By defaultigraph tries to select the fastest suitable algorithm. If there are noweights, then an unweighted breadth-first search is used, otherwise if allweights are positive, then Dijkstra's algorithm is used. If there arenegative weights and we do the calculation for more than 100 sources, thenJohnson's algorithm is used. Otherwise the Bellman-Ford algorithm is used.You can override igraph's choice by explicitly giving this parameter. Notethat 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 beused, regardless of this argument. |
Stochastic matrix of a graph
Description
get.stochastic() was renamed tostochastic_matrix() to create a moreconsistent API.
Usage
get.stochastic( graph, column.wise = FALSE, sparse = igraph_opt("sparsematrices"))Arguments
graph | The input graph. Must be of class |
column.wise | If |
sparse | Logical scalar, whether to return a sparse matrix. The |
Query vertex attributes of a graph
Description
get.vertex.attribute() was renamed tovertex_attr() to create a moreconsistent API.
Usage
get.vertex.attribute(graph, name, index = V(graph))Arguments
graph | The graph. |
name | Name of the attribute to query. If missing, thenall vertex attributes are returned in a list. |
index | An optional vertex sequence to query the attribute onlyfor these vertices. |
Parameters for the igraph package
Description
getIgraphOpt() was renamed toigraph_opt() to create a moreconsistent API.
Usage
getIgraphOpt(x, default = NULL)Arguments
x | A character string holding an option name. |
default | If the specified option is not set in the options list, thisvalue is returned. This facilitates retrieving an option and checkingwhether it is set and setting it separately if not. |
Find the edge ids based on the incident vertices of the edges
Description
Find the edges in an igraph graph that have the specified end points. Thisfunction handles multi-graph (graphs with multiple edges) and can consideror ignore the edge directions in directed graphs.
Usage
get_edge_ids(graph, vp, directed = TRUE, error = FALSE)Arguments
graph | The input graph. |
vp | The incident vertices, given as a two-column data frame, two-column matrix,or vector of vertex ids or symbolic vertex names.For a vector, the values are interpreted pairwise, i.e. the first and second are used forthe first edge, the third and fourth for the second, etc. |
directed | Logical scalar, whether to consider edge directions indirected graphs. This argument is ignored for undirected graphs. |
error | Logical scalar, whether to report an error if an edge is notfound in the graph. If |
Details
igraph vertex ids are natural numbers, starting from one, up to the numberof vertices in the graph. Similarly, edges are also numbered from one, up tothe number of edges.
This function allows finding the edges of the graph, via their incidentvertices.
Value
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, thenzero is reported. (If theerror argument isFALSE.)
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
Other structural queries:[.igraph(),[[.igraph(),adjacent_vertices(),are_adjacent(),ends(),gorder(),gsize(),head_of(),incident(),incident_edges(),is_directed(),neighbors(),tail_of()
Examples
g <- make_ring(10)ei <- get_edge_ids(g, c(1, 2, 4, 5))E(g)[ei]## non-existant edgeget_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))eisE(g)[eis]Girth of a graph
Description
The girth of a graph is the length of the shortest circle in it.
Usage
girth(graph, circle = TRUE)Arguments
graph | The input graph. It may be directed, but the algorithm searchesfor undirected circles anyway. |
circle | Logical scalar, whether to return the shortest circle itself. |
Details
The current implementation works for undirected graphs only, directed graphsare treated as undirected graphs. Loop edges and multiple edges are ignored.If the graph is a forest (i.e. acyclic), thenInf is returned.
This implementation is based on Alon Itai and Michael Rodeh: Finding aminimum circuit in a graphProceedings of the ninth annual ACMsymposium on Theory of computing, 1-10, 1977. The first implementation ofthis function was done by Keith Briggs, thanks Keith.
Value
A named list with two components:
- girth
Integer constant, the girth of the graph, or
Infif the graph is acyclic.- circle
Numeric vector with the vertex ids in the shortest circle.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
Alon Itai and Michael Rodeh: Finding a minimum circuit in agraphProceedings of the ninth annual ACM symposium on Theory ofcomputing, 1-10, 1977
See Also
Other structural.properties:bfs(),component_distribution(),connect(),constraint(),coreness(),degree(),dfs(),distance_table(),edge_density(),feedback_arc_set(),feedback_vertex_set(),is_acyclic(),is_dag(),is_matching(),k_shortest_paths(),knn(),reciprocity(),subcomponent(),subgraph(),topo_sort(),transitivity(),unfold_tree(),which_multiple(),which_mutual()
Graph cyclesfeedback_arc_set(),feedback_vertex_set(),find_cycle(),has_eulerian_path(),is_acyclic(),is_dag(),simple_cycles()
Examples
# No circle in a treeg <- make_tree(1000, 3)girth(g)# The worst case running time is for a ringg <- make_ring(100)girth(g)# What about a random graph?g <- sample_gnp(1000, 1 / 1000)girth(g)Efficiency of a graph
Description
These functions calculate the global or average local efficiency of a network,or the local efficiency of every vertex in the network. See below fordefinitions.
Usage
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"))Arguments
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. Ignoredfor 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 indirected graphs. “out” considers out-neighbors only, “in”considers in-neighbors only, “all” considers both. |
Value
Forglobal_efficiency(), the global efficiency of the graph as asingle number. Foraverage_local_efficiency(), the average localefficiency of the graph as a single number. Forlocal_efficiency(), thelocal efficiency of each vertex in a vector.
Global efficiency
The global efficiency of a network is defined as the average of inversedistances between all pairs of vertices.
More precisely:
E_g = \frac{1}{n (n-1)} \sum_{i \ne j} \frac{1}{d_{ij}}
wheren is the number of vertices.
The inverse distance between pairs that are not reachable from each other isconsidered to be zero. For graphs with fewer than 2 vertices, NaN is returned.
Local efficiency
The local efficiency of a network around a vertex is defined as follows: Weremove the vertex and compute the distances (shortest path lengths) betweenits neighbours through the rest of the network. The local efficiency aroundthe removed vertex is the average of the inverse of these distances.
The inverse distance between two vertices which are not reachable from eachother is considered to be zero. The local efficiency around a vertex withfewer than two neighbours is taken to be zero by convention.
Average local efficiency
The average local efficiency of a network is simply the arithmetic mean ofthe local efficiencies of all the vertices; see the definition for localefficiency above.
Related documentation in the C library
global_efficiency(),local_efficiency(),average_local_efficiency().
References
V. Latora and M. Marchiori: Efficient Behavior of Small-WorldNetworks, Phys. Rev. Lett. 87, 198701 (2001).
I. Vragović, E. Louis, and A. Díaz-Guilera, Efficiency of informationaltransfer in regular and complex networks, Phys. Rev. E 71, 1 (2005).
Examples
g <- make_graph("zachary")global_efficiency(g)average_local_efficiency(g)Order (number of vertices) of a graph
Description
vcount() andgorder() are aliases.
Usage
vcount(graph)gorder(graph)Arguments
graph | The graph |
Value
Number of vertices, numeric scalar.
Related documentation in the C library
See Also
Other structural queries:[.igraph(),[[.igraph(),adjacent_vertices(),are_adjacent(),ends(),get_edge_ids(),gsize(),head_of(),incident(),incident_edges(),is_directed(),neighbors(),tail_of()
Examples
g <- make_ring(10)gorder(g)vcount(g)Create an igraph graph from a list of edges, or a notable graph
Description
graph() was renamed tomake_graph() to create a moreconsistent API.
Usage
graph( edges, ..., n = max(edges), isolates = NULL, directed = TRUE, dir = directed, simplify = TRUE)Arguments
edges | A vector defining the edges, the first edge pointsfrom the first element to the second, the second edge from the thirdto the fourth, etc. For a numeric vector, these are interpretedas internal vertex ids. For character vectors, they are interpretedas vertex names. Alternatively, this can be a character scalar, the name of anotable graph. See Notable graphs below. The name is caseinsensitive. 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 isignored (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. |
Edge connectivity
Description
graph.adhesion() was renamed toadhesion() to create a moreconsistent API.
Usage
graph.adhesion(graph, checks = TRUE)Arguments
graph | The input graph. |
checks | Logical constant. Whether to check that the graph is connectedand also the degree of the vertices. If the graph is not (strongly)connected then the connectivity is obviously zero. Otherwise if the minimumdegree is one then the edge connectivity is also one. It is a good idea toperform these checks, as they can be done quickly compared to theconnectivity calculation itself. They were suggested by Peter McMahan,thanks Peter. |
Create graphs from adjacency matrices
Description
graph.adjacency() was renamed tograph_from_adjacency_matrix() to create a moreconsistent API.
Usage
graph.adjacency( adjmatrix, mode = c("directed", "undirected", "max", "min", "upper", "lower", "plus"), weighted = NULL, diag = TRUE, add.colnames = NULL, add.rownames = NA)Arguments
adjmatrix | A square adjacency matrix. From igraph version 0.5.1 thiscan be a sparse matrix created with the |
mode | Character scalar, specifies how igraph should interpret thesupplied matrix. See also the |
weighted | This argument specifies whether to create a weighted graphfrom an adjacency matrix. If it is |
diag | Logical scalar, whether to include the diagonal of the matrix inthe calculation. If this is |
add.colnames | Character scalar, whether to add the column names asvertex attributes. If it is |
add.rownames | Character scalar, whether to add the row names as vertexattributes. Possible values the same as the previous argument. By defaultrow names are not added. If ‘ |
Create graphs from adjacency lists
Description
graph.adjlist() was renamed tograph_from_adj_list() to create a moreconsistent API.
Usage
graph.adjlist(adjlist, mode = c("out", "in", "all", "total"), duplicate = TRUE)Arguments
adjlist | The adjacency list. It should be consistent, i.e. the maximumthroughout 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 isundirected (‘all’ or ‘total’) or directed; and in the lattercase, whether it contains the outgoing (‘out’) or the incoming(‘in’) neighbors of the vertices. |
duplicate | Logical scalar. For undirected graphs it gives whetheredges are included in the list twice. E.g. if it is This argument is ignored if |
Create a graph from the Graph Atlas
Description
graph.atlas() was renamed tograph_from_atlas() to create a moreconsistent API.
Usage
graph.atlas(n)Arguments
n | The id of the graph to create. |
Number of automorphisms
Description
graph.automorphisms() was renamed tocount_automorphisms() to create a moreconsistent API.
Usage
graph.automorphisms( graph, colors = NULL, sh = c("fm", "f", "fs", "fl", "flm", "fsm"))Arguments
graph | The input graph, it is treated as undirected. |
colors | The colors of the individual vertices of the graph; onlyvertices having the same color are allowed to match each other in anautomorphism. When omitted, igraph uses the |
sh | The splitting heuristics for the BLISS algorithm. Possible valuesare:‘ |
Breadth-first search
Description
graph.bfs() was renamed tobfs() to create a moreconsistent API.
Usage
graph.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)Arguments
Create a bipartite graph
Description
graph.bipartite() was renamed tomake_bipartite_graph() to create a moreconsistent API.
Usage
graph.bipartite(types, edges, directed = FALSE)Arguments
types | A vector giving the vertex types. It will be coerced intoboolean. 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 graphas the |
edges | A vector giving the edges of the graph, the same way as for theregular |
directed | Whether to create a directed graph, boolean constant. Notethat by default undirected graphs are created, as this is more common forbipartite graphs. |
Vertex connectivity
Description
graph.cohesion() was renamed tocohesion() to create a moreconsistent API.
Usage
graph.cohesion(x, ...)Arguments
x | x |
... | passed to |
Complementer of a graph
Description
graph.complementer() was renamed tocomplementer() to create a moreconsistent API.
Usage
graph.complementer(graph, loops = FALSE)Arguments
graph | The input graph, can be directed or undirected. |
loops | Logical constant, whether to generate loop edges. |
Compose two graphs as binary relations
Description
graph.compose() was renamed tocompose() to create a moreconsistent API.
Usage
graph.compose(g1, g2, byname = "auto")Arguments
g1 | The first input graph. |
g2 | The second input graph. |
byname | A logical scalar, or the character scalar |
K-core decomposition of graphs
Description
graph.coreness() was renamed tocoreness() to create a moreconsistent API.
Usage
graph.coreness(graph, mode = c("all", "out", "in"))Arguments
graph | The input graph, it can be directed or undirected |
mode | The type of the core in directed graphs. Character constant,possible values: |
Creating igraph graphs from data frames or vice-versa
Description
graph.data.frame() was renamed tograph_from_data_frame() to create a moreconsistent API.
Usage
graph.data.frame(d, directed = TRUE, vertices = NULL)Arguments
d | A data frame containing a symbolic edge list in the first twocolumns. Additional columns are considered as edge attributes. Sinceversion 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 |
De Bruijn graphs
Description
graph.de.bruijn() was renamed tomake_de_bruijn_graph() to create a moreconsistent API.
Usage
graph.de.bruijn(m, n)Arguments
m | Integer scalar, the size of the alphabet. See details below. |
n | Integer scalar, the length of the labels. See details below. |
Graph density
Description
graph.density() was renamed toedge_density() to create a moreconsistent API.
Usage
graph.density(graph, loops = FALSE)Arguments
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 thegraph. If this parameter is set to FALSE yet the graph contains self-loops,the result will not be meaningful. |
Depth-first search
Description
graph.dfs() was renamed todfs() to create a moreconsistent API.
Usage
graph.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)Arguments
Difference of two sets
Description
graph.difference() was renamed todifference() to create a moreconsistent API.
Usage
graph.difference(...)Arguments
... | Arguments, their number and interpretation depends onthe function that implements |
Disjoint union of graphs
Description
graph.disjoint.union() was renamed todisjoint_union() to create a moreconsistent API.
Usage
graph.disjoint.union(...)Arguments
... | Graph objects or lists of graph objects. |
Graph diversity
Description
graph.diversity() was renamed todiversity() to create a moreconsistent API.
Usage
graph.diversity(graph, weights = NULL, vids = V(graph))Arguments
graph | The input graph. Edge directions are ignored. |
weights |
|
vids | The vertex ids for which to calculate the measure. |
Create a graph from an edge list matrix
Description
graph.edgelist() was renamed tograph_from_edgelist() to create a moreconsistent API.
Usage
graph.edgelist(el, directed = TRUE)Arguments
el | The edge list, a two column matrix, character or numeric. |
directed | Whether to create a directed graph. |
Eigenvalues and eigenvectors of the adjacency matrix of a graph
Description
graph.eigen() was renamed tospectrum() to create a moreconsistent API.
Usage
graph.eigen( graph, algorithm = c("arpack", "auto", "lapack", "comp_auto", "comp_lapack", "comp_arpack"), which = list(), options = arpack_defaults())Arguments
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 tocalculate. By default the leading (i.e. largest magnitude) eigenvalue andthe corresponding eigenvector is calculated. |
options | Options for the ARPACK solver. See |
A graph with no edges
Description
graph.empty() was renamed tomake_empty_graph() to create a moreconsistent API.
Usage
graph.empty(n = 0, directed = TRUE)Arguments
n | Number of vertices. |
directed | Whether to create a directed graph. |
Create an extended chordal ring graph
Description
graph.extended.chordal.ring() was renamed tomake_chordal_ring() to create a moreconsistent API.
Usage
graph.extended.chordal.ring(n, w, directed = FALSE)Arguments
n | The number of vertices. |
w | A matrix which specifies the extended chordal ring. Seedetails below. |
directed | Logical scalar, whether or not to create a directed graph. |
Create an igraph graph from a list of edges, or a notable graph
Description
graph.famous() was renamed tomake_graph() to create a moreconsistent API.
Usage
graph.famous( edges, ..., n = max(edges), isolates = NULL, directed = TRUE, dir = directed, simplify = TRUE)Arguments
edges | A vector defining the edges, the first edge pointsfrom the first element to the second, the second edge from the thirdto the fourth, etc. For a numeric vector, these are interpretedas internal vertex ids. For character vectors, they are interpretedas vertex names. Alternatively, this can be a character scalar, the name of anotable graph. See Notable graphs below. The name is caseinsensitive. 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 isignored (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. |
Creating (small) graphs via a simple interface
Description
graph.formula() was renamed tograph_from_literal() to create a moreconsistent API.
Usage
graph.formula(..., simplify = TRUE)Arguments
... | For |
simplify | Logical scalar, whether to call |
Create a full graph
Description
graph.full() was renamed tomake_full_graph() to create a moreconsistent API.
Usage
graph.full(n, directed = FALSE, loops = FALSE)Arguments
n | Number of vertices. |
directed | Whether to create a directed graph. |
loops | Whether to add self-loops to the graph. |
Create a full bipartite graph
Description
graph.full.bipartite() was renamed tomake_full_bipartite_graph() to create a moreconsistent API.
Usage
graph.full.bipartite(n1, n2, directed = FALSE, mode = c("all", "out", "in"))Arguments
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 ‘ |
Create a complete (full) citation graph
Description
graph.full.citation() was renamed tomake_full_citation_graph() to create a moreconsistent API.
Usage
graph.full.citation(n, directed = TRUE)Arguments
n | The number of vertices. |
directed | Whether to create a directed graph. |
Load a graph from the graph database for testing graph isomorphism.
Description
graph.graphdb() was renamed tograph_from_graphdb() to create a moreconsistent API.
Usage
graph.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)Arguments
url | If not |
prefix | Gives the prefix. See details below. Possible values: |
type | Gives the graph type identifier. See details below. Possiblevalues: |
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 typethere are a number of actual graphs in the database. This argument specifieswhich one to read. |
base | The base address of the database. See details below. |
compressed | Logical constant, if TRUE than the file is expected to becompressed by gzip. If |
directed | Logical constant, whether to create a directed graph. |
Create graphs from a bipartite adjacency matrix
Description
graph.incidence() was renamed tograph_from_biadjacency_matrix() to create a moreconsistent API.
Usage
graph.incidence( incidence, directed = FALSE, mode = c("all", "out", "in", "total"), multiple = FALSE, weighted = NULL, add.names = NULL)Arguments
incidence | The input bipartite adjacency matrix. It can also be a sparse matrixfrom the |
directed | Logical scalar, whether to create a directed graph. |
mode | A character constant, defines the direction of the edges indirected graphs, ignored for undirected graphs. If ‘ |
multiple | Logical scalar, specifies how to interpret the matrixelements. See details below. |
weighted | This argument specifies whether to create a weighted graphfrom the bipartite adjacency matrix. If it is |
add.names | A character constant, |
Intersection of two or more sets
Description
graph.intersection() was renamed tointersection() to create a moreconsistent API.
Usage
graph.intersection(...)Arguments
... | Arguments, their number and interpretation depends onthe function that implements |
Create a graph from an isomorphism class
Description
graph.isocreate() was renamed tograph_from_isomorphism_class() to create a moreconsistent API.
Usage
graph.isocreate(size, number, directed = TRUE)Arguments
size | The number of vertices in the graph. |
number | The isomorphism class. |
directed | Whether to create a directed graph (the default). |
Kautz graphs
Description
graph.kautz() was renamed tomake_kautz_graph() to create a moreconsistent API.
Usage
graph.kautz(m, n)Arguments
m | Integer scalar, the size of the alphabet. See details below. |
n | Integer scalar, the length of the labels. See details below. |
Average nearest neighbor degree
Description
graph.knn() was renamed toknn() to create a moreconsistent API.
Usage
graph.knn( graph, vids = V(graph), mode = c("all", "out", "in", "total"), neighbor.degree.mode = c("all", "out", "in", "total"), weights = NULL)Arguments
graph | The input graph. It may be directed. |
vids | The vertices for which the calculation is performed. Normally itincludes all vertices. Note, that if not all vertices are given here, thenboth ‘ |
mode | Character constant to indicate the type of neighbors to considerin directed graphs. |
neighbor.degree.mode | The type of degree to average in directed graphs. |
weights | Weight vector. If the graph has a |
Graph Laplacian
Description
graph.laplacian() was renamed tolaplacian_matrix() to create a moreconsistent API.
Usage
graph.laplacian( graph, normalized = FALSE, weights = NULL, sparse = igraph_opt("sparsematrices"))Arguments
graph | The input graph. |
normalized | Deprecated, use |
weights | An optional vector giving edge weights for weighted Laplacianmatrix. If this is |
sparse | Logical scalar, whether to return the result as a sparsematrix. The |
Create a lattice graph
Description
graph.lattice() was renamed tomake_lattice() to create a moreconsistent API.
Usage
graph.lattice( dimvector = NULL, length = NULL, dim = NULL, nei = 1, directed = FALSE, mutual = FALSE, periodic = FALSE, circular = deprecated())Arguments
dimvector | A vector giving the size of the lattice in eachdimension. |
length | Integer constant, for regular lattices, the size of thelattice in each dimension. |
dim | Integer constant, the dimension of the lattice. |
nei | The distance within which (inclusive) the neighbors on thelattice 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 isperiodic along each dimension. This parameter may also be scalar boolen value which willbe extended to boolean vector with dimvector length. |
circular | Deprecated, use |
Related documentation in the C library
Creating a graph from LCF notation
Description
graph.lcf() was renamed tograph_from_lcf() to create a moreconsistent API.
Usage
graph.lcf(n, shifts, repeats = 1)Arguments
n | Integer, the number of vertices in the graph. If |
shifts | Integer vector, the shifts. |
repeats | Integer constant, how many times to repeat the shifts. |
Maximum flow in a graph
Description
graph.maxflow() was renamed tomax_flow() to create a moreconsistent API.
Usage
graph.maxflow(graph, source, target, capacity = NULL)Arguments
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 |
Minimum cut in a graph
Description
graph.mincut() was renamed tomin_cut() to create a moreconsistent API.
Usage
graph.mincut( graph, source = NULL, target = NULL, capacity = NULL, value.only = TRUE)Arguments
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 |
Graph motifs
Description
graph.motifs() was renamed tomotifs() to create a moreconsistent API.
Usage
graph.motifs(graph, size = 3, cut.prob = rep(0, size))Arguments
graph | Graph object, the input graph. |
size | The size of the motif, currently sizes 3 and 4 are supported indirected graphs and sizes 3-6 in undirected graphs. |
cut.prob | Numeric vector giving the probabilities that the searchgraph is cut at a certain level. Its length should be the same as the sizeof the motif (the |
Graph motifs
Description
graph.motifs.est() was renamed tosample_motifs() to create a moreconsistent API.
Usage
graph.motifs.est( graph, size = 3, cut.prob = rep(0, size), sample.size = vcount(graph)/10, sample = NULL)Arguments
graph | Graph object, the input graph. |
size | The size of the motif, currently size 3 and 4 are supportedin directed graphs and sizes 3-6 in undirected graphs. |
cut.prob | Numeric vector giving the probabilities that the searchgraph is cut at a certain level. Its length should be the same as the sizeof the motif (the |
sample.size | The number of vertices to use as a starting point forfinding motifs. Only used if the |
sample | If not |
Graph motifs
Description
graph.motifs.no() was renamed tocount_motifs() to create a moreconsistent API.
Usage
graph.motifs.no(graph, size = 3, cut.prob = rep(0, size))Arguments
graph | Graph object, the input graph. |
size | The size of the motif. |
cut.prob | Numeric vector giving the probabilities that the searchgraph is cut at a certain level. Its length should be the same as the sizeof the motif (the |
Neighborhood of graph vertices
Description
graph.neighborhood() was renamed tomake_ego_graph() to create a moreconsistent API.
Usage
graph.neighborhood( graph, order = 1, nodes = V(graph), mode = c("all", "out", "in"), mindist = 0)Arguments
graph | The input graph. |
order | Integer giving the order of the neighborhood. Negative valuesindicate an infinite order. |
nodes | The vertices for which the calculation is performed. |
mode | Character constant, it specifies how to use the direction ofthe edges if a directed graph is analyzed. For ‘out’ only theoutgoing edges are followed, so all vertices reachable from the sourcevertex in at most |
mindist | The minimum distance to include the vertex in the result. |
Create a ring graph
Description
graph.ring() was renamed tomake_ring() to create a moreconsistent API.
Usage
graph.ring(n, directed = FALSE, mutual = FALSE, circular = TRUE)Arguments
n | Number of vertices. |
directed | Whether the graph is directed. |
mutual | Whether directed edges are mutual. It is ignored inundirected graphs. |
circular | Whether to create a circular ring. A non-circularring is essentially a “line”: a tree where every non-leafvertex has one child. |
Create a star graph, a tree with n vertices and n - 1 leaves
Description
graph.star() was renamed tomake_star() to create a moreconsistent API.
Usage
graph.star(n, mode = c("in", "out", "mutual", "undirected"), center = 1)Arguments
n | Number of vertices. |
mode | It defines the direction of theedges, |
center | ID of the center vertex. |
Strength or weighted vertex degree
Description
graph.strength() was renamed tostrength() to create a moreconsistent API.
Usage
graph.strength( graph, vids = V(graph), mode = c("all", "out", "in", "total"), loops = TRUE, weights = NULL)Arguments
graph | The input graph. |
vids | The vertices for which the strength will be calculated. |
mode | Character string, “out” for out-degree, “in” forin-degree or “all” for the sum of the two. For undirected graphs thisargument is ignored. |
loops | Logical; whether the loop edges are also counted. |
weights | Weight vector. If the graph has a |
Create tree graphs
Description
graph.tree() was renamed tomake_tree() to create a moreconsistent API.
Usage
graph.tree(n, children = 2, mode = c("out", "in", "undirected"))Arguments
n | Number of vertices. |
children | Integer scalar, the number of children of a vertex(except for leafs) |
mode | Defines the direction of theedges. |
Union of graphs
Description
graph.union() was renamed tounion.igraph() to create a moreconsistent API.
Usage
graph.union(..., byname = "auto")Arguments
... | Graph objects or lists of graph objects. |
byname | A logical scalar, or the character scalar |
Convert object to a graph
Description
This is a generic function to convert R objects to igraph graphs.
Usage
graph_(...)Arguments
... | Parameters, see details below. |
Details
TODO
Examples
## These are equivalentgraph_(cbind(1:5, 2:6), from_edgelist(directed = FALSE))graph_(cbind(1:5, 2:6), from_edgelist(), directed = FALSE)Graph attributes of a graph
Description
Graph attributes of a graph
Usage
graph_attr(graph, name)Arguments
graph | Input graph. |
name | The name of attribute to query. If missing, then allattributes are returned in a list. |
Value
A list of graph attributes, or a single graph attribute.
See Also
Vertex, edge and graph attributesdelete_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(),set_vertex_attrs(),vertex_attr(),vertex_attr<-(),vertex_attr_names()
Examples
g <- make_ring(10)graph_attr(g)graph_attr(g, "name")Set all or some graph attributes
Description
Set all or some graph attributes
Usage
graph_attr(graph, name) <- valueArguments
graph | The graph. |
name | The name of the attribute to set. If missing, then |
value | The value of the attribute to set |
Value
The graph, with the attribute(s) added.
See Also
Vertex, edge and graph attributesdelete_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(),set_vertex_attrs(),vertex_attr(),vertex_attr<-(),vertex_attr_names()
Examples
g <- make_graph(~ A - B:C:D)graph_attr(g, "name") <- "4-star"ggraph_attr(g) <- list( layout = layout_with_fr(g), name = "4-star layed out")plot(g)List names of graph attributes
Description
List names of graph attributes
Usage
graph_attr_names(graph)Arguments
graph | The graph. |
Value
Character vector, the names of the graph attributes.
See Also
Vertex, edge and graph attributesdelete_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(),set_vertex_attrs(),vertex_attr(),vertex_attr<-(),vertex_attr_names()
Examples
g <- make_ring(10)graph_attr_names(g)Central vertices of a graph
Description
The center of a graph is the set of its vertices with minimal eccentricity.
Usage
graph_center(graph, ..., weights = NULL, mode = c("all", "out", "in", "total"))Arguments
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 fromthe given vertices should be calculated for directed graphs. If |
Value
The vertex IDs of the central vertices.
Related documentation in the C library
See Also
Other paths:all_simple_paths(),diameter(),distance_table(),eccentricity(),radius()
Examples
tree <- make_tree(100, 7)graph_center(tree)graph_center(tree, mode = "in")graph_center(tree, mode = "out")# Without and with weightsring <- make_ring(10)graph_center(ring)# Add weightsE(ring)$weight <- seq_len(ecount(ring))graph_center(ring)Create graphs from adjacency lists
Description
An adjacency list is a list of numeric vectors, containing the neighborvertices for each vertex. This function creates an igraph graph object fromsuch a list.
Usage
graph_from_adj_list( adjlist, mode = c("out", "in", "all", "total"), duplicate = TRUE)Arguments
adjlist | The adjacency list. It should be consistent, i.e. the maximumthroughout 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 isundirected (‘all’ or ‘total’) or directed; and in the lattercase, whether it contains the outgoing (‘out’) or the incoming(‘in’) neighbors of the vertices. |
duplicate | Logical scalar. For undirected graphs it gives whetheredges are included in the list twice. E.g. if it is This argument is ignored if |
Details
Adjacency lists are handy if you intend to do many (small) modifications toa graph. In this case adjacency lists are more efficient than igraph graphs.
The idea is that you convert your graph to an adjacency list byas_adj_list(), do your modifications to the graphs and finallycreate again an igraph graph by callinggraph_from_adj_list().
Value
An igraph graph object.
Related documentation in the C library
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
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()
Examples
## Directedg <- make_ring(10, directed = TRUE)al <- as_adj_list(g, mode = "out")g2 <- graph_from_adj_list(al)isomorphic(g, g2)## Undirectedg <- make_ring(10)al <- as_adj_list(g)g2 <- graph_from_adj_list(al, mode = "all")isomorphic(g, g2)ecount(g2)g3 <- graph_from_adj_list(al, mode = "all", duplicate = FALSE)ecount(g3)which_multiple(g3)Create graphs from adjacency matrices
Description
graph_from_adjacency_matrix() is a flexible function for creatingigraphgraphs from adjacency matrices.
Usage
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(...)Arguments
adjmatrix | A square adjacency matrix. From igraph version 0.5.1 thiscan be a sparse matrix created with the |
mode | Character scalar, specifies how igraph should interpret thesupplied matrix. See also the |
weighted | This argument specifies whether to create a weighted graphfrom an adjacency matrix. If it is |
diag | Logical scalar, whether to include the diagonal of the matrix inthe calculation. If this is |
add.colnames | Character scalar, whether to add the column names asvertex attributes. If it is |
add.rownames | Character scalar, whether to add the row names as vertexattributes. Possible values the same as the previous argument. By defaultrow names are not added. If ‘ |
... | Passed to |
Details
The order of the vertices are preserved, i.e. the vertex corresponding tothe first row will be vertex 0 in the graph, etc.
graph_from_adjacency_matrix() operates in two main modes, depending on theweighted argument.
If this argument isNULL then an unweighted graph is created and anelement of the adjacency matrix gives the number of edges to create betweenthe two corresponding vertices. The details depend on the value of themode argument:
- "directed"
The graph will be directed and a matrix element givesthe number of edges between two vertices.
- "undirected"
This is exactly the same as
max, for convenience.Note that it isnot checked whether the matrix is symmetric.- "max"
An undirected graph will be created and
max(A(i,j), A(j,i))gives the number of edges.- "upper"
An undirected graph will be created, only the upper right triangle(including the diagonal) is used for the number of edges.
- "lower"
An undirected graph will be created, only the lower left triangle(including the diagonal) is used for creating the edges.
- "min"
An undirected graph will be created with
min(A(i,j), A(j,i))edgesbetween vertexiandj.- "plus"
An undirected graph will be created with
A(i,j)+A(j,i)edgesbetween vertexiandj.
If theweighted argument is notNULL then the elements of thematrix give the weights of the edges (if they are not zero). The detailsdepend on the value of themode argument:
- "directed"
The graph will be directed and a matrix element gives the edge weights.
- "undirected"
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.
- "max"
An undirected graph will be created and
max(A(i,j), A(j,i))gives the edge weights.- "upper"
An undirected graph will be created, only the upper right triangle(including the diagonal) is used (for the edge weights).
- "lower"
An undirected graph will be created, only the lower left triangle(including the diagonal) is used for creating the edges.
- "min"
An undirected graph will be created,
min(A(i,j), A(j,i))gives the edge weights.- "plus"
An undirected graph will be created,
A(i,j)+A(j,i)gives the edge weights.
Value
An igraph graph object.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
make_graph() andgraph_from_literal() for other ways tocreate graphs.
Examples
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 testsnon_zero_sort <- function(x) sort(x[x != 0])adj_matrix <- matrix(runif(100), 10)adj_matrix[adj_matrix < 0.5] <- 0g3 <- 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 namesrownames(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)Create a graph from the Graph Atlas
Description
graph_from_atlas() creates graphs from the book‘An Atlas of Graphs’ byRoland C. Read and Robin J. Wilson. The atlas contains all undirectedgraphs with up to seven vertices, numbered from 0 up to 1252. Thegraphs are listed:
in increasing order of number of nodes;
for a fixed number of nodes, in increasing order of the numberof edges;
for fixed numbers of nodes and edges, in increasing order ofthe degree sequence, for example 111223 < 112222;
for fixed degree sequence, in increasing number ofautomorphisms.
Usage
graph_from_atlas(n)atlas(...)Arguments
n | The id of the graph to create. |
... | Passed to |
Value
An igraph graph.
See Also
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()
Examples
## Some randomly picked graphs from the atlasgraph_from_atlas(sample(0:1252, 1))graph_from_atlas(sample(0:1252, 1))Create graphs from a bipartite adjacency matrix
Description
graph_from_biadjacency_matrix() creates a bipartite igraph graph from an incidencematrix.
Usage
graph_from_biadjacency_matrix( incidence, directed = FALSE, mode = c("all", "out", "in", "total"), multiple = FALSE, weighted = NULL, add.names = NULL)Arguments
incidence | The input bipartite adjacency matrix. It can also be a sparse matrixfrom the |
directed | Logical scalar, whether to create a directed graph. |
mode | A character constant, defines the direction of the edges indirected graphs, ignored for undirected graphs. If ‘ |
multiple | Logical scalar, specifies how to interpret the matrixelements. See details below. |
weighted | This argument specifies whether to create a weighted graphfrom the bipartite adjacency matrix. If it is |
add.names | A character constant, |
Details
Bipartite graphs have a ‘type’ vertex attribute in igraph,this is boolean andFALSE for the vertices of the first kind andTRUE for vertices of the second kind.
graph_from_biadjacency_matrix() can operate in two modes, depending on themultiple argument. If it isFALSE then a single edge iscreated for every non-zero element in the bipartite adjacency matrix. Ifmultiple isTRUE, then the matrix elements are rounded up tothe closest non-negative integer to get the number of edges to createbetween 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 usethis naming to avoid confusion with the edge-vertex incidence matrix.
Value
A bipartite igraph graph. In other words, an igraph graph that has avertex attributetype.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
make_bipartite_graph() for another way to create bipartitegraphs
Other biadjacency:as_data_frame()
Examples
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)Create a graph from an edge list matrix
Description
graph_from_edgelist() creates a graph from an edge list. Its argumentis a two-column matrix, each row defines one edge. If it isa numeric matrix then its elements are interpreted as vertex ids. Ifit is a character matrix then it is interpreted as symbolic vertexnames and a vertex id will be assigned to each name, and also aname vertex attribute will be added.
Usage
graph_from_edgelist(el, directed = TRUE)from_edgelist(...)Arguments
el | The edge list, a two column matrix, character or numeric. |
directed | Whether to create a directed graph. |
... | Passed to |
Value
An igraph graph.
See Also
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()
Examples
el <- matrix(c("foo", "bar", "bar", "foobar"), nc = 2, byrow = TRUE)graph_from_edgelist(el)# Create a ring by handgraph_from_edgelist(cbind(1:10, c(2:10, 1)))Load a graph from the graph database for testing graph isomorphism.
Description
This function downloads a graph from a database created for the evaluationof graph isomorphism testing algorithms.
Usage
graph_from_graphdb( url = NULL, prefix = "iso", type = "r001", nodes = NULL, pair = "A", which = 0, base = "https://github.com/igraph/graphsdb/raw/refs/heads/main", compressed = TRUE, directed = TRUE)Arguments
url | If not |
prefix | Gives the prefix. See details below. Possible values: |
type | Gives the graph type identifier. See details below. Possiblevalues: |
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 typethere are a number of actual graphs in the database. This argument specifieswhich one to read. |
base | The base address of the database. See details below. |
compressed | Logical constant, if TRUE than the file is expected to becompressed by gzip. If |
directed | Logical constant, whether to create a directed graph. |
Details
graph_from_graphdb() reads a graph from the graph database from an FTP orHTTP server or from a local copy. It has two modes of operation:
If theurl argument is specified then it should the complete path toa local or remote graph database file. In this case we simply callread_graph() with the proper arguments to read the file.
Ifurl isNULL, and this is the default, then the filename isassembled from thebase,prefix,type,nodes,pair andwhich arguments.
Unfortunately the original graph database homepage is now defunct, but seeits old version athttps://web.archive.org/web/20090215182331/http://amalfi.dis.unina.it/graph/db/doc/graphdbat.htmlfor the actual format of a graph database file and other information.
Value
A new graph object.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
M. De Santo, P. Foggia, C. Sansone, M. Vento: A large databaseof graphs and its use for benchmarking graph isomorphism algorithms,Pattern Recognition Letters, Volume 24, Issue 8 (May 2003)
See Also
Foreign format readersread_graph(),write_graph()
Convert graphNEL objects from the graph package to igraph
Description
The graphNEL class is defined in thegraph package, it is anotherway to represent graphs.graph_from_graphnel() takes a graphNELgraph and converts it to an igraph graph. It handles allgraph/vertex/edge attributes. If the graphNEL graph has a vertexattribute called ‘name’ it will be used as igraph vertexattribute ‘name’ and the graphNEL vertex names will beignored.
Usage
graph_from_graphnel(graphNEL, name = TRUE, weight = TRUE, unlist.attrs = TRUE)Arguments
graphNEL | The graphNEL graph. |
name | Logical scalar, whether to add graphNEL vertex names as anigraph vertex attribute called ‘ |
weight | Logical scalar, whether to add graphNEL edge weights as anigraph edge attribute called ‘ |
unlist.attrs | Logical scalar. graphNEL attribute query functionsreturn the values of the attributes in R lists, if this argument is |
Details
Because graphNEL graphs poorly support multiple edges, the edgeattributes of the multiple edges are lost: they are all replaced by theattributes of the first of the multiple edges.
Value
graph_from_graphnel() returns an igraph graph object.
See Also
as_graphnel() for the other direction,as_adjacency_matrix(),graph_from_adjacency_matrix(),as_adj_list() andgraph_from_adj_list() for othergraph 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()
Examples
## Undirectedg <- make_ring(10)V(g)$name <- letters[1:10]GNEL <- as_graphnel(g)g2 <- graph_from_graphnel(GNEL)g2## Directedg3 <- make_star(10, mode = "in")V(g3)$name <- letters[1:10]GNEL2 <- as_graphnel(g3)g4 <- graph_from_graphnel(GNEL2)g4From incidence matrix
Description
graph_from_incidence_matrix() was renamed tograph_from_biadjacency_matrix() to create a moreconsistent API.
Usage
graph_from_incidence_matrix(...)Details
Some authors refer to the bipartite adjacency matrix as the"bipartite incidence matrix". igraph 1.6.0 and later does not usethis naming to avoid confusion with the edge-vertex incidence matrix.
Create a graph from an isomorphism class
Description
The isomorphism class is a non-negative integer number.Graphs (with the same number of vertices) having the same isomorphismclass are isomorphic and isomorphic graphs always have the sameisomorphism class. Currently it can handle directed graphs with 3 or 4vertices and undirected graphd with 3 to 6 vertices.
Usage
graph_from_isomorphism_class(size, number, directed = TRUE)Arguments
size | The number of vertices in the graph. |
number | The isomorphism class. |
directed | Whether to create a directed graph (the default). |
Value
An igraph object, the graph of the given size, directednessand isomorphism class.
Related documentation in the C library
See Also
Other graph isomorphism:canonical_permutation(),count_isomorphisms(),count_subgraph_isomorphisms(),isomorphic(),isomorphism_class(),isomorphisms(),subgraph_isomorphic(),subgraph_isomorphisms()
Creating a graph from LCF notation
Description
LCF is short for Lederberg-Coxeter-Frucht, it is a concise notation for3-regular Hamiltonian graphs. It constists of three parameters, the numberof vertices in the graph, a list of shifts giving additional edges to acycle backbone and another integer giving how many times the shifts shouldbe performed.Seehttps://mathworld.wolfram.com/LCFNotation.html for details.
Usage
graph_from_lcf(shifts, ..., n = NULL, repeats = 1L)Arguments
shifts | Integer vector, the shifts. |
... | These dots are for future extensions and must be empty. |
n | Integer, the number of vertices in the graph. If |
repeats | Integer constant, how many times to repeat the shifts. |
Value
A graph object.
Related documentation in the C library
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
make_graph() can create arbitrary graphs, see also the otherfunctions on the its manual page for creating special graphs.
Examples
# This is the Franklin graph:g1 <- graph_from_lcf(shifts = c(5L, -5L), n = 12L, repeats = 6L)g2 <- make_graph("Franklin")isomorphic(g1, g2)Creating (small) graphs via a simple interface
Description
This function is useful if you want to create a small (named) graphquickly, it works for both directed and undirected graphs.
Usage
graph_from_literal(..., simplify = TRUE)from_literal(...)Arguments
... | For |
simplify | Logical scalar, whether to call |
Details
graph_from_literal() is very handy for creating small graphs quickly.You need to supply one or more R expressions giving the structure ofthe graph. The expressions consist of vertex names and edgeoperators. An edge operator is a sequence of ‘-’ and‘+’ characters, the former is for the edges and thelatter 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 ‘-’ charactersthen the graph will be undirected, whereas a single ‘+’character implies a directed graph.
Let us see some simple examples. Without arguments the functioncreates 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 couldhave written the following, this creates the same graph:
graph_from_literal( A-----B )
If you have many disconnected components in the graph, separate themwith 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. Ifan edge operator connects two vertex sets then every vertex from thefirst set will be connected to every vertex in the second set. Thefollowing 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 operatorincludes 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 verticesBandC.
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 ‘+-----+’ haveexactly the same meaning.
If the vertex names include spaces or other special characters thenyou 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.
Value
An igraph graph
See Also
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()
Examples
# A simple undirected graphg <- graph_from_literal( Alice - Bob - Cecil - Alice, Daniel - Cecil - Eugene, Cecil - Gordon)g# Another undirected graph, ":" notationg2 <- graph_from_literal(Alice - Bob:Cecil:Daniel, Cecil:Daniel - Eugene:Gordon)g2# A directed graphg3 <- graph_from_literal( Alice +-+ Bob --+ Cecil +-- Daniel, Eugene --+ Gordon:Helen)g3# A graph with isolate verticesg4 <- graph_from_literal(Alice -- Bob -- Daniel, Cecil:Gordon, Helen)g4V(g4)$name# "Arrows" can be arbitrarily longg5 <- graph_from_literal(Alice +---------+ Bob)g5# Special vertex namesg6 <- graph_from_literal("+" -- "-", "*" -- "/", "%%" -- "%/%")g6Get the id of a graph
Description
Graph ids are used to check that a vertex or edge sequencebelongs to a graph. If you create a new graph by changing thestructure of a graph, the new graph will have a new id.Changing the attributes will not change the id.
Usage
graph_id(x, ...)Arguments
x | A graph or a vertex sequence or an edge sequence. |
... | Not used currently. |
Value
The id of the graph, a character scalar. Forvertex and edge sequences the id of the graph they were created from.
Examples
g <- make_ring(10)graph_id(g)graph_id(V(g))graph_id(E(g))g2 <- g + 1graph_id(g2)igraph data structure versions
Description
igraph's internal data representation changes sometimes betweenversions. This means that it is not always possible to use igraph objectsthat were created (and possibly saved to a file) with an olderigraph version.
Usage
graph_version(graph)Arguments
graph | The input graph. If it is missing, thenthe version number of the current data format is returned. |
Details
graph_version() queries the current data format,or the data format of a possibly older igraph graph.
upgrade_graph() can convert an older data formatto the current one.
Value
An integer scalar.
See Also
upgrade_graph to convert the data format of a graph.
Other versions:upgrade_graph()
Graphlet decomposition of a graph
Description
Graphlet decomposition models a weighted undirected graph via the union ofpotentially overlapping dense social groups. This is done by a two-stepalgorithm. In the first step a candidate set of groups (a candidate basis)is created by finding cliques if the thresholded input graph. In the secondstep these the graph is projected on the candidate basis, resulting a weightcoefficient for each clique in the candidate basis.
Usage
graphlet_basis(graph, weights = NULL)graphlet_proj( graph, weights = NULL, cliques, niter = 1000, Mu = rep(1, length(cliques)))graphlets(graph, weights = NULL, niter = 1000)Arguments
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 theprojection. |
niter | Integer scalar, the number of iterations to perform. |
Mu | Starting weights for the projection. |
Details
igraph contains three functions for performing the graph decomponsition of agraph. The first isgraphlets(), which performed both steps on themethod and returns a list of subgraphs, with their corresponding weights.The second and third functions correspond to the first and second steps ofthe algorithm, and they are useful if the user wishes to perform themindividually:graphlet_basis() andgraphlet_proj().
Value
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 graphletbasis subgraphs.
Related documentation in the C library
Examples
## Create an example graph firstD1 <- matrix(0, 5, 5)D2 <- matrix(0, 5, 5)D3 <- matrix(0, 5, 5)D1[1:3, 1:3] <- 2D2[3:5, 3:5] <- 3D3[2:5, 2:5] <- 1g <- simplify(graph_from_adjacency_matrix(D1 + D2 + D3, mode = "undirected", weighted = TRUE))V(g)$color <- "white"E(g)$label <- E(g)$weightE(g)$label.cex <- 2E(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 graphletsgl <- graphlets(g, niter = 1000)## Plot graphletsfor (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)}Graphlet decomposition of a graph
Description
graphlets.candidate.basis() was renamed tographlet_basis() to create a moreconsistent API.
Usage
graphlets.candidate.basis(graph, weights = NULL)Arguments
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 |
Graphlet decomposition of a graph
Description
graphlets.project() was renamed tographlet_proj() to create a moreconsistent API.
Usage
graphlets.project( graph, weights = NULL, cliques, niter = 1000, Mu = rep(1, length(cliques)))Arguments
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 theprojection. |
niter | Integer scalar, the number of iterations to perform. |
Mu | Starting weights for the projection. |
Greedy vertex coloring
Description
greedy_vertex_coloring() finds a coloring for the vertices of a graphbased on a simple greedy algorithm.
Usage
greedy_vertex_coloring(graph, heuristic = c("colored_neighbors", "dsatur"))Arguments
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 thelargest number of already colored neighbors. “dsatur” selects thevertex with the largest number of unique colors in its neighborhood, i.e.its "saturation degree"; when there are several maximum saturation degreevertices, the one with the most uncolored neighbors will be selected. |
Details
The goal of vertex coloring is to assign a "color" (represented as a positiveinteger) to each vertex of the graph such that neighboring vertices neverhave the same color. This function solves the problem by considering thevertices one by one according to a heuristic, always choosing the smallestcolor that differs from that of already colored neighbors. The coloringobtained this way is not necessarily minimum but it can be calculated inlinear time.
Value
A numeric vector where itemi contains the color indexassociated to vertexi.
Related documentation in the C library
Examples
g <- make_graph("petersen")col <- greedy_vertex_coloring(g)plot(g, vertex.color = col)Geometric random graphs
Description
grg.game() was renamed tosample_grg() to create a moreconsistent API.
Usage
grg.game(nodes, radius, torus = FALSE, coords = FALSE)Arguments
nodes | The number of vertices in the graph. |
radius | The radius within which the vertices will be connected by anedge. |
torus | Logical constant, whether to use a torus instead of a square. |
coords | Logical scalar, whether to add the positions of the verticesas vertex attributes called ‘ |
Groups of a vertex partitioning
Description
Create a list of vertex groups from some graph clustering or communitystructure.
Usage
groups(x)Arguments
x | Some object that represents a grouping of the vertices. See detailsbelow. |
Details
Currently two methods are defined for this function. The default methodworks on the output ofcomponents(). (In fact it works on anyobject that is a list with an entry calledmembership.)
The second method works oncommunities() objects.
Value
A named list of numeric or character vectors. The names are justnumbers that refer to the groups. The vectors themselves are numeric orsymbolic vertex ids.
See Also
components() and the various community findingfunctions.
Community detectionas_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()
Examples
g <- make_graph("Zachary")fgc <- cluster_fast_greedy(g)groups(fgc)g2 <- make_ring(10) + make_full_graph(5)groups(components(g2))Growing random graph generation
Description
growing.random.game() was renamed tosample_growing() to create a moreconsistent API.
Usage
growing.random.game(n, m = 1, directed = TRUE, citation = FALSE)Arguments
n | Numeric constant, number of vertices in the graph. |
m | Numeric constant, number of edges added in each time step. |
directed | Logical, whether to create a directed graph. |
citation | Logical. If |
The size of the graph (number of edges)
Description
ecount() andgsize() are aliases.
Usage
gsize(graph)ecount(graph)Arguments
graph | The graph. |
Value
Numeric scalar, the number of edges.
See Also
Other structural queries:[.igraph(),[[.igraph(),adjacent_vertices(),are_adjacent(),ends(),get_edge_ids(),gorder(),head_of(),incident(),incident_edges(),is_directed(),neighbors(),tail_of()
Examples
g <- sample_gnp(100, 2 / 100)gsize(g)ecount(g)# Number of edges in a G(n,p) graphreplicate(100, sample_gnp(10, 1 / 2), simplify = FALSE) %>% vapply(gsize, 0) %>% hist()Harmonic centrality of vertices
Description
The harmonic centrality of a vertex is the mean inverse distance to all othervertices. The inverse distance to an unreachable vertex is considered to be zero.
Usage
harmonic_centrality( graph, vids = V(graph), mode = c("out", "in", "all", "total"), weights = NULL, normalized = FALSE, cutoff = -1)Arguments
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 formeasuring the distance in directed graphs. “out” follows paths alongthe edge directions only, “in” traverses the edges in reverse, while“all” ignores edge directions. This argument is ignored for undirectedgraphs. |
weights | Optional positive weight vector for calculating weightedharmonic centrality. If the graph has a |
normalized | Logical scalar, whether to calculate the normalizedharmonic centrality. If true, the result is the mean inverse path length toother 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 theharmonic centrality. There is no such limit when the cutoff is negative. Note thatzero cutoff means that only paths of at most length 0 are considered. |
Details
Thecutoff argument can be used to restrict the calculation to pathsof lengthcutoff or smaller only; this can be used for larger graphsto speed up the calculation. Ifcutoff is negative (which is thedefault), then the function calculates the exact harmonic centrality scores.
Value
Numeric vector with the harmonic centrality scores of all the vertices inv.
Related documentation in the C library
References
M. Marchiori and V. Latora, Harmony in the small-world,Physica A 285, pp. 539-546 (2000).
See Also
Centrality measuresalpha_centrality(),authority_score(),betweenness(),closeness(),diversity(),eigen_centrality(),hits_scores(),page_rank(),power_centrality(),spectrum(),strength(),subgraph_centrality()
Examples
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")Find the multiple or loop edges in a graph
Description
has.multiple() was renamed toany_multiple() to create a moreconsistent API.
Usage
has.multiple(graph)Arguments
graph | The input graph. |
Find Eulerian paths or cycles in a graph
Description
has_eulerian_path() andhas_eulerian_cycle() checks whether thereis an Eulerian path or cycle in the input graph.eulerian_path() andeulerian_cycle() return such a path or cycle if it exists, and throwsan error otherwise.
Usage
has_eulerian_path(graph)has_eulerian_cycle(graph)eulerian_path(graph)eulerian_cycle(graph)Arguments
graph | An igraph graph object |
Details
has_eulerian_path() decides whether the input graph has an Eulerianpath, i.e. a path that passes through every edge of the graph exactlyonce, and returns a logical value as a result.eulerian_path() returnsa possible Eulerian path, described with its edge and vertex sequence, orthrows an error if no such path exists.
has_eulerian_cycle() decides whether the input graph has an Euleriancycle, i.e. a path that passes through every edge of the graph exactlyonce and that returns to its starting point, and returns a logical value asa result.eulerian_cycle() returns a possible Eulerian cycle, describedwith its edge and vertex sequence, or throws an error if no such cycle exists.
Value
Forhas_eulerian_path() andhas_eulerian_cycle(), a logicalvalue that indicates whether the graph contains an Eulerian path or cycle.Foreulerian_path() andeulerian_cycle(), a named list with twoentries:
- 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.
Related documentation in the C library
is_eulerian(),eulerian_path(),eulerian_cycle().
See Also
Graph cyclesfeedback_arc_set(),feedback_vertex_set(),find_cycle(),girth(),is_acyclic(),is_dag(),simple_cycles()
Examples
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))Head of the edge(s) in a graph
Description
For undirected graphs, head and tail is not defined. In this casehead_of() returns vertices incident to the supplied edges, andtail_of() returns the other end(s) of the edge(s).
Usage
head_of(graph, es)Arguments
graph | The input graph. |
es | The edges to query. |
Value
A vertex sequence with the head(s) of the edge(s).
See Also
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
Description
Print the only the head of an R object
Usage
head_print( x, max_lines = 20, header = "", footer = "", omitted_footer = "", ...)Arguments
x | The object to print, or a callback function. See |
max_lines | Maximum number of lines to print,notincluding 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 anythingis omitted from the printout. If a function, then it will be called,otherwise printed using |
... | Extra arguments to pass to |
Value
x, invisibly.
Kleinberg's hub and authority centrality scores.
Description
The hub scores of the vertices are defined as the principal eigenvectorofA A^T, whereA is the adjacency matrix of thegraph.
Usage
hits_scores( graph, ..., scale = TRUE, weights = NULL, options = arpack_defaults())Arguments
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 maximumscore of one. If no scaling is used then the result vector has unit lengthin the Euclidean norm. |
weights | Optional positive weight vector for calculating weightedscores. If the graph has a |
options | A named list, to override some ARPACK options. See |
Details
Similarly, the authority scores of the vertices are defined as the principaleigenvector ofA^T A, whereA is the adjacency matrix ofthe graph.
For undirected matrices the adjacency matrix is symmetric and the hubscores are the same as authority scores.
Value
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
optionsmember returned byarpack(), see that for documentation.
Related documentation in the C library
References
J. Kleinberg. Authoritative sources in a hyperlinkedenvironment.Proc. 9th ACM-SIAM Symposium on Discrete Algorithms,1998. Extended version inJournal of the ACM 46(1999). Also appearsas IBM Research Report RJ 10076, May 1997.
See Also
eigen_centrality() for eigenvector centrality,page_rank() for the Page Rank scores.arpack() forthe underlining machinery of the computation.
Centrality measuresalpha_centrality(),authority_score(),betweenness(),closeness(),diversity(),eigen_centrality(),harmonic_centrality(),page_rank(),power_centrality(),spectrum(),strength(),subgraph_centrality()
Examples
## An in-starg <- make_star(10)hits_scores(g)## A ringg2 <- make_ring(10)hits_scores(g2)Create a hierarchical random graph from an igraph graph
Description
hrg() creates a HRG from an igraph graph. The igraph graph must bea directed binary tree, withn-1 internal andn leafvertices. Theprob argument contains the HRG probability labelsfor each vertex; these are ignored for leaf vertices.
Usage
hrg(graph, prob)Arguments
graph | The igraph graph to create the HRG from. |
prob | A vector of probabilities, one for each vertex, in the order ofvertex ids. |
Value
hrg() returns anigraphHRG object.
Related documentation in the C library
See Also
Other hierarchical random graph functions:consensus_tree(),fit_hrg(),hrg-methods,hrg_tree(),predict_edges(),print.igraphHRG(),print.igraphHRGConsensus(),sample_hrg()
Hierarchical random graphs
Description
Fitting and sampling hierarchical random graph models.
Details
A hierarchical random graph is an ensemble of undirected graphs withnvertices. It is defined via a binary tree withn leaf andn-1internal vertices, where the internal vertices are labeled withprobabilities. The probability that two vertices are connected in therandom graph is given by the probability label at their closest commonancestor.
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 setof sampled HRGs (consensus_tree()) and for predicting missing edges ina network based on its HRG models (predict_edges()).
The igraph HRG implementation is heavily based on the code published byAaron Clauset, at his website (not functional any more).
See Also
Other hierarchical random graph functions:consensus_tree(),fit_hrg(),hrg(),hrg_tree(),predict_edges(),print.igraphHRG(),print.igraphHRGConsensus(),sample_hrg()
Create a consensus tree from several hierarchical random graph models
Description
hrg.consensus() was renamed toconsensus_tree() to create a moreconsistent API.
Usage
hrg.consensus(graph, hrg = NULL, start = FALSE, num.samples = 10000)Arguments
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 thesupplied |
num.samples | Number of samples to use for consensus generation ormissing edge prediction. |
Create a hierarchical random graph from an igraph graph
Description
hrg.create() was renamed tohrg() to create a moreconsistent API.
Usage
hrg.create(graph, prob)Arguments
graph | The igraph graph to create the HRG from. |
prob | A vector of probabilities, one for each vertex, in the order ofvertex ids. |
Create an igraph graph from a hierarchical random graph model
Description
hrg.dendrogram() was renamed tohrg_tree() to create a moreconsistent API.
Usage
hrg.dendrogram(hrg)Arguments
hrg | A hierarchical random graph model. |
Fit a hierarchical random graph model
Description
hrg.fit() was renamed tofit_hrg() to create a moreconsistent API.
Usage
hrg.fit(graph, hrg = NULL, start = FALSE, steps = 0)Arguments
graph | The graph to fit the model to. Edge directions are ignored indirected graphs. |
hrg | A hierarchical random graph model, in the form of an |
start | Logical, whether to start the fitting/sampling from thesupplied |
steps | The number of MCMC steps to make. If this is zero, then theMCMC procedure is performed until convergence. |
Sample from a hierarchical random graph model
Description
hrg.game() was renamed tosample_hrg() to create a moreconsistent API.
Usage
hrg.game(hrg)Arguments
hrg | A hierarchical random graph model. |
Predict edges based on a hierarchical random graph model
Description
hrg.predict() was renamed topredict_edges() to create a moreconsistent API.
Usage
hrg.predict( graph, hrg = NULL, start = FALSE, num.samples = 10000, num.bins = 25)Arguments
graph | The graph to fit the model to. Edge directions are ignored indirected graphs. |
hrg | A hierarchical random graph model, in the form of an |
start | Logical, whether to start the fitting/sampling from thesupplied |
num.samples | Number of samples to use for consensus generation ormissing edge prediction. |
num.bins | Number of bins for the edge probabilities. Give a highernumber for a more accurate prediction. |
Create an igraph graph from a hierarchical random graph model
Description
hrg_tree() creates the corresponsing igraph tree of a hierarchicalrandom graph model.
Usage
hrg_tree(hrg)Arguments
hrg | A hierarchical random graph model. |
Value
An igraph graph with a vertex attribute called"probability".
Related documentation in the C library
See Also
Other hierarchical random graph functions:consensus_tree(),fit_hrg(),hrg(),hrg-methods,predict_edges(),print.igraphHRG(),print.igraphHRGConsensus(),sample_hrg()
Kleinberg's hub and authority centrality scores.
Description
hub.score() was renamed tohub_score() to create a moreconsistent API.
Usage
hub.score(graph, scale = TRUE, weights = NULL, options = arpack_defaults())Arguments
graph | The input graph. |
scale | Logical scalar, whether to scale the result to have a maximumscore of one. If no scaling is used then the result vector has unit lengthin the Euclidean norm. |
weights | Optional positive weight vector for calculating weightedscores. If the graph has a |
options | A named list, to override some ARPACK options. See |
Decide if two graphs are identical
Description
Two graphs are considered identical by this function if and only ifthey are represented in exactly the same way in the internal Rrepresentation. This means that the two graphs must have the samelist of vertices and edges, in exactly the same order, with samedirectedness, and the two graphs must also have identical graph, vertex andedge attributes.
Usage
identical_graphs(g1, g2, attrs = TRUE)Arguments
g1,g2 | The two graphs |
attrs | Whether to compare the attributes of the graphs |
Details
This is similar toidentical in thebase package,but it ignores the mutable piece of igraph objects; those might bedifferent even if the two graphs are identical.
Attribute comparison can be turned off with theattrs parameter ifthe attributes of the two graphs are allowed to be different.
Value
Logical scalar
How igraph functions handle attributes when the graph changes
Description
Many times, when the structure of a graph is modified, vertices/edges map ofthe original graph map to vertices/edges in the newly created (modified)graph. For examplesimplify() maps multiple edges to singleedges. igraph provides a flexible mechanism to specify what to do with thevertex/edge attributes in these cases.
Details
The functions that support the combination of attributes have one or twoextra arguments calledvertex.attr.comb and/oredge.attr.combthat specify how to perform the mapping of the attributes. E.g.contract() contracts many vertices into a single one, theattributes of the vertices can be combined and stores as the vertexattributes of the new graph.
The specification of the combination of (vertex or edge) attributes can begiven 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 predefinedcombinations, see their list below.
If it is a function, then the given function is expected to perform thecombination. 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 tothat single vertex.
The third option, a list can be used to specify different combinationmethods for different attributes. A named entry of the list corresponds tothe attribute with the same name. An unnamed entry (i.e. if the name is theempty string) of the list specifies the default combination method. I.e.
list(weight="sum", "ignore")
specifies that the weight of thenew edge should be sum of the weights of the corresponding edges in the oldgraph; and that the rest of the attributes should be ignored (=dropped).
Predefined combination functions
The following combinationbehaviors are predefined:
- "ignore"
The attribute is ignored and dropped.
- "sum"
The sum of the attributes is calculated.This does not work for character attributes and works for complex attributesonly if they have a
sumgeneric defined.(E.g. it works for sparse matrices from theMatrixpackage,because they have asummethod.)- "prod"
The product of the attributes is calculated.This does not work for character attributes and works for complex attributesonly if they have a
prodfunction defined.- "min"
The minimum of the attributes is calculated and returned.For character and complex attributes the standard R
minfunction is used.- "max"
The maximum of the attributes is calculated and returned.For character and complex attributes the standard R
maxfunction is used.- "random"
Chooses one of the supplied attribute values, uniformly randomly.For character and complex attributes this is implemented by calling
sample.- "first"
Always chooses the first attribute value.It is implemented by calling the
head()function.- "last"
Always chooses the last attribute value.It is implemented by calling the
tail()function.- "mean"
The mean of the attributes is calculated and returned.For character and complex attributes this simply calls the
mean()function.- "median"
The median of the attributes is selected.Calls the R
median()function for all attribute types.- "concat"
Concatenate the attributes, using the
c()function.This results almost always a complex attribute.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
graph_attr(),vertex_attr(),edge_attr() on how to use graph/vertex/edge attributes ingeneral.igraph_options() on igraph parameters.
Vertex, edge and graph attributesdelete_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(),set_vertex_attrs(),vertex_attr(),vertex_attr<-(),vertex_attr_names()
Examples
g <- make_graph(c(1, 2, 1, 2, 1, 2, 2, 3, 3, 4))E(g)$weight <- 1:5## print attribute values with the graphigraph_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 onessimplify(g, edge.attr.comb = "sum")## collect attributes into a stringsimplify(g, edge.attr.comb = toString)## concatenate them into a vector, this creates a complex## attributesimplify(g, edge.attr.comb = "concat")E(g)$name <- letters[seq_len(ecount(g))]## both attributes are collected into stringssimplify(g, edge.attr.comb = toString)## harmonic average of weights, names are droppedsimplify(g, edge.attr.comb = list( weight = function(x) length(x) / sum(1 / x), name = "ignore"))Getting and setting graph attributes, shortcut
Description
The$ operator is a shortcut to get and and setgraph attributes. It is shorter and just as readable asgraph_attr() andset_graph_attr().
Usage
## S3 method for class 'igraph'x$name## S3 replacement method for class 'igraph'x$name <- valueArguments
x | An igraph graph |
name | Name of the attribute to get/set. |
value | New value of the graph attribute. |
See Also
Vertex, edge and graph attributesdelete_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(),set_vertex_attrs(),vertex_attr(),vertex_attr<-(),vertex_attr_names()
Examples
g <- make_ring(10)g$nameg$name <- "10-ring"g$nameQuery or set attributes of the edges in an edge sequence
Description
The$ operator is a syntactic sugar to query and setedge attributes, for edges in an edge sequence.
Usage
## 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 <- valueE(x, path = NULL, P = NULL, directed = NULL) <- valueArguments
x | An edge sequence. For |
i | Index. |
value | New value of the attribute, for the edges in the edgesequence. |
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 |
Details
The query form of$ is a shortcut foredge_attr(),e.g.E(g)[idx]$attr is equivalent toedge_attr(g, attr, E(g)[idx]).
The assignment form of$ is a shortcut forset_edge_attr(), e.g.E(g)[idx]$attr <- value isequivalent tog <- set_edge_attr(g, attr, E(g)[idx], value).
Value
A vector or list, containing the values of the attributename for the edges in the sequence. For numeric, character orlogical attributes, it is a vector of the appropriate type, otherwiseit is a list.
See Also
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()
Examples
# color edges of the largest componentlargest_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)Indexing edge sequences
Description
Edge sequences can be indexed very much like a plain numeric R vector,with some extras.
Usage
## S3 method for class 'igraph.es'x[...]Arguments
x | An edge sequence |
... | Indices, see details below. |
Value
Another edge sequence, referring to the same graph.
Multiple indices
When using multiple indices within the bracket, all of themare evaluated independently, and then the results are concatenatedusing thec() function. E.g.E(g)[1, 2, .inc(1)]is equivalent toc(E(g)[1], E(g)[2], E(g)[.inc(1)]).
Index types
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 thegiven positions in the sequence are selected. This is the same asindexing a regular R atomic vector with positive numeric vectors.
When indexed with negative numeric vectors, the edges at thegiven positions in the sequence are omitted. Again, this is the sameas indexing a regular R atomic vector.
When indexed with a logical vector, the lengths of the edgesequence and the index must match, and the edges for which theindex is
TRUEare selected.Named graphs can be indexed with character vectors,to select edges with the given names. Note that a graph mayhave edge names and vertex names, and both can be used to selectedges. Edge names are simply used as names of the numericedge id vector. Vertex names effectively only work in graphs withoutmultiple edges, and must be separated with a
|bar characterto select an edges that incident to the two given vertices. Seeexamples below.
Edge attributes
When indexing edge sequences, edge attributes can be referredto simply by using their names. E.g. if a graph has aweight edgeattribute, thenE(G)[weight > 1] selects all edges with a weightlarger than one. See more examples below. Note that attribute names mask thenames of variables present in the calling environment; if you need to look upa 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 callingenvironment. In other words, useE(g)[.env$weight > 1] to make surethatweight is looked up from the calling environment even if there isan edge attribute with the same name. Similarly, you can use.data tomatch attribute names only.
Special functions
There are some special igraph functions that can be usedonly in expressions indexing edge sequences:
.inctakes a vertex sequence, and selects all edges that have at least one incident vertex in the vertex sequence.
.fromsimilar to
.inc(), but only the tails of the edges are considered..tois 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 edgesfrom the left hand side argument,pointingto the right hand side argument, are selected, in directed graphs.\%<-\%similar to
\%--\%, but edgesto the left hand side argument,pointingfrom the right hand side argument, are selected, in directed graphs.
Note that multiple special functions can be used together, or withregular indices, and then their results are concatenated. See moreexamples below.
See Also
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()
Examples
# -----------------------------------------------------------------# Special operators for indexing based on graph structureg <- 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 diameterg <- sample_pa(100, directed = FALSE)d <- get_diameter(g)E(g, path = d)# -----------------------------------------------------------------# Select edges based on attributesg <- 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 environmentE(g)$x <- E(g)$weightx <- 2E(g)[.env$x]Select edges and show their metadata
Description
The double bracket operator can be used on edge sequences, to printthe meta-data (edge attributes) of the edges in the sequence.
Usage
## S3 method for class 'igraph.es'x[[...]]Arguments
x | An edge sequence. |
... | Additional arguments, passed to |
Details
Technically, when used with edge sequences, the double bracketoperator does exactly the same as the single bracket operator,but the resulting edge sequence is printed differently: allattributes of the edges in the sequence are printed as well.
See[.igraph.es for more about indexing edge sequences.
Value
Another edge sequence, with metadata printing turned on.See details below.
See Also
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()
Examples
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
Description
Delete vertices or edges from a graph
Usage
## S3 method for class 'igraph'e1 - e2Arguments
e1 | Left argument, see details below. |
e2 | Right argument, see details below. |
Details
The minus operator (‘-’) can be used to remove verticesor edges from the graph. The operation performed is selected based onthe type of the right hand side argument:
If it is an igraph graph object, then the difference of thetwo graphs is calculated, see
difference().If it is a numeric or character vector, then it is interpretedas a vector of vertex ids and the specified vertices will bedeleted from the graph. Example:
g <- make_ring(10)V(g)$name <- letters[1:10]g <- g - c("a", "b")If
e2is a vertex sequence (e.g. created by theV()function), then these vertices will be deleted fromthe 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 thevertices()) function, then all arguments ofvertices()areconcatenated and the result is interpreted as a vector of vertexids. These vertices will be removed from the graph.If it is an object created with the
edge()(or theedges()) function, then all arguments ofedges()areconcatenated and then interpreted as edges to be removed from thegraph.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 allpath()arguments are concatenated and then interpretedas 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")
Value
An igraph graph.
See Also
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()
Query or set attributes of the vertices in a vertex sequence
Description
The$ operator is a syntactic sugar to query and set theattributes of the vertices in a vertex sequence.
Usage
## 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 <- valueV(x) <- valueArguments
x | A vertex sequence. For |
i | Index. |
value | New value of the attribute, for the vertices in thevertex sequence. |
name | Name of the vertex attribute to query or set. |
Details
The query form of$ is a shortcut forvertex_attr(), e.g.V(g)[idx]$attr is equivalenttovertex_attr(g, attr, V(g)[idx]).
The assignment form of$ is a shortcut forset_vertex_attr(), e.g.V(g)[idx]$attr <- value isequivalent tog <- set_vertex_attr(g, attr, V(g)[idx], value).
Value
A vector or list, containing the values ofattributename for the vertices in the vertex sequence.For numeric, character or logical attributes, it is a vector of theappropriate type, otherwise it is a list.
See Also
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 attributesdelete_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(),set_vertex_attrs(),vertex_attr(),vertex_attr<-(),vertex_attr_names()
Examples
g <- make_( ring(10), with_vertex_( name = LETTERS[1:10], color = sample(1:2, 10, replace = TRUE) ))V(g)$nameV(g)$colorV(g)$frame.color <- V(g)$color# color vertices of the largest componentlargest_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)Indexing vertex sequences
Description
Vertex sequences can be indexed very much like a plain numeric R vector,with some extras.
Usage
## S3 method for class 'igraph.vs'x[..., na_ok = FALSE]Arguments
x | A vertex sequence. |
... | Indices, see details below. |
na_ok | Whether it is OK to have |
Details
Vertex sequences can be indexed using both the single bracket andthe double bracket operators, and they both work the same way.The only difference between them is that the double bracket operatormarks the result for printing vertex attributes.
Value
Another vertex sequence, referring to the same graph.
Multiple indices
When using multiple indices within the bracket, all of themare evaluated independently, and then the results are concatenatedusing thec() function (except for thena_ok argument,which is special an must be named. E.g.V(g)[1, 2, .nei(1)]is equivalent toc(V(g)[1], V(g)[2], V(g)[.nei(1)]).
Index types
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 thegiven positions in the sequence are selected. This is the same asindexing a regular R atomic vector with positive numeric vectors.
When indexed with negative numeric vectors, the vertices at thegiven positions in the sequence are omitted. Again, this is the sameas indexing a regular R atomic vector.
When indexed with a logical vector, the lengths of the vertexsequence and the index must match, and the vertices for which theindex is
TRUEare selected.Named graphs can be indexed with character vectors,to select vertices with the given names.
Vertex attributes
When indexing vertex sequences, vertex attributes can be referredto simply by using their names. E.g. if a graph has aname vertexattribute, thenV(g)[name == "foo"] is equivalent toV(g)[V(g)$name == "foo"]. See more examples below. Note that attributenames mask the names of variables present in the calling environment; ifyou need to look up a variable and you do not want a similarly namedvertex attribute to mask it, use the.env pronoun to perform thename lookup in the calling environment. In other words, useV(g)[.env$name == "foo"] to make sure thatname is looked upfrom the calling environment even if there is a vertex attribute with thesame name. Similarly, you can use.data to match attribute names only.
Special functions
There are some special igraph functions that can be used onlyin expressions indexing vertex sequences:
.neitakes a vertex sequence as its argumentand selects neighbors of these vertices.An optional
modeargument can be used to select successors (mode="out"),or predecessors (mode="in") in directed graphs..incTakes an edge sequence as an argument,and selects vertices that have at least one incident edge in this edge sequence.
.fromSimilar to
.inc, but only considers the tails of the edges..toSimilar 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 withregular indices, and then their results are concatenated. See moreexamples below.
See Also
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()
Examples
# -----------------------------------------------------------------# Setting attributes for subsets of verticeslargest_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 functiong <- 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 namesg <- 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 attributesg <- 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 environmentV(g)$x <- 10:13x <- 2V(g)[.env$x]Select vertices and show their metadata
Description
The double bracket operator can be used on vertex sequences, to printthe meta-data (vertex attributes) of the vertices in the sequence.
Usage
## S3 method for class 'igraph.vs'x[[...]]Arguments
x | A vertex sequence. |
... | Additional arguments, passed to |
Details
Technically, when used with vertex sequences, the double bracketoperator does exactly the same as the single bracket operator,but the resulting vertex sequence is printed differently: allattributes of the vertices in the sequence are printed as well.
See[.igraph.vs for more about indexing vertex sequences.
Value
The double bracket operator returns another vertex sequence,with meta-data (attribute) printing turned on. See details below.
See Also
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()
Examples
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]]The igraph console
Description
igraph.console() was renamed toconsole() to create a moreconsistent API.
Usage
igraph.console()Convert graphNEL objects from the graph package to igraph
Description
igraph.from.graphNEL() was renamed tograph_from_graphnel() to create a moreconsistent API.
Usage
igraph.from.graphNEL(graphNEL, name = TRUE, weight = TRUE, unlist.attrs = TRUE)Arguments
graphNEL | The graphNEL graph. |
name | Logical scalar, whether to add graphNEL vertex names as anigraph vertex attribute called ‘ |
weight | Logical scalar, whether to add graphNEL edge weights as anigraph edge attribute called ‘ |
unlist.attrs | Logical scalar. graphNEL attribute query functionsreturn the values of the attributes in R lists, if this argument is |
Parameters for the igraph package
Description
igraph.options() was renamed toigraph_options() to create a moreconsistent API.
Usage
igraph.options(...)Arguments
... | A list may be given as the only argument, or any number ofarguments may be in the |
Sampling a random integer sequence
Description
igraph.sample() was renamed tosample_seq() to create a moreconsistent API.
Usage
igraph.sample(low, high, length)Arguments
low | The lower limit of the interval (inclusive). |
high | The higher limit of the interval (inclusive). |
length | The length of the sample. |
Various vertex shapes when plotting igraph graphs
Description
igraph.shape.noclip() was renamed toshape_noclip() to create a moreconsistent API.
Usage
igraph.shape.noclip(coords, el, params, end = c("both", "from", "to"))Various vertex shapes when plotting igraph graphs
Description
igraph.shape.noplot() was renamed toshape_noplot() to create a moreconsistent API.
Usage
igraph.shape.noplot(coords, v = NULL, params)Convert igraph graphs to graphNEL objects from the graph package
Description
igraph.to.graphNEL() was renamed toas_graphnel() to create a moreconsistent API.
Usage
igraph.to.graphNEL(graph)Arguments
graph | An igraph graph object. |
Query igraph's version string
Description
igraph.version() was renamed toigraph_version() to create a moreconsistent API.
Usage
igraph.version()Parameters for the igraph package
Description
igraph has some parameters which (usually) affect the behavior of manyfunctions. These can be set for the whole session viaigraph_options().
Usage
igraph_options(...)igraph_opt(x, default = NULL)Arguments
... | A list may be given as the only argument, or any number ofarguments may be in the |
x | A character string holding an option name. |
default | If the specified option is not set in the options list, thisvalue is returned. This facilitates retrieving an option and checkingwhether it is set and setting it separately if not. |
Details
The parameter values set via a call to theigraph_options() functionwill remain in effect for the rest of the session, affecting the subsequentbehaviour of the other functions of theigraph package for which thegiven parameters are relevant.
This offers the possibility of customizing the functioning of theigraph package, for instance by insertions of appropriate calls toigraph_options() in a load hook for packageigraph.
The currently used parameters in alphabetical order:
- add.params
Logical scalar, whether to add model parameter to the graphsthat are created by the various graph constructors.By default it is
TRUE.- add.vertex.names
Logical scalar, whether to add vertex names to node level indices,like degree, betweenness scores, etc.By default it is
TRUE.- annotate.plot
Logical scalar, whether to annotate igraph plotswith the graph's name (
namegraph attribute, if present) asmain,and with the number of vertices and edges asxlab.Defaults toFALSE.- dend.plot.type
The plotting function to use when plotting community structure dendrograms via
plot_dendrogram().Possible values are ‘auto’ (the default), ‘phylo’, ‘hclust’ and ‘dendrogram’.Seeplot_dendrogram()for details.- edge.attr.comb
Specifies what to do with the edge attributes if the graph is modified.The default value is
list(weight="sum", name="concat", "ignore").Seeattribute.combination()for details on this.- print.edge.attributes
Logical constant, whether to print edge attributes when printing graphs.Defaults to
FALSE.- print.full
Logical scalar, whether
print.igraph()should show the graph structure as well,or only a summary of the graph.- print.graph.attributes
Logical constant, whether to print graph attributes when printing graphs. Defaults to
FALSE.- print.vertex.attributes
Logical constant, whether to print vertex attributes when printing graphs. Defaults to
FALSE.- return.vs.es
Whether functions that return a set or sequence of vertices/edgesshould 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
.onLoadfunction of your package,without affecting other packages.- sparsematrices
Whether to use the
Matrixpackage for (sparse) matrices.It is recommended, if the user works with larger graphs.- verbose
Logical constant, whether igraph functions should talk more than minimal.E.g. if
TRUEthen some functions will use progress bars while computing. Defaults toFALSE.- vertex.attr.comb
Specifies what to do with the vertex attributes if the graph is modified.The default value is
list(name="concat", "ignore").Seeattribute.combination()for details on this.
Value
igraph_options() returns a list with the old values of theupdated parameters, invisibly. Without any arguments, it returns thevalues of all options.
Forigraph_opt(), the current value set for optionx, orNULL if the option is unset.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
igraph_options() is similar tooptions() andigraph_opt() is similar togetOption().
Other igraph options:with_igraph_opt()
Examples
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")Query igraph's version string
Description
Returns the R package version,prints the R package version and C library version.
Usage
igraph_version()Value
A character scalar, the igraph version string, with an attribute"c_version" giving the C library version string.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
Examples
igraph_version()Incident edges of a vertex in a graph
Description
Incident edges of a vertex in a graph
Usage
incident(graph, v, mode = c("all", "out", "in", "total"))Arguments
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 isignored for undirected graphs. |
Value
An edge sequence containing the incident edges ofthe input vertex.
See Also
Other structural queries:[.igraph(),[[.igraph(),adjacent_vertices(),are_adjacent(),ends(),get_edge_ids(),gorder(),gsize(),head_of(),incident_edges(),is_directed(),neighbors(),tail_of()
Examples
g <- make_graph("Zachary")incident(g, 1)incident(g, 34)Incident edges of multiple vertices in a graph
Description
This function is similar toincident(), but itqueries multiple vertices at once.
Usage
incident_edges(graph, v, mode = c("out", "in", "all", "total"))Arguments
graph | Input graph. |
v | The vertices to query |
mode | Whether to query outgoing (‘out’), incoming(‘in’) edges, or both types (‘all’). This isignored for undirected graphs. |
Value
A list of edge sequences.
See Also
Other structural queries:[.igraph(),[[.igraph(),adjacent_vertices(),are_adjacent(),ends(),get_edge_ids(),gorder(),gsize(),head_of(),incident(),is_directed(),neighbors(),tail_of()
Examples
g <- make_graph("Zachary")incident_edges(g, c(1, 34))Indent a printout
Description
Indent a printout
Usage
indent_print(..., .indent = " ", .printer = print)Arguments
... | Passed to the printing function. |
.indent | Character scalar, indent the printout with this. |
.printer | The printing function, defaults toprint. |
Value
The first element in..., invisibly.
Independent vertex sets
Description
independence.number() was renamed toivs_size() to create a moreconsistent API.
Usage
independence.number(graph)Arguments
graph | The input graph. |
Independent vertex sets
Description
independent.vertex.sets() was renamed toivs() to create a moreconsistent API.
Usage
independent.vertex.sets(graph, min = NULL, max = NULL)Arguments
graph | The input graph. |
min | Numeric constant, limit for the minimum size of the independentvertex sets to find. |
max | Numeric constant, limit for the maximum size of the independentvertex sets to find. |
Subgraph of a graph
Description
induced.subgraph() was renamed toinduced_subgraph() to create a moreconsistent API.
Usage
induced.subgraph( graph, vids, impl = c("auto", "copy_and_delete", "create_from_scratch"))Arguments
graph | The original graph. |
vids | Numeric vector, the vertices of the original graph which willform the subgraph. |
impl | Character scalar, to choose between two implementation of thesubgraph calculation. ‘ |
Infomap community finding
Description
infomap.community() was renamed tocluster_infomap() to create a moreconsistent API.
Usage
infomap.community( graph, e.weights = NULL, v.weights = NULL, nb.trials = 10, modularity = TRUE)Arguments
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 anyinteger value equal or larger than 1). |
modularity | Logical scalar, whether to calculate the modularity scoreof the detected community structure. |
A graph with subgraphs that are each a random graph.
Description
interconnected.islands.game() was renamed tosample_islands() to create a moreconsistent API.
Usage
interconnected.islands.game(islands.n, islands.size, islands.pin, n.inter)Arguments
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 eachisland. |
n.inter | The number of edges to create between two islands. |
Intersection of two or more sets
Description
This is an S3 generic function. Seemethods("intersection")for the actual implementations for various S3 classes. Initiallyit is implemented for igraph graphs and igraph vertex and edgesequences. Seeintersection.igraph(), andintersection.igraph.vs().
Usage
intersection(...)Arguments
... | Arguments, their number and interpretation depends onthe function that implements |
Value
Depends on the function that implements this method.
See Also
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()
Intersection of graphs
Description
The intersection of two or more graphs are created. The graphs may haveidentical or overlapping vertex sets.
Usage
## S3 method for class 'igraph'intersection(..., byname = "auto", keep.all.vertices = TRUE)Arguments
... | 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 onlyappear in a subset of the input graphs. |
Details
intersection() creates the intersection of two or more graphs:only edges present in all graphs will be included. The correspondingoperator is%s%.
If thebyname argument isTRUE (orauto and all graphsare named), then the operation is performed on symbolic vertex names insteadof 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 ispresent in multiple graphs and would result a name clash, then thisattribute is renamed by adding suffixes: _1, _2, etc.
Thename vertex attribute is treated specially if the operation isperformed based on symbolic vertex names. In this casename must bepresent in all graphs, and it is not renamed in the result graph.
An error is generated if some input graphs are directed and others areundirected.
Value
A new graph object.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
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()
Examples
## Common part of two social networksnet1 <- 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
Description
Intersection of edge sequences
Usage
## S3 method for class 'igraph.es'intersection(...)Arguments
... | The edge sequences to take the intersection of. |
Details
They must belong to the same graph. Note that this function has‘set’ semantics and the multiplicity of edges is lost in theresult.
Value
An edge sequence that contains edges that appear in allgiven sequences, each edge exactly once.
See Also
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()
Examples
g <- make_(ring(10), with_vertex_(name = LETTERS[1:10]))intersection(E(g)[1:6], E(g)[5:9])Intersection of vertex sequences
Description
Intersection of vertex sequences
Usage
## S3 method for class 'igraph.vs'intersection(...)Arguments
... | The vertex sequences to take the intersection of. |
Details
They must belong to the same graph. Note that this function has‘set’ semantics and the multiplicity of vertices is lost in theresult.
Value
A vertex sequence that contains vertices that appear in allgiven sequences, each vertex exactly once.
See Also
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()
Examples
g <- make_(ring(10), with_vertex_(name = LETTERS[1:10]))intersection(E(g)[1:6], E(g)[5:9])Checks whether the graph has a vertex attribute calledtype
Description
is.bipartite() was renamed tois_bipartite() to create a moreconsistent API.
Usage
is.bipartite(graph)Arguments
graph | The input graph |
Chordality of a graph
Description
is.chordal() was renamed tois_chordal() to create a moreconsistent API.
Usage
is.chordal( graph, alpha = NULL, alpham1 = NULL, fillin = FALSE, newgraph = FALSE)Arguments
graph | The input graph. It may be directed, but edge directions areignored, as the algorithm is defined for undirected graphs. |
alpha | Numeric vector, the maximal chardinality ordering of thevertices. 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. |
Connected components of a graph
Description
is.connected() was renamed tois_connected() to create a moreconsistent API.
Usage
is.connected(graph, mode = c("weak", "strong"))Arguments
graph | The graph to analyze. |
mode | Character string, either “weak” or “strong”. Fordirected graphs “weak” implies weakly, “strong” stronglyconnected components to search. It is ignored for undirected graphs. |
Directed acyclic graphs
Description
is.dag() was renamed tois_dag() to create a moreconsistent API.
Usage
is.dag(graph)Arguments
graph | The input graph. It may be undirected, in which case |
Check if a degree sequence is valid for a multi-graph
Description
is.degree.sequence() was renamed tois_degseq() to create a moreconsistent API.
Usage
is.degree.sequence(out.deg, in.deg = NULL)Arguments
out.deg | Integer vector, the degree sequence for undirected graphs, orthe out-degree sequence for directed graphs. |
in.deg |
|
Check whether a graph is directed
Description
is.directed() was renamed tois_directed() to create a moreconsistent API.
Usage
is.directed(graph)Arguments
graph | The input graph |
Is a degree sequence graphical?
Description
is.graphical.degree.sequence() was renamed tois_graphical() to create a moreconsistent API.
Usage
is.graphical.degree.sequence( out.deg, in.deg = NULL, allowed.edge.types = c("simple", "loops", "multi", "all"))Arguments
out.deg | Integer vector, the degree sequence for undirected graphs, orthe 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 besimple). ‘loops’ means that loop edges are allowed but mutiple edgesare not. ‘multi’ means that multiple edges are allowed but loop edgesare not. ‘all’ means that both loop edges and multiple edges areallowed. |
Functions to deal with the result of network community detection
Description
is.hierarchical() was renamed tois_hierarchical() to create a moreconsistent API.
Usage
is.hierarchical(communities)Is this object an igraph graph?
Description
is.igraph() was renamed tois_igraph() to create a moreconsistent API.
Usage
is.igraph(graph)Arguments
graph | An R object. |
Find the multiple or loop edges in a graph
Description
is.loop() was renamed towhich_loop() to create a moreconsistent API.
Usage
is.loop(graph, eids = E(graph))Arguments
graph | The input graph. |
eids | The edges to which the query is restricted. By default this isall edges in the graph. |
Matching
Description
is.matching() was renamed tois_matching() to create a moreconsistent API.
Usage
is.matching(graph, matching, types = NULL)Arguments
graph | The input graph. It might be directed, but edge directions willbe ignored. |
matching | A potential matching. An integer vector that gives thepair in the matching for each vertex. For vertices without a pair,supply |
types | Vertex types, if the graph is bipartite. By default theyare taken from the ‘ |
Matching
Description
is.maximal.matching() was renamed tois_max_matching() to create a moreconsistent API.
Usage
is.maximal.matching(graph, matching, types = NULL)Arguments
graph | The input graph. It might be directed, but edge directions willbe ignored. |
matching | A potential matching. An integer vector that gives thepair in the matching for each vertex. For vertices without a pair,supply |
types | Vertex types, if the graph is bipartite. By default theyare taken from the ‘ |
Minimal vertex separators
Description
is.minimal.separator() was renamed tois_min_separator() to create a moreconsistent API.
Usage
is.minimal.separator(graph, candidate)Arguments
graph | The input graph. It may be directed, but edge directions areignored. |
candidate | A numeric vector giving the vertex ids of the candidateseparator. |
Find the multiple or loop edges in a graph
Description
is.multiple() was renamed towhich_multiple() to create a moreconsistent API.
Usage
is.multiple(graph, eids = E(graph))Arguments
graph | The input graph. |
eids | The edges to which the query is restricted. By default this isall edges in the graph. |
Find mutual edges in a directed graph
Description
is.mutual() was renamed towhich_mutual() to create a moreconsistent API.
Usage
is.mutual(graph, eids = E(graph), loops = TRUE)Arguments
graph | The input graph. |
eids | Edge sequence, the edges that will be probed. By default isincludes all edges in the order of their ids. |
loops | Logical, whether to consider directed self-loops to be mutual. |
Named graphs
Description
is.named() was renamed tois_named() to create a moreconsistent API.
Usage
is.named(graph)Arguments
graph | The input graph. |
Vertex separators
Description
is.separator() was renamed tois_separator() to create a moreconsistent API.
Usage
is.separator(graph, candidate)Arguments
graph | The input graph. It may be directed, but edge directions areignored. |
candidate | A numeric vector giving the vertex ids of the candidateseparator. |
Simple graphs
Description
is.simple() was renamed tois_simple() to create a moreconsistent API.
Usage
is.simple(graph)Arguments
graph | The graph to work on. |
Weighted graphs
Description
is.weighted() was renamed tois_weighted() to create a moreconsistent API.
Usage
is.weighted(graph)Arguments
graph | The input graph. |
Acyclic graphs
Description
This function tests whether the given graph is free of cycles.
Usage
is_acyclic(graph)Arguments
graph | The input graph. |
Details
This function looks for directed cycles in directed graphs and undirectedcycles in undirected graphs. Usefind_cycle() to return a specific cycle.
Value
A logical vector of length one.
Related documentation in the C library
See Also
is_forest() andis_dag() for functions specific to undirectedand directed graphs.
Graph cyclesfeedback_arc_set(),feedback_vertex_set(),find_cycle(),girth(),has_eulerian_path(),is_dag(),simple_cycles()
Other structural.properties:bfs(),component_distribution(),connect(),constraint(),coreness(),degree(),dfs(),distance_table(),edge_density(),feedback_arc_set(),feedback_vertex_set(),girth(),is_dag(),is_matching(),k_shortest_paths(),knn(),reciprocity(),subcomponent(),subgraph(),topo_sort(),transitivity(),unfold_tree(),which_multiple(),which_mutual()
Examples
g <- make_graph(c(1, 2, 1, 3, 2, 4, 3, 4), directed = TRUE)is_acyclic(g)is_acyclic(as_undirected(g))Check biconnectedness
Description
Tests whether a graph is biconnected.
Usage
is_biconnected(graph)Arguments
graph | The input graph. Edge directions are ignored. |
Details
A graph is biconnected if the removal of any single vertex (and its adjacentedges) does not disconnect it.
igraph does not consider single-vertex graphs biconnected.
Note that some authors do not consider the graph consisting oftwo connected vertices as biconnected, however, igraph does.
Value
Logical,TRUE if the graph is biconnected.
Related documentation in the C library
See Also
articulation_points(),biconnected_components(),is_connected(),vertex_connectivity()
Connected componentsarticulation_points(),biconnected_components(),component_distribution(),decompose()
Examples
is_biconnected(make_graph("bull"))is_biconnected(make_graph("dodecahedron"))is_biconnected(make_full_graph(1))is_biconnected(make_full_graph(2))Checks whether the graph has a vertex attribute calledtype.
Description
It does not check whether the graph is bipartite in themathematical sense. Usebipartite_mapping() for that.
Usage
is_bipartite(graph)Arguments
graph | The input graph |
See Also
Bipartite graphsbipartite_mapping(),bipartite_projection(),make_bipartite_graph()
Chordality of a graph
Description
A graph is chordal (or triangulated) if each of its cycles of four or morenodes has a chord, which is an edge joining two nodes that are not adjacentin the cycle. An equivalent definition is that any chordless cycles have atmost three nodes.
Usage
is_chordal( graph, alpha = NULL, alpham1 = NULL, fillin = FALSE, newgraph = FALSE)Arguments
graph | The input graph. It may be directed, but edge directions areignored, as the algorithm is defined for undirected graphs. |
alpha | Numeric vector, the maximal chardinality ordering of thevertices. 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. |
Details
The chordality of the graph is decided by first performing maximumcardinality search on it (if thealpha andalpham1 argumentsareNULL), 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.
Value
A list with three members:
- chordal
Logical scalar, it is
TRUEiff the input graph is chordal.- fillin
If requested, then a numeric vector giving the fill-in edges.
NULLotherwise.- newgraph
If requested, then the triangulated graph, an
igraphobject.NULLotherwise.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
Robert E Tarjan and Mihalis Yannakakis. (1984). Simplelinear-time algorithms to test chordality of graphs, test acyclicity ofhypergraphs, and selectively reduce acyclic hypergraphs.SIAM Journalof Computation 13, 566–579.
See Also
Other chordal:max_cardinality()
Examples
## The examples from the Tarjan-Yannakakis paperg1 <- 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)Is this a complete graph?
Description
A graph is considered complete if there is an edge between all distinctdirected pairs of vertices. igraph considers both the singleton graphand the null graph complete.
Usage
is_complete(graph)Arguments
graph | The input graph. |
Value
True if the graph is complete.
Related documentation in the C library
See Also
Other cliques:cliques(),ivs(),weighted_cliques()
Examples
g <- make_full_graph(6, directed = TRUE)is_complete(g)g <- delete_edges(g, 1)is_complete(g)g <- as_undirected(g)is_complete(g)Directed acyclic graphs
Description
This function tests whether the given graph is a DAG, a directed acyclicgraph.
Usage
is_dag(graph)Arguments
graph | The input graph. It may be undirected, in which case |
Details
is_dag() checks whether there is a directed cycle in the graph. If not,the graph is a DAG.
Value
A logical vector of length one.
Related documentation in the C library
Author(s)
Tamas Nepuszntamas@gmail.com for the C code, Gabor Csardicsardi.gabor@gmail.com for the R interface.
See Also
Graph cyclesfeedback_arc_set(),feedback_vertex_set(),find_cycle(),girth(),has_eulerian_path(),is_acyclic(),simple_cycles()
Other structural.properties:bfs(),component_distribution(),connect(),constraint(),coreness(),degree(),dfs(),distance_table(),edge_density(),feedback_arc_set(),feedback_vertex_set(),girth(),is_acyclic(),is_matching(),k_shortest_paths(),knn(),reciprocity(),subcomponent(),subgraph(),topo_sort(),transitivity(),unfold_tree(),which_multiple(),which_mutual()
Examples
g <- make_tree(10)is_dag(g)g2 <- g + edge(5, 1)is_dag(g2)Check if a degree sequence is valid for a multi-graph
Description
is_degseq() checks whether the given vertex degrees (in- andout-degrees for directed graphs) can be realized by a graph. Note that thegraph 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 twodegree vectors are equal and whether their sums are also equal. These areknown sufficient and necessary conditions for a degree sequence to be valid.
Usage
is_degseq(out.deg, in.deg = NULL)Arguments
out.deg | Integer vector, the degree sequence for undirected graphs, orthe out-degree sequence for directed graphs. |
in.deg |
|
Value
A logical scalar.
Author(s)
Tamás Nepuszntamas@gmail.com and Szabolcs Horvátszhorvat@gmail.com
References
Z Király, Recognizing graphic degree sequences and generatingall 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).
See Also
Other graphical degree sequences:is_graphical()
Examples
g <- sample_gnp(100, 2 / 100)is_degseq(degree(g))is_graphical(degree(g))Check whether a graph is directed
Description
Check whether a graph is directed
Usage
is_directed(graph)Arguments
graph | The input graph |
Value
Logical scalar, whether the graph is directed.
See Also
Other structural queries:[.igraph(),[[.igraph(),adjacent_vertices(),are_adjacent(),ends(),get_edge_ids(),gorder(),gsize(),head_of(),incident(),incident_edges(),neighbors(),tail_of()
Examples
g <- make_ring(10)is_directed(g)g2 <- make_ring(10, directed = TRUE)is_directed(g2)Decide whether a graph is a forest.
Description
is_forest() decides whether a graph is a forest, and optionally returns aset of possible root vertices for its components.
Usage
is_forest(graph, mode = c("out", "in", "all", "total"), details = FALSE)Arguments
graph | An igraph graph object |
mode | Whether to consider edge directions in a directed graph.‘all’ ignores edge directions; ‘out’ requires edges to beoriented outwards from the root, ‘in’ requires edges to be orientedtowards the root. |
details | Whether to return only whether the graph is a tree ( |
Details
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 orientedaway from the root (out-trees or arborescences) or all edges are orientedtowards the root (in-trees or anti-arborescences). This test can becontrolled using the mode parameter.
By convention, the null graph (i.e. the graph with no vertices) is consideredto be a forest.
Value
Whendetails isFALSE, a logical value that indicateswhether the graph is a tree. Whendetails isTRUE, a namedlist 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.
Related documentation in the C library
See Also
Other trees:is_tree(),make_from_prufer(),sample_spanning_tree(),to_prufer()
Examples
g <- make_tree(3) + make_tree(5, 3)is_forest(g)is_forest(g, details = TRUE)Is a degree sequence graphical?
Description
Determine whether the given vertex degrees (in- and out-degrees fordirected graphs) can be realized by a graph.
Usage
is_graphical( out.deg, in.deg = NULL, allowed.edge.types = c("simple", "loops", "multi", "all"))Arguments
out.deg | Integer vector, the degree sequence for undirected graphs, orthe 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 besimple). ‘loops’ means that loop edges are allowed but mutiple edgesare not. ‘multi’ means that multiple edges are allowed but loop edgesare not. ‘all’ means that both loop edges and multiple edges areallowed. |
Details
The classical concept of graphicality assumes simple graphs. This functioncan perform the check also when self-loops, multi-edges, or both are allowedin the graph.
Value
A logical scalar.
Related documentation in the C library
Author(s)
Tamás Nepuszntamas@gmail.com
References
Hakimi SL: On the realizability of a set of integers as degreesof 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 torealize graphical degree sequences of directed graphs.The ElectronicJournal of Combinatorics 17(1):R66, 2010.
See Also
Other graphical degree sequences:is_degseq()
Examples
g <- sample_gnp(100, 2 / 100)is_degseq(degree(g))is_graphical(degree(g))Is this object an igraph graph?
Description
Is this object an igraph graph?
Usage
is_igraph(graph)Arguments
graph | An R object. |
Value
A logical constant,TRUE if argumentgraph is a graphobject.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
Examples
g <- make_ring(10)is_igraph(g)is_igraph(numeric(10))Matching
Description
A matching in a graph means the selection of a set of edges that arepairwise non-adjacent, i.e. they have no common incident vertices. Amatching is maximal if it is not a proper subset of any other matching.
Usage
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)Arguments
graph | The input graph. It might be directed, but edge directions willbe ignored. |
matching | A potential matching. An integer vector that gives thepair in the matching for each vertex. For vertices without a pair,supply |
types | Vertex types, if the graph is bipartite. By default theyare taken from the ‘ |
weights | Potential edge weights. If the graph has an edgeattribute called ‘ |
eps | A small real number used in equality tests in the weightedbipartite matching algorithm. Two real numbers are considered equal inthe algorithm if their difference is smaller than |
Details
is_matching() checks a matching vector and verifies whether itslength matches the number of vertices in the given graph, its values arebetween zero (inclusive) and the number of vertices (inclusive), andwhether there exists a corresponding edge in the graph for every matchedvertex pair. For bipartite graphs, it also verifies whether the matchedvertices are in different parts of the graph.
is_max_matching() checks whether a matching is maximal. A matchingis maximal if and only if there exists no unmatched vertex in a graphsuch that one of its neighbors is also unmatched.
max_bipartite_match() calculates a maximum matching in a bipartitegraph. A matching in a bipartite graph is a partial assignment ofvertices of the first kind to vertices of the second kind such that eachvertex of the first kind is matched to at most one vertex of the secondkind and vice versa, and matched vertices must be connected by an edgein the graph. The size (or cardinality) of a matching is the number ofedges. A matching is a maximum matching if there exists no othermatching with larger cardinality. For weighted graphs, a maximummatching is a matching whose edges have the largest possible totalweight among all possible matchings.
Maximum matchings in bipartite graphs are found by the push-relabelalgorithm with greedy initialization and a global relabeling after everyn/2 steps wheren is the number of vertices in the graph.
Value
is_matching() andis_max_matching() return a logicalscalar.
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
NA.
Author(s)
Tamas Nepuszntamas@gmail.com
See Also
Other structural.properties:bfs(),component_distribution(),connect(),constraint(),coreness(),degree(),dfs(),distance_table(),edge_density(),feedback_arc_set(),feedback_vertex_set(),girth(),is_acyclic(),is_dag(),k_shortest_paths(),knn(),reciprocity(),subcomponent(),subgraph(),topo_sort(),transitivity(),unfold_tree(),which_multiple(),which_mutual()
Examples
g <- graph_from_literal(a - b - c - d - e - f)m1 <- c("b", "a", "d", "c", "f", "e") # maximal matchingm2 <- c("b", "a", "d", "c", NA, NA) # non-maximal matchingm3 <- c("b", "c", "d", "c", NA, NA) # not a matchingis_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 graphsMinimal vertex separators
Description
Check whether a given set of vertices is a minimal vertex separator.
Usage
is_min_separator(graph, candidate)Arguments
graph | The input graph. It may be directed, but edge directions areignored. |
candidate | A numeric vector giving the vertex ids of the candidateseparator. |
Details
is_min_separator() decides whether the supplied vertex set is a minimalvertex separator. A minimal vertex separator is a vertex separator, suchthat none of its proper subsets are a vertex separator.
Value
A logical scalar, whether the supplied vertex set is a (minimal)vertex separator or not.
Related documentation in the C library
See Also
Other flow:dominator_tree(),edge_connectivity(),is_separator(),max_flow(),min_cut(),min_separators(),min_st_separators(),st_cuts(),st_min_cuts(),vertex_connectivity()
Examples
# The graph from the Moody-White papermw <- 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 subgraphsmw1 <- 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)Named graphs
Description
An igraph graph is named, if there is a symbolic name associated with itsvertices.
Usage
is_named(graph)Arguments
graph | The input graph. |
Details
In igraph vertices can always be identified and specified via their numericvertex ids. This is, however, not always convenient, and in many cases thereexist symbolic ids that correspond to the vertices. To allow this moreflexible identification of vertices, one can assign a vertex attributecalled ‘name’ to an igraph graph. After doing this, the symbolicvertex names can be used in all igraph functions, instead of the numericids.
Note that the uniqueness of vertex names are currently not enforced inigraph, you have to check that for yourself, when assigning the vertexnames.
Value
A logical scalar.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
Examples
g <- make_ring(10)is_named(g)V(g)$name <- letters[1:10]is_named(g)neighbors(g, "a")Is this a printer callback?
Description
Is this a printer callback?
Usage
is_printer_callback(x)Arguments
x | An R object. |
See Also
Other printer callbacks:printer_callback()
Check whether removing this set of vertices would disconnect the graph.
Description
is_separator() determines whether the supplied vertex set is a vertexseparator:A vertex setS is a separator if there are verticesu andvin the graph such that all paths betweenu andv passthrough some vertices inS.
Usage
is_separator(graph, candidate)Arguments
graph | The input graph. It may be directed, but edge directions areignored. |
candidate | A numeric vector giving the vertex ids of the candidateseparator. |
Value
A logical scalar, whether the supplied vertex set is a (minimal)vertex separator or not.lists all vertex separator of minimum size.
Related documentation in the C library
See Also
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()
Examples
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))Decide whether a graph is a tree.
Description
is_tree() decides whether a graph is a tree, and optionally returns apossible root vertex if the graph is a tree.
Usage
is_tree(graph, mode = c("out", "in", "all", "total"), details = FALSE)Arguments
graph | An igraph graph object |
mode | Whether to consider edge directions in a directed graph.‘all’ ignores edge directions; ‘out’ requires edges to beoriented outwards from the root, ‘in’ requires edges to be orientedtowards the root. |
details | Whether to return only whether the graph is a tree ( |
Details
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 edgesare oriented away from a root (out-tree or arborescence) or all edges areoriented towards a root (in-tree or anti-arborescence). This test can becontrolled using the mode parameter.
By convention, the null graph (i.e. the graph with no vertices) is considerednot to be a tree.
Value
Whendetails isFALSE, a logical value that indicateswhether the graph is a tree. Whendetails isTRUE, a namedlist 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.
Related documentation in the C library
See Also
Other trees:is_forest(),make_from_prufer(),sample_spanning_tree(),to_prufer()
Examples
g <- make_tree(7, 2)is_tree(g)is_tree(g, details = TRUE)Weighted graphs
Description
In weighted graphs, a real number is assigned to each (directed orundirected) edge.
Usage
is_weighted(graph)Arguments
graph | The input graph. |
Details
In igraph edge weights are represented via an edge attribute, called‘weight’. Theis_weighted() function only checks that such anattribute exists. (It does not even checks that it is a numeric edgeattribute.)
Edge weights are used for different purposes by the different functions.E.g. shortest path functions use it as the cost of the path; communityfinding methods use it as the strength of the relationship between twovertices, etc. Check the manual pages of the functions working with weightedgraphs for details.
Value
A logical scalar.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
Examples
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
Description
Decide if two graphs are isomorphic
Usage
isomorphic(graph1, graph2, method = c("auto", "direct", "vf2", "bliss"), ...)is_isomorphic_to( graph1, graph2, method = c("auto", "direct", "vf2", "bliss"), ...)Arguments
graph1 | The first graph. |
graph2 | The second graph. |
method | The method to use. Possible values: ‘auto’,‘direct’, ‘vf2’, ‘bliss’. See their detailsbelow. |
... | Additional arguments, passed to the various methods. |
Value
Logical scalar,TRUE if the graphs are isomorphic.
‘auto’ method
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 isused.
Otherwise the ‘bliss’ method is used.
‘direct’ method
This method only works on graphs with three or four vertices,and it is based on a pre-calculated and stored table. It does nothave any extra arguments.
‘vf2’ method
This method uses the VF2 algorithm by Cordella, Foggia et al., seereferences below. It supports vertex and edge colors and have thefollowing extra arguments:
- vertex.color1, vertex.color2
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
NULLfor both of these arguments.See also examples below.- edge.color1, edge.color2
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
NULLfor both of these arguments.
‘bliss’ method
Uses the BLISS algorithm by Junttila and Kaski, and it works forundirected graphs. For both graphs thecanonical_permutation() and then thepermute()function is called to transfer them into canonical form; finally thecanonical forms are compared.Extra arguments:
- sh
Character constant, the heuristics to use in the BLISS algorithm for
graph1andgraph2. See theshargument ofcanonical_permutation()for possible values.
sh defaults to ‘fm’.
References
Tommi Junttila and Petteri Kaski: Engineering an Efficient CanonicalLabeling Tool for Large and Sparse Graphs,Proceedings of theNinth Workshop on Algorithm Engineering and Experiments and the FourthWorkshop on Analytic Algorithms and Combinatorics. 2007.
LP Cordella, P Foggia, C Sansone, and M Vento: An improved algorithmfor matching large graphs,Proc. of the 3rd IAPR TC-15 Workshopon Graphbased Representations in Pattern Recognition, 149–159, 2001.
See Also
Other graph isomorphism:canonical_permutation(),count_isomorphisms(),count_subgraph_isomorphisms(),graph_from_isomorphism_class(),isomorphism_class(),isomorphisms(),subgraph_isomorphic(),subgraph_isomorphisms()
Examples
# create some non-isomorphic graphsg1 <- 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 firstg1 <- sample_pa(30, m = 2, directed = FALSE)g2 <- permute(g1, sample(vcount(g1)))# should be TRUEisomorphic(g1, g2)isomorphic(g1, g2, method = "bliss")isomorphic(g1, g2, method = "vf2")# colored graph isomorphismg1 <- 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 defaultcount_isomorphisms(g1, g2)# ignore colorscount_isomorphisms(g1, g2, vertex.color1 = NULL, vertex.color2 = NULL)Isomorphism class of a graph
Description
The isomorphism class is a non-negative integer number.Graphs (with the same number of vertices) having the same isomorphismclass are isomorphic and isomorphic graphs always have the sameisomorphism class. Currently it can handle directed graphs with 3 or 4vertices and undirected graphs with 3 to 6 vertices.
Usage
isomorphism_class(graph, v)Arguments
graph | The input graph. |
v | Optionally a vertex sequence. If not missing, then an inducedsubgraph of the input graph, consisting of this vertices, is used. |
Value
An integer number.
See Also
Other graph isomorphism:canonical_permutation(),count_isomorphisms(),count_subgraph_isomorphisms(),graph_from_isomorphism_class(),isomorphic(),isomorphisms(),subgraph_isomorphic(),subgraph_isomorphisms()
Examples
# create some non-isomorphic graphsg1 <- 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
Description
Calculate all isomorphic mappings between the vertices of two graphs
Usage
isomorphisms(graph1, graph2, method = "vf2", ...)Arguments
graph1 | The first graph. |
graph2 | The second graph. |
method | Currently only ‘vf2’ is supported, see |
... | Extra arguments, passed to the various methods. |
Value
A list of vertex sequences, corresponding to allmappings from the first graph to the second.
See Also
Other graph isomorphism:canonical_permutation(),count_isomorphisms(),count_subgraph_isomorphisms(),graph_from_isomorphism_class(),isomorphic(),isomorphism_class(),subgraph_isomorphic(),subgraph_isomorphisms()
Independent vertex sets
Description
A vertex set is called independent if there no edges between any twovertices in it. These functions find independent vertex sets in undirectedgraphs
Usage
ivs(graph, min = NULL, max = NULL)largest_ivs(graph)max_ivs(graph)ivs_size(graph)independence_number(graph)is_ivs(graph, candidate)Arguments
graph | The input graph. |
min | Numeric constant, limit for the minimum size of the independentvertex sets to find. |
max | Numeric constant, limit for the maximum size of the independentvertex sets to find. |
candidate | The vertex set to test for being an independent set. |
Details
ivs() finds all independent vertex sets in thenetwork, obeying the size limitations given in themin andmaxarguments.
largest_ivs() finds the largest independent vertexsets in the graph. An independent vertex set is largest if there is noindependent vertex set with more vertices.
max_ivs() finds the maximal independent vertexsets in the graph. An independent vertex set is maximal if it cannot beextended to a larger independent vertex set. The largest independent vertexsets are maximal, but the opposite is not always true.
ivs_size() calculate the size of the largest independentvertex set(s).
independence_number() is an alias forivs_size().
These functions use the algorithm described by Tsukiyama et al., seereference below.
is_ivs() tests if no pairs within a vertex set are connected.
Value
ivs(),largest_ivs() andmax_ivs() return a list containing numericvertex ids, each list element is an independent vertex set.
ivs_size() returns an integer constant.
is_ivs() returnsTRUE if the candidate vertex set forms anindependent set.
Related documentation in the C library
Author(s)
Tamas Nepuszntamas@gmail.com ported it from the Very NautyGraph Library by Keith Briggs (https://keithbriggs.info/) and GaborCsardicsardi.gabor@gmail.com wrote the R interface and this manualpage.
References
S. Tsukiyama, M. Ide, H. Ariyoshi and I. Shirawaka. A newalgorithm for generating all the maximal independent sets.SIAM JComputing, 6:505–517, 1977.
See Also
Other cliques:cliques(),is_complete(),weighted_cliques()
Examples
# Do not run, takes a couple of seconds# A quite dense graphset.seed(42)g <- sample_gnp(100, 0.9)ivs_size(g)ivs(g, min = ivs_size(g))largest_ivs(g)# Empty graphinduced_subgraph(g, largest_ivs(g)[[1]])length(max_ivs(g))Create a random regular graph
Description
k.regular.game() was renamed tosample_k_regular() to create a moreconsistent API.
Usage
k.regular.game(no.of.nodes, k, directed = FALSE, multiple = FALSE)Arguments
no.of.nodes | Integer scalar, the number of vertices in the generatedgraph. |
k | Integer scalar, the degree of each vertex in the graph, or theout-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. |
Find thek shortest paths between two vertices
Description
Finds thek shortest paths between the given source and targetvertex in order of increasing length. Currently this function usesYen's algorithm.
Usage
k_shortest_paths( graph, from, to, ..., k, weights = NULL, mode = c("out", "in", "all", "total"))Arguments
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 ofincreasing length. |
weights | Possibly a numeric vector giving edge weights. If this is |
mode | Character constant, gives whether the shortest paths to or fromthe given vertices should be calculated for directed graphs. If |
Value
A named list with two components is returned:
- vpaths
The list of
kshortest paths in terms of vertices- epaths
The list of
kshortest paths in terms of edges
Related documentation in the C library
References
Yen, Jin Y.:An algorithm for finding shortest routes from all source nodes to a givendestination in general networks.Quarterly of Applied Mathematics. 27 (4): 526–530. (1970)doi:10.1090/qam/253822
See Also
shortest_paths(),all_shortest_paths()
Other structural.properties:bfs(),component_distribution(),connect(),constraint(),coreness(),degree(),dfs(),distance_table(),edge_density(),feedback_arc_set(),feedback_vertex_set(),girth(),is_acyclic(),is_dag(),is_matching(),knn(),reciprocity(),subcomponent(),subgraph(),topo_sort(),transitivity(),unfold_tree(),which_multiple(),which_mutual()
Graph rewiring while preserving the degree distribution
Description
This function can be used together withrewire() torandomly rewire the edges while preserving the original graph's degreedistribution.
Usage
keeping_degseq(loops = FALSE, niter = 100)Arguments
loops | Whether to allow destroying and creating loop edges. |
niter | Number of rewiring trials to perform. |
Details
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 notalready exists in the graph. The algorithm does not create multipleedges.
Author(s)
Tamas Nepuszntamas@gmail.com and Gabor Csardicsardi.gabor@gmail.com
See Also
Other rewiring functions:each_edge(),rewire()
Examples
g <- make_ring(10)g %>% rewire(keeping_degseq(niter = 20)) %>% degree()print_all(rewire(g, with = keeping_degseq(niter = vcount(g) * 10)))Average nearest neighbor degree
Description
Calculate the average nearest neighbor degree of the given vertices and thesame quantity in the function of vertex degree
Usage
knn( graph, vids = V(graph), mode = c("all", "out", "in", "total"), neighbor.degree.mode = c("all", "out", "in", "total"), weights = NULL)Arguments
graph | The input graph. It may be directed. |
vids | The vertices for which the calculation is performed. Normally itincludes all vertices. Note, that if not all vertices are given here, thenboth ‘ |
mode | Character constant to indicate the type of neighbors to considerin directed graphs. |
neighbor.degree.mode | The type of degree to average in directed graphs. |
weights | Weight vector. If the graph has a |
Details
Note that for zero degree vertices the answer in ‘knn’ isNaN (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
k_{nn,u} = \frac{1}{s_u} \sum_v w_{uv} k_v,
wheres_u = \sum_v w_{uv} is the sum of the incidentedge weights of vertexu, i.e. its strength.The sum runs over the neighborsv of vertexuas indicated bymode.w_{uv} denotes the weighted adjacency matrixandk_v is the neighbors' degree, specified byneighbor_degree_mode.
Value
A list with two members:
- knn
A numeric vector giving the average nearest neighbor degree for all vertices in
vids.- 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.
Related documentation in the C library
avg_nearest_neighbor_degree().
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
Alain Barrat, Marc Barthelemy, Romualdo Pastor-Satorras,Alessandro Vespignani: The architecture of complex weighted networks, Proc.Natl. Acad. Sci. USA 101, 3747 (2004)
See Also
Other structural.properties:bfs(),component_distribution(),connect(),constraint(),coreness(),degree(),dfs(),distance_table(),edge_density(),feedback_arc_set(),feedback_vertex_set(),girth(),is_acyclic(),is_dag(),is_matching(),k_shortest_paths(),reciprocity(),subcomponent(),subgraph(),topo_sort(),transitivity(),unfold_tree(),which_multiple(),which_mutual()
Examples
# Some trivial onesg <- 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 graphg4 <- sample_gnp(1000, p = 5 / 1000)knn(g4)# A weighted graphg5 <- make_star(10)E(g5)$weight <- seq(ecount(g5))knn(g5)Finding communities based on propagating labels
Description
label.propagation.community() was renamed tocluster_label_prop() to create a moreconsistent API.
Usage
label.propagation.community( graph, weights = NULL, ..., mode = c("out", "in", "all"), initial = NULL, fixed = NULL)Arguments
graph | The input graph. Note that the algorithm was originallydefined 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 thismakes sense only if you provided an initial state, otherwise this elementwill be ignored. Also note that vertices without labels cannot be fixed. |
Graph Laplacian
Description
The Laplacian of a graph.
Usage
laplacian_matrix( graph, weights = NULL, sparse = igraph_opt("sparsematrices"), normalization = c("unnormalized", "symmetric", "left", "right"), normalized)Arguments
graph | The input graph. |
weights | An optional vector giving edge weights for weighted Laplacianmatrix. If this is |
sparse | Logical scalar, whether to return the result as a sparsematrix. The |
normalization | The normalization method to use when calculating theLaplacian matrix. See the "Normalization methods" section on this page. |
normalized | Deprecated, use |
Details
The Laplacian Matrix of a graph is a symmetric matrix having the same numberof 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 edgebetween vertices i and j and 0 otherwise.
The Laplacian matrix can also be normalized, with severalconventional normalization methods.See the "Normalization methods" section on this page.
The weighted version of the Laplacian simply works with the weighted degreeinstead of the plain degree. I.e. (i,j) is d[i], the weighted degree ofvertex i if if i==j, -w if i!=j and there is an edge between vertices i andj with weight w, and 0 otherwise. The weighted degree of a vertex is the sumof the weights of its adjacent edges.
Value
A numeric matrix.
Normalization methods
The Laplacian matrixL is defined in terms of the adjacency matrixA and a diagonal matrixD containing the degrees as follows:
"unnormalized": Unnormalized Laplacian,
L = D - A."symmetric": Symmetrically normalized Laplacian,
L = I - D^{-\frac{1}{2}} A D^{-\frac{1}{2}}."left": Left-stochastic normalized Laplacian,
{L = I - D^{-1} A}."right": Right-stochastic normalized Laplacian,
L = I - A D^{-1}.
Related documentation in the C library
get_laplacian(),get_laplacian_sparse().
Author(s)
Gabor Csardicsardi.gabor@gmail.com
Examples
g <- make_ring(10)laplacian_matrix(g)laplacian_matrix(g, normalization = "unnormalized")laplacian_matrix(g, normalization = "unnormalized", sparse = FALSE)Functions to find cliques, i.e. complete subgraphs in a graph
Description
largest.cliques() was renamed tolargest_cliques() to create a moreconsistent API.
Usage
largest.cliques(graph)Arguments
graph | The input graph. |
Independent vertex sets
Description
largest.independent.vertex.sets() was renamed tolargest_ivs() to create a moreconsistent API.
Usage
largest.independent.vertex.sets(graph)Arguments
graph | The input graph. |
Random citation graphs
Description
lastcit.game() was renamed tosample_last_cit() to create a moreconsistent API.
Usage
lastcit.game( n, edges = 1, agebins = n/7100, pref = (1:(agebins + 1))^-3, directed = TRUE)Arguments
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. |
Choose an appropriate graph layout algorithm automatically
Description
layout.auto() was renamed tolayout_nicely() to create a moreconsistent API.
Usage
layout.auto(graph, dim = 2, ...)Arguments
graph | The input graph |
dim | Dimensions, should be 2 or 3. |
... | For |
Simple two-row layout for bipartite graphs
Description
layout.bipartite() was renamed tolayout_as_bipartite() to create a moreconsistent API.
Usage
layout.bipartite(graph, types = NULL, hgap = 1, vgap = 1, maxiter = 100)Arguments
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 thesame layer. |
vgap | Real scalar, the distance between the two layers. |
maxiter | Integer scalar, the maximum number of iterations in thecrossing minimization stage. 100 is a reasonable default; if you feel thatyou have too many edge crossings, increase this. |
Graph layout with vertices on a circle
Description
layout.circle() was renamed tolayout_in_circle() to create a moreconsistent API.
Usage
layout.circle(..., params = list())Arguments
... | Passed to the new layout functions. |
params | Passed to the new layout functions as arguments. |
The Davidson-Harel layout algorithm
Description
layout.davidson.harel() was renamed tolayout_with_dh() to create a moreconsistent API.
Usage
layout.davidson.harel( 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)))Arguments
graph | The graph to lay out. Edge directions are ignored. |
coords | Optional starting positions for the vertices. If this argumentis 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 theenergy function. |
weight.border | Weight for the distance from the border component ofthe energy function. It can be set to zero, if vertices are allowed to siton the border. |
weight.edge.lengths | Weight for the edge length component of theenergy function. |
weight.edge.crossings | Weight for the edge crossing component of theenergy function. |
weight.node.edge.dist | Weight for the node-edge distance component ofthe energy function. |
The DrL graph layout generator
Description
layout.drl() was renamed tolayout_with_drl() to create a moreconsistent API.
Usage
layout.drl( graph, use.seed = FALSE, seed = matrix(runif(vcount(graph) * 2), ncol = 2), options = drl_defaults$default, weights = NULL, dim = 2)Arguments
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 thevertices is |
options | Options for the layout generator, a named list. See detailsbelow. |
weights | The weights of the edges. It must be a positive numeric vector, |
dim | Either ‘2’ or ‘3’, it specifies whether we want atwo dimensional or a three dimensional layout. Note that because of thenature of the DrL algorithm, the three dimensional layout takessignificantly longer to compute. |
The Fruchterman-Reingold layout algorithm
Description
layout.fruchterman.reingold() was renamed tolayout_with_fr() to create a moreconsistent API.
Usage
layout.fruchterman.reingold(..., params = list())Arguments
... | Passed to the new layout functions. |
params | Passed to the new layout functions as arguments. |
Grid Fruchterman-Reingold layout, this was removed from igraph
Description
Now it calls the Fruchterman-Reingold layoutlayout_with_fr().
Usage
layout.fruchterman.reingold.grid(graph, ...)Arguments
graph | Input graph. |
... | Extra arguments are ignored. |
Value
Layout coordinates, a two column matrix.
The GEM layout algorithm
Description
layout.gem() was renamed tolayout_with_gem() to create a moreconsistent API.
Usage
layout.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)))Arguments
graph | The input graph. Edge directions are ignored. |
coords | If not |
maxiter | The maximum number of iterations to perform. Updating asingle 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 defaultis 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 reasonabledefault is the square root of the number of vertices. |
The graphopt layout algorithm
Description
layout.graphopt() was renamed tolayout_with_graphopt() to create a moreconsistent API.
Usage
layout.graphopt( graph, start = NULL, niter = 500, charge = 0.001, mass = 30, spring.length = 0, spring.constant = 1, max.sa.movement = 5)Arguments
graph | The input graph. |
start | If given, then it should be a matrix with two columns and oneline for each vertex. This matrix will be used as starting positions for thealgorithm. If not given, then a random starting matrix is used. |
niter | Integer scalar, the number of iterations to perform. Should bea couple of hundred in general. If you have a large graph then you mightwant to only do a few iterations and then check the result. If it is notgood enough you can feed it in again in the |
charge | The charge of the vertices, used to calculate electricrepulsion. The default is 0.001. |
mass | The mass of the vertices, used for the spring forces. Thedefault is 30. |
spring.length | The length of the springs, an integer number. Thedefault value is zero. |
spring.constant | The spring constant, the default value is one. |
max.sa.movement | Real constant, it gives the maximum amount ofmovement allowed in a single step along a single axis. The default value is5. |
Simple grid layout
Description
layout.grid() was renamed tolayout_on_grid() to create a moreconsistent API.
Usage
layout.grid(graph, width = 0, height = 0, dim = 2)Arguments
graph | The input graph. |
width | The number of vertices in a single row of the grid. If this iszero or negative, then for 2d layouts the width of the grid will be thesquare root of the number of vertices in the graph, rounded up to the nextinteger. Similarly, it will be the cube root for 3d layouts. |
height | The number of vertices in a single column of the grid, forthree dimensional layouts. If this is zero or negative, then it isdeterminted automatically. |
dim | Two or three. Whether to make 2d or a 3d layout. |
Simple grid layout
Description
Uselayout_on_grid().
Usage
layout.grid.3d(graph, width = 0, height = 0)Arguments
graph | The input graph. |
width | The number of vertices in a single row of the grid. If this iszero or negative, then for 2d layouts the width of the grid will be thesquare root of the number of vertices in the graph, rounded up to the nextinteger. Similarly, it will be the cube root for 3d layouts. |
height | The number of vertices in a single column of the grid, forthree dimensional layouts. If this is zero or negative, then it isdeterminted automatically. |
The Kamada-Kawai layout algorithm
Description
layout.kamada.kawai() was renamed tolayout_with_kk() to create a moreconsistent API.
Usage
layout.kamada.kawai(..., params = list())Arguments
... | Passed to the new layout functions. |
params | Passed to the new layout functions as arguments. |
Large Graph Layout
Description
layout.lgl() was renamed tolayout_with_lgl() to create a moreconsistent API.
Usage
layout.lgl(..., params = list())Arguments
... | Passed to the new layout functions. |
params | Passed to the new layout functions as arguments. |
Graph layout by multidimensional scaling
Description
layout.mds() was renamed tolayout_with_mds() to create a moreconsistent API.
Usage
layout.mds(graph, dist = NULL, dim = 2, options = arpack_defaults())Arguments
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 forsolving the eigenproblem |
Merging graph layouts
Description
layout.merge() was renamed tomerge_coords() to create a moreconsistent API.
Usage
layout.merge(graphs, layouts, method = "dla")Arguments
graphs | A list of graph objects. |
layouts | A list of two-column matrices. |
method | Character constant giving the method to use. Right now only |
Normalize coordinates for plotting graphs
Description
layout.norm() was renamed tonorm_coords() to create a moreconsistent API.
Usage
layout.norm( layout, xmin = -1, xmax = 1, ymin = -1, ymax = 1, zmin = -1, zmax = 1)Arguments
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 bothare |
ymin,ymax | The limits for the second coordinate, if one of them orboth are |
zmin,zmax | The limits for the third coordinate, if one of them or bothare |
Randomly place vertices on a plane or in 3d space
Description
layout.random() was renamed tolayout_randomly() to create a moreconsistent API.
Usage
layout.random(..., params = list())Arguments
... | Passed to the new layout functions. |
params | Passed to the new layout functions as arguments. |
The Reingold-Tilford graph layout algorithm
Description
layout.reingold.tilford() was renamed tolayout_as_tree() to create a moreconsistent API.
Usage
layout.reingold.tilford(..., params = list())Arguments
... | Passed to the new layout functions. |
params | Passed to the new layout functions as arguments. |
Graph layout with vertices on the surface of a sphere
Description
layout.sphere() was renamed tolayout_on_sphere() to create a moreconsistent API.
Usage
layout.sphere(..., params = list())Arguments
... | Passed to the new layout functions. |
params | Passed to the new layout functions as arguments. |
Spring layout, this was removed from igraph
Description
Now it calls the Fruchterman-Reingold layoutlayout_with_fr().
Usage
layout.spring(graph, ...)Arguments
graph | Input graph. |
... | Extra arguments are ignored. |
Value
Layout coordinates, a two column matrix.
Generate coordinates to place the vertices of a graph in a star-shape
Description
layout.star() was renamed tolayout_as_star() to create a moreconsistent API.
Usage
layout.star(graph, center = V(graph)[1], order = NULL)Arguments
graph | The graph to layout. |
center | The id of the vertex to put in the center. By default it isthe first vertex. |
order | Numeric vector, the order of the vertices along the perimeter.The default ordering is given by the vertex ids. |
The Sugiyama graph layout generator
Description
layout.sugiyama() was renamed tolayout_with_sugiyama() to create a moreconsistent API.
Usage
layout.sugiyama( graph, layers = NULL, hgap = 1, vgap = 1, maxiter = 100, weights = NULL, attributes = c("default", "all", "none"))Arguments
graph | The input graph. |
layers | A numeric vector or |
hgap | Real scalar, the minimum horizontal gap between vertices in thesame layer. |
vgap | Real scalar, the distance between layers. |
maxiter | Integer scalar, the maximum number of iterations in thecrossing minimization stage. 100 is a reasonable default; if you feel thatyou have too many edge crossings, increase this. |
weights | Optional edge weight vector. If |
attributes | Which graph/vertex/edge attributes to keep in the extendedgraph. ‘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 ofthem. |
SVD layout, this was removed from igraph
Description
Now it calls the Fruchterman-Reingold layoutlayout_with_fr().
Usage
layout.svd(graph, ...)Arguments
graph | Input graph. |
... | Extra arguments are ignored. |
Value
Layout coordinates, a two column matrix.
Graph layouts
Description
This is a generic function to apply a layout function toa graph.
Usage
layout_(graph, layout, ...)## S3 method for class 'igraph_layout_spec'print(x, ...)## S3 method for class 'igraph_layout_modifier'print(x, ...)Arguments
graph | The input graph. |
layout | The layout specification. It must be a callto a layout specification function. |
... | Further modifiers, see a complete list below.For the |
x | The layout specification |
Details
There are two ways to calculate graph layouts in igraph.The first way is to call a layout function (they all haveprefixlayout_() on a graph, to get the vertex coordinates.
The second way (new in igraph 0.8.0), has two steps, and itis more flexible. First you call a layout specificationfunction (the one without thelayout_() prefix, andthenlayout_() (oradd_layout_()) toperform the layouting.
The second way is preferred, as it is more flexible. It allowsoperations before and after the layouting. E.g. using thecomponent_wise() argument, the layout can be calculatedseparately for each component, and then merged to get thefinal results.
Value
The return value of the layout function, usually atwo column matrix. For 3D layouts a three column matrix.
Modifiers
Modifiers modify how a layout calculation is performed.Currently implemented modifiers:
component_wise()calculates the layout separatelyfor each component of the graph, and then mergesthem.normalize()scales the layout to a square.
See Also
add_layout_() to add the layout to thegraph 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()
Examples
g <- make_ring(10) + make_full_graph(5)coords <- layout_(g, as_star())plot(g, layout = coords)Simple two-row layout for bipartite graphs
Description
Minimize edge-crossings in a simple two-row (or column) layout for bipartitegraphs.
Usage
layout_as_bipartite(graph, types = NULL, hgap = 1, vgap = 1, maxiter = 100)as_bipartite(...)Arguments
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 thesame layer. |
vgap | Real scalar, the distance between the two layers. |
maxiter | Integer scalar, the maximum number of iterations in thecrossing minimization stage. 100 is a reasonable default; if you feel thatyou have too many edge crossings, increase this. |
... | Arguments to pass to |
Details
The layout is created by first placing the vertices in two rows, accordingto their types. Then the positions within the rows are optimized to minimizeedge crossings, using the Sugiyama algorithm (seelayout_with_sugiyama()).
Value
A matrix with two columns and as many rows as the number of verticesin the input graph.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
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()
Examples
# Random bipartite graphinc <- 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 columnsg %>% add_layout_(as_bipartite()) %>% plot()Generate coordinates to place the vertices of a graph in a star-shape
Description
A simple layout generator, that places one vertex in the center of a circleand the rest of the vertices equidistantly on the perimeter.
Usage
layout_as_star(graph, center = V(graph)[1], order = NULL)as_star(...)Arguments
graph | The graph to layout. |
center | The id of the vertex to put in the center. By default it isthe 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 |
Details
It is possible to choose the vertex that will be in the center, and theorder of the vertices can be also given.
Value
A matrix with two columns and as many rows as the number of verticesin the input graph.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
layout() andlayout_with_drl() for other layoutalgorithms,plot.igraph() andtkplot() on how toplot graphs andstar() 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()
Examples
g <- make_star(10)layout_as_star(g)## Alternative formlayout_(g, as_star())The Reingold-Tilford graph layout algorithm
Description
A tree-like layout, it is perfect for trees, acceptable for graphs with nottoo many cycles.
Usage
layout_as_tree( graph, root = numeric(), circular = FALSE, rootlevel = numeric(), mode = c("out", "in", "all"), flip.y = TRUE)as_tree(...)Arguments
graph | The input graph. |
root | The index of the root vertex or root vertices. If this is anon-empty vector then the supplied vertex ids are used as the roots of thetrees (or a single tree if the graph is connected). If it is an emptyvector, then the root vertices are automatically calculated based ontopological sorting, performed with the opposite mode than the |
circular | Logical scalar, whether to plot the tree in a circularfashion. Defaults to |
rootlevel | This argument can be useful when drawing forests which arenot trees (i.e. they are unconnected and have tree components). It specifiesthe level of the root vertices for every tree in the forest. It is onlyconsidered if the |
mode | Specifies which edges to consider when building the tree. If itis ‘out’, then only the outgoing, if it is ‘in’, then only theincoming edges of a parent are considered. If it is ‘all’ then alledges are used (this was the behavior in igraph 0.5 and before). Thisparameter also influences how the root vertices are calculated, if they arenot 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 |
Details
Arranges the nodes in a tree where the given node is used as the root. Thetree 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 firstto obtain a possible spanning tree.
Value
A numeric matrix with two columns, and one row for each vertex.
Author(s)
Tamas Nepuszntamas@gmail.com and Gabor Csardicsardi.gabor@gmail.com
References
Reingold, E and Tilford, J (1981). Tidier drawing of trees.IEEE Trans. on Softw. Eng., SE-7(2):223–228.
See Also
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()
Examples
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)))Graph layout with vertices on a circle.
Description
Place vertices on a circle, in the order of their vertex ids.
Usage
layout_in_circle(graph, order = V(graph))in_circle(...)Arguments
graph | The input graph. |
order | The vertices to place on the circle, in the order of theirdesired placement. Vertices that are not included here will be placed at(0,0). |
... | Passed to |
Details
If you want to order the vertices differently, then permute them using thepermute() function.
Value
A numeric matrix with two columns, and one row for each vertex.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
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()
Examples
## Place vertices on a circle, order them according to their## communitylibrary(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)Choose an appropriate graph layout algorithm automatically
Description
This function tries to choose an appropriate graph layout algorithm for thegraph, automatically, based on a simple algorithm. See details below.
Usage
layout_nicely(graph, dim = 2, ...)nicely(...)Arguments
graph | The input graph |
dim | Dimensions, should be 2 or 3. |
... | For |
Details
layout_nicely() tries to choose an appropriate layout function for thesupplied graph, and uses that to generate the layout. The currentimplementation 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 anadditional ‘z’ vertex attribute, that is also used.
Otherwise, if the graph is a forest and has less than 30 vertices,
layout_as_tree()is used.Otherwise,if the graph is connected and has less than 1000 vertices, theFruchterman-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’ istypically used to specify the weights of the edges if the layout algorithmsupports them. In this case, omitting ‘weights’ or setting it toNULL will make igraph use the 'weight' edge attribute from the graphif it is present. However, most layout algorithms do not support non-positiveweights, solayout_nicely() would fail if you simply called it onyour graph without specifying explicit weights and the weights happened toinclude non-positive numbers. We strive to ensure thatlayout_nicely()works out-of-the-box for most graphs, so the rule is that if you omit‘weights’ or set it toNULL andlayout_nicely() wouldend up callinglayout_with_fr() orlayout_with_drl(), we do notforward the weights to these functions and issue a warning about this. Youcan useweights = NA to silence the warning.
Value
A numeric matrix with two or three columns.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
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()
Simple grid layout
Description
This layout places vertices on a rectangular grid, in two or threedimensions.
Usage
layout_on_grid(graph, width = 0, height = 0, dim = 2)on_grid(...)Arguments
graph | The input graph. |
width | The number of vertices in a single row of the grid. If this iszero or negative, then for 2d layouts the width of the grid will be thesquare root of the number of vertices in the graph, rounded up to the nextinteger. Similarly, it will be the cube root for 3d layouts. |
height | The number of vertices in a single column of the grid, forthree dimensional layouts. If this is zero or negative, then it isdeterminted automatically. |
dim | Two or three. Whether to make 2d or a 3d layout. |
... | Passed to |
Details
The function places the vertices on a simple rectangular grid, one after theother. If you want to change the order of the vertices, then see thepermute() function.
Value
A two-column or three-column matrix.
Author(s)
Tamas Nepuszntamas@gmail.com
See Also
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()
Examples
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))}Graph layout with vertices on the surface of a sphere
Description
Place vertices on a sphere, approximately uniformly, in the order of theirvertex ids.
Usage
layout_on_sphere(graph)on_sphere(...)Arguments
graph | The input graph. |
... | Passed to |
Details
layout_on_sphere() places the vertices (approximately) uniformly on thesurface 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 thepermute() function.
Value
A numeric matrix with three columns, and one row for each vertex.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
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()
Randomly place vertices on a plane or in 3d space
Description
This function uniformly randomly places the vertices of the graph in two orthree dimensions.
Usage
layout_randomly(graph, dim = c(2, 3))randomly(...)Arguments
graph | The input graph. |
dim | Integer scalar, the dimension of the space to use. It must be 2or 3. |
... | Parameters to pass to |
Details
Randomly places vertices on a [-1,1] square (in 2d) or in a cube (in 3d). Itis probably a useless layout, but it can use as a starting point for otherlayout generators.
Value
A numeric matrix with two or three columns.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
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()
The Davidson-Harel layout algorithm
Description
Place vertices of a graph on the plane, according to the simulated annealingalgorithm by Davidson and Harel.
Usage
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(...)Arguments
graph | The graph to lay out. Edge directions are ignored. |
coords | Optional starting positions for the vertices. If this argumentis 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 theenergy function. |
weight.border | Weight for the distance from the border component ofthe energy function. It can be set to zero, if vertices are allowed to siton the border. |
weight.edge.lengths | Weight for the edge length component of theenergy function. |
weight.edge.crossings | Weight for the edge crossing component of theenergy function. |
weight.node.edge.dist | Weight for the node-edge distance component ofthe energy function. |
... | Passed to |
Details
This function implements the algorithm by Davidson and Harel, see RonDavidson, David Harel: Drawing Graphs Nicely Using Simulated Annealing. ACMTransactions 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. Theoriginal publication did not disclose any parameter values, and the onesbelow were determined by experimentation.
The algorithm consists of two phases, an annealing phase, and a fine-tuningphase. There is no simulated annealing in the second phase.
Our implementation tries to follow the original publication, as much aspossible. The only major difference is that coordinates are explicitly keptwithin the bounds of the rectangle of the layout.
Value
A matrix with two columns, containing the x and y coordinatesof the vertices:
- x
The x-coordinate of the vertex.
- y
The y-coordinate of the vertex.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
Ron Davidson, David Harel: Drawing Graphs Nicely Using SimulatedAnnealing.ACM Transactions on Graphics 15(4), pp. 301-331, 1996.
See Also
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()
Examples
set.seed(42)## Figures from the paperg_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)The DrL graph layout generator
Description
DrL is a force-directed graph layout toolbox focused on real-worldlarge-scale graphs, developed by Shawn Martin and colleagues at SandiaNational Laboratories.
Usage
layout_with_drl( graph, use.seed = FALSE, seed = matrix(runif(vcount(graph) * 2), ncol = 2), options = drl_defaults$default, weights = NULL, dim = c(2, 3))with_drl(...)Arguments
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 thevertices is |
options | Options for the layout generator, a named list. See detailsbelow. |
weights | The weights of the edges. It must be a positive numeric vector, |
dim | Either ‘2’ or ‘3’, it specifies whether we want atwo dimensional or a three dimensional layout. Note that because of thenature of the DrL algorithm, the three dimensional layout takessignificantly longer to compute. |
... | Passed to |
Details
This function implements the force-directed DrL layout generator.
The generator has the following parameters:
- edge.cut
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.
- init.iterations
Number of iterations in the first phase.
- init.temperature
Start temperature, first phase.
- init.attraction
Attraction, first phase.
- init.damping.mult
Damping, first phase.
- liquid.iterations
Number of iterations, liquid phase.
- liquid.temperature
Start temperature, liquid phase.
- liquid.attraction
Attraction, liquid phase.
- liquid.damping.mult
Damping, liquid phase.
- expansion.iterations
Number of iterations, expansion phase.
- expansion.temperature
Start temperature, expansion phase.
- expansion.attraction
Attraction, expansion phase.
- expansion.damping.mult
Damping, expansion phase.
- cooldown.iterations
Number of iterations, cooldown phase.
- cooldown.temperature
Start temperature, cooldown phase.
- cooldown.attraction
Attraction, cooldown phase.
- cooldown.damping.mult
Damping, cooldown phase.
- crunch.iterations
Number of iterations, crunch phase.
- crunch.temperature
Start temperature, crunch phase.
- crunch.attraction
Attraction, crunch phase.
- crunch.damping.mult
Damping, crunch phase.
- simmer.iterations
Number of iterations, simmer phase.
- simmer.temperature
Start temperature, simmer phase.
- simmer.attraction
Attraction, simmer phase.
- simmer.damping.mult
Damping, simmer phase.
There are five pre-defined parameter settings as well, these are calleddrl_defaults$default,drl_defaults$coarsen,drl_defaults$coarsest,drl_defaults$refine anddrl_defaults$final.
Value
A numeric matrix with two columns.
Author(s)
Shawn Martin (https://www.cs.otago.ac.nz/homepages/smartin/)and Gabor Csardicsardi.gabor@gmail.com for the R/igraph interfaceand the three dimensional version.
References
See the following technical report: Martin, S., Brown, W.M.,Klavans, R., Boyack, K.W., DrL: Distributed Recursive (Graph) Layout. SANDReports, 2008. 2936: p. 1-10.
See Also
layout() for other layout generators.
Examples
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)The Fruchterman-Reingold layout algorithm
Description
Place vertices on the plane using the force-directed layout algorithm byFruchterman and Reingold.
Usage
layout_with_fr( graph, coords = NULL, dim = c(2, 3), 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(...)Arguments
Details
See the referenced paper below for the details of the algorithm.
This function was rewritten from scratch in igraph version 0.8.0.
Value
A two- or three-column matrix, each row giving the coordinates of avertex, according to the ids of the vertex ids.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
Fruchterman, T.M.J. and Reingold, E.M. (1991). Graph Drawing byForce-directed Placement.Software - Practice and Experience,21(11):1129-1164.
See Also
layout_with_drl(),layout_with_kk() forother 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()
Examples
# Fixing egog <- sample_pa(20, m = 2)minC <- rep(-Inf, vcount(g))maxC <- rep(Inf, vcount(g))minC[1] <- maxC[1] <- 0co <- 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)The GEM layout algorithm
Description
Place vertices on the plane using the GEM force-directed layout algorithm.
Usage
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(...)Arguments
graph | The input graph. Edge directions are ignored. |
coords | If not |
maxiter | The maximum number of iterations to perform. Updating asingle 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 defaultis 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 reasonabledefault is the square root of the number of vertices. |
... | Passed to |
Details
See the referenced paper below for the details of the algorithm.
Value
A numeric matrix with two columns, and as many rows as the number ofvertices.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
Arne Frick, Andreas Ludwig, Heiko Mehldau: A Fast AdaptiveLayout Algorithm for Undirected Graphs,Proc. Graph Drawing 1994,LNCS 894, pp. 388-403, 1995.
See Also
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()
Examples
set.seed(42)g <- make_ring(10)plot(g, layout = layout_with_gem)The graphopt layout algorithm
Description
A force-directed layout algorithm, that scales relatively well to largegraphs.
Usage
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(...)Arguments
graph | The input graph. |
start | If given, then it should be a matrix with two columns and oneline for each vertex. This matrix will be used as starting positions for thealgorithm. If not given, then a random starting matrix is used. |
niter | Integer scalar, the number of iterations to perform. Should bea couple of hundred in general. If you have a large graph then you mightwant to only do a few iterations and then check the result. If it is notgood enough you can feed it in again in the |
charge | The charge of the vertices, used to calculate electricrepulsion. The default is 0.001. |
mass | The mass of the vertices, used for the spring forces. Thedefault is 30. |
spring.length | The length of the springs, an integer number. Thedefault value is zero. |
spring.constant | The spring constant, the default value is one. |
max.sa.movement | Real constant, it gives the maximum amount ofmovement allowed in a single step along a single axis. The default value is5. |
... | Passed to |
Details
layout_with_graphopt() is a port of the graphopt layout algorithm by MichaelSchmuhl. graphopt version 0.4.1 was rewritten in C and the support forlayers was removed (might be added later) and a code was a bit reorganizedto avoid some unnecessary steps is the node charge (see below) is zero.
graphopt uses physical analogies for defining attracting and repellingforces among the vertices and then the physical system is simulated until itreaches an equilibrium. (There is no simulated annealing or anything likethat, so a stable fixed point is not guaranteed.)
Value
A numeric matrix with two columns, and a row for each vertex.
Author(s)
Michael Schmuhl for the original graphopt code, rewritten andwrapped by Gabor Csardicsardi.gabor@gmail.com.
See Also
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()
The Kamada-Kawai layout algorithm
Description
Place the vertices on the plane, or in 3D space, based on a physicalmodel of springs.
Usage
layout_with_kk( graph, coords = NULL, dim = c(2, 3), 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(...)Arguments
graph | The input graph. Edge directions are ignored. |
coords | If not |
dim | Integer scalar, 2 or 3, the dimension of the layout. Twodimensional layouts are places on a plane, three dimensional ones in the 3dspace. |
maxiter | The maximum number of iterations to perform. The algorithmmight terminate earlier, see the |
epsilon | Numeric scalar, the algorithm terminates, if the maximaldelta is less than this. (See the reference below for what delta means.) Ifyou 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 in longer edges.Note that this is the opposite of |
minx | If not |
maxx | Similar to |
miny | Similar to |
maxy | Similar to |
minz | Similar to |
maxz | Similar to |
niter,sigma,initemp,coolexp |
|
start | Deprecated synonym for |
... | Passed to |
Details
See the referenced paper below for the details of the algorithm.
This function was rewritten from scratch in igraph version 0.8.0 and itfollows truthfully the original publication by Kamada and Kawai now.
Value
A numeric matrix with two (dim=2) or three (dim=3) columns, and asmany rows as the number of vertices, the x, y and potentially z coordinatesof the vertices.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
Kamada, T. and Kawai, S.: An Algorithm for Drawing GeneralUndirected Graphs.Information Processing Letters, 31/1, 7–15, 1989.
See Also
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()
Examples
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)Large Graph Layout
Description
A layout generator for larger graphs.
Usage
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(...)Arguments
graph | The input graph |
maxiter | The maximum number of iterations to perform (150). |
maxdelta | The maximum change for a vertex during an iteration (thenumber of vertices). |
area | The area of the surface on which the vertices are placed (squareof 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 therepulsion forces between vertices only vertices in the same or neighboringgrid 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. Thedefault value is -1 which means that a random vertex is selected. |
... | Passed to |
Details
layout_with_lgl() is for large connected graphs, it is similar to the layoutgenerator of the Large Graph Layout software(https://lgl.sourceforge.net/).
Value
A numeric matrix with two columns and as many rows as vertices.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
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()
Graph layout by multidimensional scaling
Description
Multidimensional scaling of some distance matrix defined on the vertices ofa graph.
Usage
layout_with_mds(graph, dist = NULL, dim = 2, options = arpack_defaults())with_mds(...)Arguments
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 forsolving the eigenproblem |
... | Passed to |
Details
layout_with_mds() uses classical multidimensional scaling (Torgerson scaling)for generating the coordinates. Multidimensional scaling aims to place pointsfrom a higher dimensional space in a (typically) 2 dimensional plane, so thatthe distances between the points are kept as much as this is possible.
By default igraph uses the shortest path matrix as the distances between thenodes, but the user can override this via thedist argument.
Warning: If the graph is symmetric to the exchange of two vertices (as is thecase with leaves of a tree connecting to the same parent), classicalmultidimensional scaling may assign the same coordinates to these vertices.
This function generates the layout separately for each graph component andthen merges them viamerge_coords().
Value
A numeric matrix withdim columns.
Author(s)
Tamas Nepuszntamas@gmail.com and Gabor Csardicsardi.gabor@gmail.com
References
Cox, T. F. and Cox, M. A. A. (2001)MultidimensionalScaling. Second edition. Chapman and Hall.
See Also
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()
Examples
g <- sample_gnp(100, 2 / 100)l <- layout_with_mds(g)plot(g, layout = l, vertex.label = NA, vertex.size = 3)The Sugiyama graph layout generator
Description
Sugiyama layout algorithm for layered directed acyclic graphs. The algorithmminimized edge crossings.
Usage
layout_with_sugiyama( graph, layers = NULL, hgap = 1, vgap = 1, maxiter = 100, weights = NULL, attributes = c("default", "all", "none"))with_sugiyama(...)Arguments
graph | The input graph. |
layers | A numeric vector or |
hgap | Real scalar, the minimum horizontal gap between vertices in thesame layer. |
vgap | Real scalar, the distance between layers. |
maxiter | Integer scalar, the maximum number of iterations in thecrossing minimization stage. 100 is a reasonable default; if you feel thatyou have too many edge crossings, increase this. |
weights | Optional edge weight vector. If |
attributes | Which graph/vertex/edge attributes to keep in the extendedgraph. ‘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 ofthem. |
... | Passed to |
Details
This layout algorithm is designed for directed acyclic graphs where eachvertex is assigned to a layer. Layers are indexed from zero, and vertices ofthe same layer will be placed on the same horizontal line. The X coordinatesof vertices within each layer are decided by the heuristic proposed bySugiyama et al. to minimize edge crossings.
You can also try to lay out undirected graphs, graphs containing cycles, orgraphs without an a priori layered assignment with this algorithm. igraphwill try to eliminate cycles and assign vertices to layers, but there is noguarantee on the quality of the layout in such cases.
The Sugiyama layout may introduce “bends” on the edges in order toobtain a visually more pleasing layout. This is achieved by adding dummynodes to edges spanning more than one layer. The resulting layout assignscoordinates not only to the nodes of the original graph but also to thedummy nodes. The layout algorithm will also return the extended graph withthe dummy nodes.
For more details, see the reference below.
Value
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.
Author(s)
Tamas Nepuszntamas@gmail.com
References
K. Sugiyama, S. Tagawa and M. Toda, "Methods for VisualUnderstanding of Hierarchical Systems". IEEE Transactions on Systems, Manand Cybernetics 11(2):109-125, 1981.
See Also
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()
Examples
## 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 typesE(DC)$lty <- 1E(DC)["BCDC++" %->% "StrongDC++"]$lty <- 2E(DC)["FreeDC++" %->% "EiskaltDC++"]$lty <- 2E(DC)["ApexDC++" %->% "FlylinkDC++ ver <= 4xx"]$lty <- 2E(DC)["ApexDC++" %->% "DiCe!++"]$lty <- 2E(DC)["StrongDC++ SQLite" %->% "FlylinkDC++ ver >= 5xx"]$lty <- 2E(DC)["GreylinkDC++" %->% "AvaLink"]$lty <- 2## Layers, as on the plotlayers <- 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 nodesall(sort(unlist(layers)) == sort(V(DC)$name))## Add some graphical parametersV(DC)$color <- "white"V(DC)$shape <- "rectangle"V(DC)$size <- 20V(DC)$size2 <- 10V(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 layerslay1 <- layout_with_sugiyama(DC, layers = apply(sapply( layers, function(x) V(DC)$name %in% x), 1, which))## Simple plot, not very nicepar(mar = rep(.1, 4))plot(DC, layout = lay1$layout, vertex.label.cex = 0.5)## Sugiyama plotplot(lay1$extd_graph, vertex.label.cex = 0.5)## The same with automatic layer calculation## Keep vertex/edge attributes in the extended graphlay2 <- 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))Community structure detecting based on the leading eigenvector of the community matrix
Description
leading.eigenvector.community() was renamed tocluster_leading_eigen() to create a moreconsistent API.
Usage
leading.eigenvector.community( graph, steps = -1, weights = NULL, start = NULL, options = arpack_defaults(), callback = NULL, extra = NULL, env = parent.frame())Arguments
graph | The input graph. Should be undirected as the method needs asymmetric matrix. |
steps | The number of steps to take, this is actually the number oftries 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. |
Line graph of a graph
Description
line.graph() was renamed tomake_line_graph() to create a moreconsistent API.
Usage
line.graph(graph)Arguments
graph | The input graph, it can be directed or undirected. |
List names of edge attributes
Description
list.edge.attributes() was renamed toedge_attr_names() to create a moreconsistent API.
Usage
list.edge.attributes(graph)Arguments
graph | The graph. |
List names of graph attributes
Description
list.graph.attributes() was renamed tograph_attr_names() to create a moreconsistent API.
Usage
list.graph.attributes(graph)Arguments
graph | The graph. |
List names of vertex attributes
Description
list.vertex.attributes() was renamed tovertex_attr_names() to create a moreconsistent API.
Usage
list.vertex.attributes(graph)Arguments
graph | The graph. |
Compute local scan statistics on graphs
Description
The scan statistic is a summary of the locality statistics that iscomputed from the local neighborhood of each vertex. Thelocal_scan() function computes the local statistics for each vertexfor a given neighborhood size and the statistic function.
Usage
local_scan( graph.us, graph.them = NULL, k = 1, FUN = NULL, weighted = FALSE, mode = c("out", "in", "all"), neighborhoods = NULL, weights = NULL, ...)Arguments
graph.us,graph | An igraph object, the graph for which the scanstatistics will be computed |
graph.them | An igraph object or |
k | An integer scalar, the size of the local neighborhood for eachvertex. Should be non-negative. |
FUN | Character, a function name, or a function object itself, forcomputing the local statistic in each neighborhood. If |
weighted | Logical scalar, TRUE if the edge weights should be usedfor computation of the scan statistic. If TRUE, the graph should beweighted. Note that this argument is ignored if |
mode | Character scalar, the kind of neighborhoods to use for thecalculation. One of ‘ |
neighborhoods | A list of neighborhoods, one for each vertex, or In theory this could be useful if the same |
weights | Numeric vector, edge weights to use for the scan instead of the edge attribute weight. If |
... | Arguments passed to |
Details
See the given reference below for the details on the local scanstatistics.
local_scan() calculates exact local scan statistics.
Ifgraph.them isNULL, thenlocal_scan() computes the‘us’ variant of the scan statistics. Otherwise,graph.them should be an igraph object and the ‘them’variant is computed usinggraph.us to extract the neighborhoodinformation, and applyingFUN on these neighborhoods ingraph.them.
Value
Forlocal_scan() typically a numeric vector containing thecomputed local statistics for each vertex. In general a list or vectorof objects, as returned byFUN.
References
Priebe, C. E., Conroy, J. M., Marchette, D. J., Park,Y. (2005). Scan Statistics on Enron Graphs.Computational andMathematical Organization Theory.
See Also
Other scan statistics:scan_stat()
Examples
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)Make a new graph
Description
This is a generic function for creating graphs.
Usage
make_(...)Arguments
... | Parameters, see details below. |
Details
make_() is a generic function for creating graphs.For every graph constructor in igraph that has amake_ prefix,there is a corresponding function without the prefix: e.g.formake_ring() there is alsoring(), etc.
The same is true for the random graph samplers, i.e. for eachconstructor with asample_ prefix, there is a correspondingfunction without that prefix.
These shorter forms can be used together withmake_().The advantage of this form is that the user can specify constructormodifiers which work with all constructors. E.g. thewith_vertex_() modifier adds vertex attributesto the newly created graphs.
See the examples and the various constructor modifiers below.
See Also
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()
Examples
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)Create a bipartite graph
Description
A bipartite graph has two kinds of vertices and connections are only allowedbetween different kinds.
Usage
make_bipartite_graph(types, edges, directed = FALSE)bipartite_graph(...)Arguments
types | A vector giving the vertex types. It will be coerced intoboolean. 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 graphas the |
edges | A vector giving the edges of the graph, the same way as for theregular |
directed | Whether to create a directed graph, boolean constant. Notethat by default undirected graphs are created, as this is more common forbipartite graphs. |
... | Passed to |
Details
Bipartite graphs have atype vertex attribute in igraph, this isboolean andFALSE for the vertices of the first kind andTRUEfor vertices of the second kind.
make_bipartite_graph() basically does three things. First it checks theedges vector against the vertextypes. Then it creates a graphusing theedges vector and finally it adds thetypes vector asa vertex attribute calledtype.edges may contain strings asvertex names; in this case,types must be a named vector that specifiesthe type for each vertex name that occurs inedges.
Value
make_bipartite_graph() returns a bipartite igraph graph. In otherwords, an igraph graph that has a vertex attribute namedtype.
is_bipartite() returns a logical scalar.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
make_graph() to create one-mode networks
Bipartite graphsbipartite_mapping(),bipartite_projection(),is_bipartite()
Examples
g <- make_bipartite_graph(rep(0:1, length.out = 10), c(1:10))print(g, v = TRUE)Create an extended chordal ring graph
Description
make_chordal_ring() creates an extended chordal ring.An extended chordal ring is regular graph, each node has the samedegree. It can be obtained from a simple ring by adding some extraedges specified by a matrix. Let p denote the number of columns inthe ‘W’ matrix. The extra edges of vertexiare added according to columni mod p in‘W’. The number of extra edges is the numberof rows in ‘W’: for each rowj an edgei->i+w[ij] is added ifi+w[ij] is less than the numberof total nodes. See also Kotsis, G: Interconnection Topologies forParallel Processing Systems, PARS Mitteilungen 11, 1-6, 1993.
Usage
make_chordal_ring(n, w, directed = FALSE)chordal_ring(...)Arguments
n | The number of vertices. |
w | A matrix which specifies the extended chordal ring. Seedetails below. |
directed | Logical scalar, whether or not to create a directed graph. |
... | Passed to |
Value
An igraph graph.
See Also
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()
Examples
chord <- make_chordal_ring( 15, matrix(c(3, 12, 4, 7, 8, 11), nr = 2))Creates a communities object.
Description
This is useful to integrate the results of community finding algorithmsthat are not included in igraph.
Usage
make_clusters( graph, membership = NULL, algorithm = NULL, merges = NULL, modularity = TRUE)Arguments
graph | The graph of the community structure. |
membership | The membership vector of the community structure, anumeric vector denoting the id of the community for each vertex. Itmight be |
algorithm | Character string, the algorithm that generatedthe community structure, it can be arbitrary. |
merges | A merge matrix, for hierarchical community structures (or |
modularity | Modularity value of the community structure. If thisis |
Value
Acommunities object.
- membership
A numeric vector giving the community id for each vertex.
- modularity
The modularity score of the partition.
- algorithm
If known, the algorithm used to obtain the communities.
- vcount
Number of vertices in the graph.
See Also
Community detectionas_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
Description
De Bruijn graphs are labeled graphs representing the overlap of strings.
Usage
make_de_bruijn_graph(m, n)de_bruijn_graph(...)Arguments
m | Integer scalar, the size of the alphabet. See details below. |
n | Integer scalar, the length of the labels. See details below. |
... | Passed to |
Details
A de Bruijn graph represents relationships between strings. An alphabet ofm letters are used and strings of lengthn are considered. Avertex corresponds to every possible string and there is a directed edgefrom vertexv to vertexw if the string ofv can betransformed into the string ofw by removing its first letter andappending a letter to it.
Please note that the graph will havem to the powern verticesand even more edges, so probably you don't want to supply too big numbersform andn.
De Bruijn graphs have some interesting properties, please see anothersource, e.g. Wikipedia for details.
Value
A graph object.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
make_kautz_graph(),make_line_graph()
Examples
# de Bruijn graphs can be created recursively by line graphs as wellg <- make_de_bruijn_graph(2, 1)make_de_bruijn_graph(2, 2)make_line_graph(g)A graph with no edges
Description
A graph with no edges
Usage
make_empty_graph(n = 0, directed = TRUE)empty_graph(...)Arguments
n | Number of vertices. |
directed | Whether to create a directed graph. |
... | Passed to |
Value
An igraph graph.
Related documentation in the C library
See Also
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()
Examples
make_empty_graph(n = 10)make_empty_graph(n = 5, directed = FALSE)Create an undirected tree graph from its Prüfer sequence
Description
make_from_prufer() creates an undirected tree graph from its Prüfersequence.
Usage
make_from_prufer(prufer)from_prufer(...)Arguments
prufer | The Prüfer sequence to convert into a graph |
... | Passed to |
Details
The Prüfer sequence of a tree graph with n labeled vertices is a sequence ofn-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 ofthe vertex that it was connected to to the sequence. Repeat until there areonly two vertices in the remaining graph.
Value
A graph object.
Related documentation in the C library
See Also
to_prufer() to convert a graph into its Prüfer sequence
Other trees:is_forest(),is_tree(),sample_spanning_tree(),to_prufer()
Examples
g <- make_tree(13, 3)to_prufer(g)Create a full bipartite graph
Description
Bipartite graphs are also called two-mode by some. This function creates abipartite graph in which every possible edge is present.
Usage
make_full_bipartite_graph( n1, n2, directed = FALSE, mode = c("all", "out", "in"))full_bipartite_graph(...)Arguments
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 |
Details
Bipartite graphs have a ‘type’ vertex attribute in igraph,this is boolean andFALSE for the vertices of the first kind andTRUE for vertices of the second kind.
Value
An igraph graph, with the ‘type’ vertex attribute set.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
make_full_graph() for creating one-mode full graphs
Examples
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")Create a complete (full) citation graph
Description
make_full_citation_graph() creates a full citation graph. This is adirected graph, where everyi->j edge is present if and only ifj<i. Ifdirected=FALSE then the graph is just a full graph.
Usage
make_full_citation_graph(n, directed = TRUE)full_citation_graph(...)Arguments
n | The number of vertices. |
directed | Whether to create a directed graph. |
... | Passed to |
Value
An igraph graph.
See Also
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()
Examples
print_all(make_full_citation_graph(10))Create a full graph
Description
Create a full graph
Usage
make_full_graph(n, directed = FALSE, loops = FALSE)full_graph(...)Arguments
n | Number of vertices. |
directed | Whether to create a directed graph. |
loops | Whether to add self-loops to the graph. |
... | Passed to |
Value
An igraph graph
See Also
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()
Examples
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
Description
Create an igraph graph from a list of edges, or a notable graph
Usage
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(...)Arguments
edges | A vector defining the edges, the first edge pointsfrom the first element to the second, the second edge from the thirdto the fourth, etc. For a numeric vector, these are interpretedas internal vertex ids. For character vectors, they are interpretedas vertex names. Alternatively, this can be a character scalar, the name of anotable graph. See Notable graphs below. The name is caseinsensitive. 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 isignored (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. |
Value
An igraph graph.
Notable graphs
make_graph() can create some notable graphs. The name of thegraph (case insensitive), a character scalar must be supplied astheedges argument, and other arguments are ignored. (A warningis given is they are specified.)
make_graph() knows the following graphs:
- Bull
The bull graph, 5 vertices, 5 edges,resembles to the head of a bull if drawn properly.
- Chvatal
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.
- Coxeter
A non-Hamiltonian cubic symmetric graph with 28 vertices and 42 edges.
- Cubical
The Platonic graph of the cube. A convex regular polyhedron with 8 vertices and 12 edges.
- Diamond
A graph with 4 vertices and 5 edges, resembles to a schematic diamond if drawn properly.
- Dodecahedral, Dodecahedron
Another Platonic solid with 20 vertices and 30 edges.
- Folkman
The semisymmetric graph with minimum number of vertices, 20 and 40 edges.A semisymmetric graph is regular, edge transitive and not vertex transitive.
- Franklin
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.
- Frucht
The Frucht Graph is the smallest cubical graphwhose automorphism group consists only of the identity element.It has 12 vertices and 18 edges.
- Grotzsch, Groetzsch
The Grötzsch graph is a triangle-free graph with 11 vertices, 20 edges, and chromatic number 4.It is named after German mathematician Herbert Grötzsch,and its existence demonstrates that the assumption of planarity is necessary in Grötzsch's theoremthat every triangle-free planar graph is 3-colorable.
- Heawood
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.
- Herschel
The Herschel graph is the smallest nonhamiltonian polyhedral graph.It is the unique such graph on 11 nodes, and has 18 edges.
- House
The house graph is a 5-vertex, 6-edge graph, the schematic draw of a house if drawn properly,basically a triangle of the top of a square.
- HouseX
The same as the house graph with an X in the square. 5 vertices and 8 edges.
- Icosahedral, Icosahedron
A Platonic solid with 12 vertices and 30 edges.
- Krackhardt kite
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.
- Levi
The graph is a 4-arc transitive cubic graph, it has 30 vertices and 45 edges.
- McGee
The McGee graph is the unique 3-regular 7-cage graph, it has 24 vertices and 36 edges.
- Meredith
The Meredith graph is a quartic graph on 70 nodes and 140 edgesthat is a counterexample to the conjecture that every 4-regular 4-connected graph is Hamiltonian.
- Noperfectmatching
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.
- Nonline
A graph whose connected components are the 9 graphswhose presence as a vertex-induced subgraph in a graph makes a nonline graph.It has 50 vertices and 72 edges.
- Octahedral, Octahedron
Platonic solid with 6 vertices and 12 edges.
- Petersen
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.
- Robertson
The unique (4,5)-cage graph, i.e. a 4-regular graph of girth 5.It has 19 vertices and 38 edges.
- Smallestcyclicgroup
A smallest nontrivial graph whose automorphism group is cyclic.It has 9 vertices and 15 edges.
- Tetrahedral,Tetrahedron
Platonic solid with 4 vertices and 6 edges.
- Thomassen
The smallest hypotraceable graph, on 34 vertices and 52 edges.A hypotraceable graph does not contain a Hamiltonian pathbut after removing any single vertex from it the remainder always contains a Hamiltonian path.A graph containing a Hamiltonian path is called traceable.
- Tutte
Tait's Hamiltonian graph conjecture statesthat every 3-connected 3-regular planar graph is Hamiltonian.This graph is a counterexample.It has 46 vertices and 69 edges.
- Uniquely3colorable
Returns a 12-vertex, triangle-free graph with chromatic number 3 that is uniquely 3-colorable.
- Walther
An identity graph with 25 vertices and 31 edges.An identity graph has a single graph automorphism, the trivial one.
- Zachary
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).
See Also
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()
Examples
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
Description
Kautz graphs are labeled graphs representing the overlap of strings.
Usage
make_kautz_graph(m, n)kautz_graph(...)Arguments
m | Integer scalar, the size of the alphabet. See details below. |
n | Integer scalar, the length of the labels. See details below. |
... | Passed to |
Details
A Kautz graph is a labeled graph, vertices are labeled by strings of lengthn+1 above an alphabet withm+1 letters, with the restrictionthat every two consecutive letters in the string must be different. There isa directed edge from a vertexv to another vertexw if it ispossible to transform the string ofv into the string ofw byremoving the first letter and appending a letter to it.
Kautz graphs have some interesting properties, see e.g. Wikipedia fordetails.
Value
A graph object.
Author(s)
Gabor Csardicsardi.gabor@gmail.com, the first version in R waswritten by Vincent Matossian.
See Also
make_de_bruijn_graph(),make_line_graph()
Examples
make_line_graph(make_kautz_graph(2, 1))make_kautz_graph(2, 2)Create a lattice graph
Description
make_lattice() is a flexible function, it can create lattices ofarbitrary dimensions, periodic or aperiodic ones. It has twoforms. In the first form you only supplydimvector, but notlength anddim. In the second form you omitdimvector and supplylength anddim.
Usage
make_lattice( dimvector = NULL, length = NULL, dim = NULL, nei = 1, directed = FALSE, mutual = FALSE, periodic = FALSE, circular = deprecated())lattice(...)Arguments
dimvector | A vector giving the size of the lattice in eachdimension. |
length | Integer constant, for regular lattices, the size of thelattice in each dimension. |
dim | Integer constant, the dimension of the lattice. |
nei | The distance within which (inclusive) the neighbors on thelattice 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 isperiodic along each dimension. This parameter may also be scalar boolen value which willbe extended to boolean vector with dimvector length. |
circular | Deprecated, use |
... | Passed to |
Value
An igraph graph.
Related documentation in the C library
See Also
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()
Examples
make_lattice(c(5, 5, 5))make_lattice(length = 5, dim = 3)Line graph of a graph
Description
This function calculates the line graph of another graph.
Usage
make_line_graph(graph)line_graph(...)Arguments
graph | The input graph, it can be directed or undirected. |
... | Passed to |
Details
The line graphL(G) of aG undirected graph is defined asfollows.L(G) has one vertex for each edge inG and twovertices inL(G) are connected by an edge if their correspondingedges share an end point.
The line graphL(G) of aG directed graph is slightlydifferent,L(G) has one vertex for each edge inG and twovertices inL(G) are connected by a directed edge if the target ofthe first vertex's corresponding edge is the same as the source of thesecond vertex's corresponding edge.
Value
A new graph object.
Author(s)
Gabor Csardicsardi.gabor@gmail.com, the first version ofthe C code was written by Vincent Matossian.
Examples
# generate the first De-Bruijn graphsg <- 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)))Create a ring graph
Description
A ring is a one-dimensional lattice and this function is a special caseofmake_lattice().
Usage
make_ring(n, directed = FALSE, mutual = FALSE, circular = TRUE)ring(...)Arguments
n | Number of vertices. |
directed | Whether the graph is directed. |
mutual | Whether directed edges are mutual. It is ignored inundirected graphs. |
circular | Whether to create a circular ring. A non-circularring is essentially a “line”: a tree where every non-leafvertex has one child. |
... | Passed to |
Value
An igraph graph.
See Also
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()
Examples
print_all(make_ring(10))print_all(make_ring(10, directed = TRUE, mutual = TRUE))Create a star graph, a tree with n vertices and n - 1 leaves
Description
star() creates a star graph, in this every single vertex isconnected to the center vertex and nobody else.
Usage
make_star(n, mode = c("in", "out", "mutual", "undirected"), center = 1)star(...)Arguments
n | Number of vertices. |
mode | It defines the direction of theedges, |
center | ID of the center vertex. |
... | Passed to |
Value
An igraph graph.
See Also
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()
Examples
make_star(10, mode = "out")make_star(5, mode = "undirected")Create tree graphs
Description
Create a k-ary tree graph, where almost all vertices other than the leaveshave the same number of children.
Usage
make_tree(n, children = 2, mode = c("out", "in", "undirected"))tree(...)Arguments
n | Number of vertices. |
children | Integer scalar, the number of children of a vertex(except for leafs) |
mode | Defines the direction of theedges. |
... | Passed to |
Value
An igraph graph
See Also
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()
Examples
make_tree(10, 2)make_tree(10, 3, mode = "undirected")Match Graphs given a seeding of vertex correspondences
Description
Given two adjacency matricesA andB of the same size, matchthe two graphs with the help ofm seed vertex pairs which correspondto the firstm rows (and columns) of the adjacency matrices.
Usage
match_vertices(A, B, m, start, iteration)Arguments
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 isinitialized with |
iteration | The number of iterations for the Frank-Wolfe algorithm |
Details
The approximate graph matching problem is to find a bijection between thevertices of two graphs , such that the number of edge disagreements betweenthe corresponding vertex pairs is minimized. For seeded graph matching, partof the bijection that consist of known correspondences (the seeds) is knownand the problem task is to complete the bijection by estimating thepermutation matrix that permutes the rows and columns of the adjacencymatrix of the second graph.
It is assumed that for the two supplied adjacency matricesA andB, both of sizen\times n, the firstm rows(andcolumns) ofA andB correspond to the same vertices in bothgraphs. That is, then \times n permutation matrix that definesthe bijection isI_{m} \bigoplus P for a(n-m)\times(n-m) permutation matrixP andm timesmidentity matrixI_{m}. The functionmatch_vertices() estimatesthe permutation matrixP via an optimization algorithm based on theFrank-Wolfe algorithm.
See references for further details.
Value
A numeric matrix which is the permutation matrix that determines thebijection between the graphs ofA andB
Author(s)
Vince Lyzinskihttps://www.ams.jhu.edu/~lyzinski/
References
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 MatchingOnline:https://arxiv.org/abs/1209.0367
See Also
sample_correlated_gnp(),sample_correlated_gnp_pair()
Examples
# 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)PMaximum cardinality search
Description
Maximum cardinality search is a simple ordering a vertices that is useful indetermining the chordality of a graph.
Usage
max_cardinality(graph)Arguments
graph | The input graph. It may be directed, but edge directions areignored, as the algorithm is defined for undirected graphs. |
Details
Maximum cardinality search visits the vertices in such an order that everytime the vertex with the most already visited neighbors is visited. Ties arebroken randomly.
The algorithm provides a simple basis for deciding whether a graph ischordal, see References below, and alsois_chordal().
Value
A list with two components:
- alpha
Numeric vector. The 1-based rank of each vertex in the graphsuch 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
alpha.In other words, the elements of this vector are the vertices in reverse maximum cardinality search order.
Related documentation in the C library
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
Robert E Tarjan and Mihalis Yannakakis. (1984). Simplelinear-time algorithms to test chordality of graphs, test acyclicity ofhypergraphs, and selectively reduce acyclic hypergraphs.SIAM Journalof Computation 13, 566–579.
See Also
Other chordal:is_chordal()
Examples
## The examples from the Tarjan-Yannakakis paperg1 <- 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)Maximum flow in a graph
Description
In a graph where each edge has a given flow capacity the maximal flowbetween two vertices is calculated.
Usage
max_flow(graph, source, target, capacity = NULL)Arguments
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 |
Details
max_flow() calculates the maximum flow between two vertices in aweighted (i.e. valued) graph. A flow fromsource totarget isan assignment of non-negative real numbers to the edges of the graph,satisfying two properties: (1) for each edge the flow (i.e. the assignednumber) is not more than the capacity of the edge (thecapacityparameter or edge attribute), (2) for every vertex, except the source andthe target the incoming flow is the same as the outgoing flow. The value ofthe flow is the incoming flow of thetarget vertex. The maximum flowis the flow of maximum value.
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:
nopushis the number of push operations,norelabelthe number of relabelings,nogapis the number of times the gap heuristics was used,nogapnodesis the total number of gap nodes omitted because of the gap heuristics andnobfsis the number of times a global breadth-first-search update was performedto assign better height (=distance) values to the vertices.
Related documentation in the C library
References
A. V. Goldberg and R. E. Tarjan: A New Approach to the MaximumFlow ProblemJournal of the ACM 35:921-940, 1988.
See Also
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()
Examples
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"])Calculate Cohesive Blocks
Description
maxcohesion() was renamed tomax_cohesion() to create a moreconsistent API.
Usage
maxcohesion(blocks)Functions to find cliques, i.e. complete subgraphs in a graph
Description
maximal.cliques() was renamed tomax_cliques() to create a moreconsistent API.
Usage
maximal.cliques(graph, min = NULL, max = NULL, subset = NULL, file = NULL)Arguments
graph | The input graph. |
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 |
Functions to find cliques, i.e. complete subgraphs in a graph
Description
maximal.cliques.count() was renamed tocount_max_cliques() to create a moreconsistent API.
Usage
maximal.cliques.count(graph, min = NULL, max = NULL, subset = NULL)Arguments
graph | The input graph. |
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 |
Independent vertex sets
Description
maximal.independent.vertex.sets() was renamed tomax_ivs() to create a moreconsistent API.
Usage
maximal.independent.vertex.sets(graph)Arguments
graph | The input graph. |
Maximal independent vertex sets in the graph
Description
maximal_ivs() was renamed tomax_ivs() to create a moreconsistent API.
Usage
maximal_ivs(graph)Arguments
graph | The input graph. |
Matching
Description
maximum.bipartite.matching() was renamed tomax_bipartite_match() to create a moreconsistent API.
Usage
maximum.bipartite.matching( graph, types = NULL, weights = NULL, eps = .Machine$double.eps)Arguments
graph | The input graph. It might be directed, but edge directions willbe ignored. |
types | Vertex types, if the graph is bipartite. By default theyare taken from the ‘ |
weights | Potential edge weights. If the graph has an edgeattribute called ‘ |
eps | A small real number used in equality tests in the weightedbipartite matching algorithm. Two real numbers are considered equal inthe algorithm if their difference is smaller than |
Maximum cardinality search
Description
maximum.cardinality.search() was renamed tomax_cardinality() to create a moreconsistent API.
Usage
maximum.cardinality.search(graph)Arguments
graph | The input graph. It may be directed, but edge directions areignored, as the algorithm is defined for undirected graphs. |
Functions to deal with the result of network community detection
Description
igraph community detection functions return their results as an object fromthecommunities class. This manual page describes the operations ofthis class.
Usage
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)Arguments
communities,x,object | A |
... | Additional arguments. |
graph | An igraph graph object, corresponding to |
hang | Numeric scalar indicating how the height of leaves should becomputed from the heights of their parents; see |
use.modularity | Logical scalar, whether to use the modularity valuesto define the height of the branches. |
no | Integer scalar, the desired number of communities. If too low ortwo high, then an error message is given. Exactly one of |
steps | The number of merge operations to perform to produce thecommunities. 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 regularR plotting methods. This vector gives the colors of the vertices explicitly. |
mark.groups | A list of numeric vectors. The communities can behighlighted using colored polygons. The groups for which the polygons aredrawn are given here. The default is to use the groups given by thecommunities. Supply |
edge.color | The colors of the edges. By default the edges withincommunities are colored green and other edges are red. |
membership | Numeric vector, one value for each vertex, the membershipvector of the community structure. Might also be |
algorithm | If not |
merges | If not |
modularity | Numeric scalar or vector, the modularity value of thecommunity structure. It can also be |
Details
Community structure detection algorithms try to find dense subgraphs indirected or undirected graphs, by optimizing some criteria, and usuallyusing heuristics.
igraph implements a number of community detection methods (see them below),all of which return an object of the classcommunities. Because thecommunity structure detection algorithms are different,communitiesobjects do not always have the same structure. Nevertheless, they have somecommon operations, these are documented here.
Theprint() generic function is defined forcommunities, itprints a short summary.
Thelength generic function call be called oncommunities andreturns the number of communities.
Thesizes() function returns the community sizes, in the order of theirids.
membership() gives the division of the vertices, into communities. Itreturns a numeric vector, one value for each vertex, the id of itscommunity. Community ids start from one. Note that some algorithms calculatethe complete (or incomplete) hierarchical structure of the communities, andnot just a single partitioning. For these algorithms typically themembership for the highest modularity value is returned, but see also themanual pages of the individual algorithms.
communities() is also the name of a function, that returns a list ofcommunities, each identified by their vertices. The vertices will havesymbolic names if theadd.vertex.names igraph option is set, and thegraph itself was named. Otherwise numeric vertex ids are used.
modularity() gives the modularity score of the partitioning. (Seemodularity.igraph() for details. For algorithms that do notresult a single partitioning, the highest modularity value is returned.
algorithm() gives the name of the algorithm that was used to calculatethe community structure.
crossing() returns a logical vector, with one value for each edge,ordered according to the edge ids. The value isTRUE iff the edgeconnects two different communities, according to the (best) membershipvector, as returned bymembership().
is_hierarchical() checks whether a hierarchical algorithm was used tofind the community structure. Some functions only make sense forhierarchical methods (e.g.merges(),cut_at() andas.dendrogram()).
merges() returns the merge matrix for hierarchical methods. An errormessage is given, if a non-hierarchical method was used to find thecommunity structure. You can check this by callingis_hierarchical() onthecommunities 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 canbe expressed as the desired number of communities or as the number of mergesteps to make. The function gives an error message, if called with anon-hierarchical method.
as.dendrogram() converts a hierarchical community structure to adendrogram object. It only works for hierarchical methods, and givesan error message to others. Seestats::dendrogram() for details.
stats::as.hclust() is similar toas.dendrogram(), but converts ahierarchical community structure to ahclust object.
ape::as.phylo() converts a hierarchical community structure to aphyloobject, you will need theape package for this.
show_trace() works (currently) only for communities found by the leadingeigenvector method (cluster_leading_eigen()), andreturns a character vector that gives the steps performed by the algorithmwhile finding the communities.
code_len() is defined for the InfoMAP method(cluster_infomap() and returns the code length of thepartition.
It is possibly to call theplot() function oncommunitiesobjects. This will plot the graph (and usesplot.igraph()internally), with the communities shown. By default it colores the verticesaccording to their communities, and also marks the vertex groupscorresponding to the communities. It passes additional arguments toplot.igraph(), please see that and alsoigraph.plotting on how to change the plot.
Value
print() returns thecommunities object itself,invisibly.
length returns an integer scalar.
sizes() returns a numeric vector.
membership() returns a numeric vector, one number for each vertex inthe 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 thevertices.
as.dendrogram() returns adendrogram object.
show_trace() returns a character vector.
code_len() returns a numeric scalar for communities found with theInfoMAP method andNULL for other methods.
plot() forcommunities objects returnsNULL, invisibly.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
Seeplot_dendrogram() for plotting community structuredendrograms.
Seecompare() for comparing two community structureson the same graph.
Community detectionas_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()
Examples
karate <- make_graph("Zachary")wc <- cluster_walktrap(karate)modularity(wc)membership(wc)plot(wc, karate)Merging graph layouts
Description
Place several graphs on the same layout
Usage
merge_coords(graphs, layouts, method = "dla")layout_components(graph, layout = layout_with_kk, ...)Arguments
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 |
Details
merge_coords() takes a list of graphs and a list of coordinates andplaces the graphs in a common layout. The method to use is chosen via themethod parameter, although right now only thedla method isimplemented.
Thedla method covers the graph with circles. Then it sorts thegraphs based on the number of vertices first and places the largest graph atthe center of the layout. Then the other graphs are placed in decreasingorder via a DLA (diffision limited aggregation) algorithm: the graph isplaced randomly on a circle far away from the center and a random walk isconducted until the graph walks into the larger graphs already placed orwalks too far from the center of the layout.
Thelayout_components() function disassembles the graph first intomaximal connected components and calls the suppliedlayout functionfor each component separately. Finally it merges the layouts via callingmerge_coords().
Value
A matrix with two columns and as many lines as the total number ofvertices in the graphs.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
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()
Examples
# create 20 scale-free graphs and place them in a common layoutgraphs <- 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")Minimum cut in a graph
Description
min_cut() calculates the minimum st-cut between two vertices in a graph(if thesource andtarget arguments are given) or the minimumcut of the graph (if bothsource andtarget areNULL).
Usage
min_cut( graph, source = NULL, target = NULL, capacity = NULL, value.only = TRUE)Arguments
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 |
Details
The minimum st-cut betweensource andtarget is the minimumtotal weight of edges needed to remove to eliminate all paths fromsource totarget.
The minimum cut of a graph is the minimum total weight of the edges neededto remove to separate the graph into (at least) two components. (Which is tomake the graphnot strongly connected in the directed case.)
The maximum flow between two vertices in a graph is the same as the minimumst-cut, somax_flow() andmin_cut() essentially calculate the samequantity, the only difference is thatmin_cut() can be invoked withoutgiving thesource andtarget arguments and then minimum of allpossible minimum cuts is calculated.
For undirected graphs the Stoer-Wagner algorithm (see reference below) isused to calculate the minimum cut.
Value
Formin_cut() a nuieric constant, the value of the minimumcut, except ifvalue.only = FALSE. In this case a named list withcomponents:
- 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.
References
M. Stoer and F. Wagner: A simple min-cut algorithm,Journal of the ACM, 44 585-591, 1997.
See Also
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()
Examples
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)Minimum size vertex separators
Description
Find all vertex sets of minimal size whose removal separates the graph intomore components
Usage
min_separators(graph)Arguments
graph | The input graph. It may be directed, but edge directions areignored. |
Details
This function implements the Kanevsky algorithm for finding all minimal-sizevertex separators in an undirected graph. See the reference below for thedetails.
In the special case of a fully connected input graph withn vertices,all subsets of sizen-1 are listed as the result.
Value
A list of numeric vectors. Each numeric vector is a vertexseparator.
Related documentation in the C library
References
Arkady Kanevsky: Finding all minimum-size separating vertex setsin 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: Ahierarchical concept of social groups.American Sociological Review,68 103–127, Feb 2003.
See Also
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()
Examples
# The graph from the Moody-White papermw <- 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 subgraphsmw1 <- 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 networkcamp <- 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)Minimum size vertex separators
Description
List all vertex sets that are minimal(s,t) separators for somes andt, in an undirected graph.
Usage
min_st_separators(graph)Arguments
graph | The input graph. It may be directed, but edge directions areignored. |
Details
A(s,t) vertex separator is a set of vertices, such that after theirremoval from the graph, there is no path betweens andt in thegraph.
A(s,t) vertex separator is minimal if none of its proper subsets isan(s,t) vertex separator for the sames andt.
Value
A list of numeric vectors. Each vector contains a vertex set(defined by vertex ids), each vector is an (s,t) separator of the inputgraph, for somes andt.
Note
Note that the code below returns{1, 3} despite its subset{1} being aseparator as well. This is because{1, 3} is minimal with respect toseparating 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
Related documentation in the C library
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
Anne Berry, Jean-Paul Bordat and Olivier Cogis: Generating Allthe Minimal Separators of a Graph, In: Peter Widmayer, Gabriele Neyer andStephan Eidenbenz (editors):Graph-theoretic concepts in computerscience, 1665, 167–172, 1999. Springer.
See Also
Other flow:dominator_tree(),edge_connectivity(),is_min_separator(),is_separator(),max_flow(),min_cut(),min_separators(),st_cuts(),st_min_cuts(),vertex_connectivity()
Examples
ring <- make_ring(4)min_st_separators(ring)chvatal <- make_graph("chvatal")min_st_separators(chvatal)# https://github.com/r-lib/roxygen2/issues/1092Minimum size vertex separators
Description
minimal.st.separators() was renamed tomin_st_separators() to create a moreconsistent API.
Usage
minimal.st.separators(graph)Arguments
graph | The input graph. It may be directed, but edge directions areignored. |
Minimum size vertex separators
Description
minimum.size.separators() was renamed tomin_separators() to create a moreconsistent API.
Usage
minimum.size.separators(graph)Arguments
graph | The input graph. It may be directed, but edge directions areignored. |
Minimum spanning tree
Description
minimum.spanning.tree() was renamed tomst() to create a moreconsistent API.
Usage
minimum.spanning.tree(graph, weights = NULL, algorithm = NULL, ...)Arguments
graph | The graph object to analyze. |
weights | Numeric vector giving the weights of the edges in thegraph. The order is determined by the edge ids. This is ignored if the |
algorithm | The algorithm to use for calculation. |
... | Additional arguments, unused. |
Modularity of a community structure of a graph
Description
mod.matrix() was renamed tomodularity_matrix() to create a moreconsistent API.
Usage
mod.matrix(graph, membership, weights = NULL, resolution = 1, directed = TRUE)Arguments
membership | Numeric vector, one value for each vertex, the membershipvector of the community structure. |
weights | If not |
resolution | The resolution parameter. Must be greater than or equal to0. Set it to 1 to use the classical definition of modularity. |
directed | Whether to use the directed or undirected version ofmodularity. Ignored for undirected graphs. |
Modularity of a community structure of a graph
Description
This function calculates how modular is a given division of a graph intosubgraphs.
Usage
## 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)Arguments
x,graph | The input graph. |
membership | Numeric vector, one value for each vertex, the membershipvector of the community structure. |
weights | If not |
resolution | The resolution parameter. Must be greater than or equal to0. Set it to 1 to use the classical definition of modularity. |
directed | Whether to use the directed or undirected version ofmodularity. Ignored for undirected graphs. |
... | Additional arguments, none currently. |
Details
modularity() calculates the modularity of a graph with respect to thegivenmembership 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 vertextypes from each other. It defined as
Q=\frac{1}{2m} \sum_{i,j}(A_{ij}-\gamma\frac{k_i k_j}{2m})\delta(c_i,c_j),
herem is the number of edges,A_{ij}is the element of theA adjacency matrix in rowi and columnj,k_i is the degree ofi,k_j is the degreeofj,c_i is the type (or component) ofi,c_j that ofj, the sum goes over alli andjpairs of vertices, and\delta(x,y) is 1 ifx=y and 0otherwise. For directed graphs, it is defined as
Q = \frac{1}{m} \sum_{i,j} (A_{ij}-\gamma\frac{k_i^{out} k_j^{in}}{m})\delta(c_i,c_j).
The resolution parameter\gamma allows weighting the randomnull model, which might be useful when finding partitions with a highmodularity. Maximizing modularity with higher values of the resolutionparameter typically results in more, smaller clusters when findingpartitions with a high modularity. Lower values typically results in fewer,larger clusters. The original definition of modularity is retrieved whensetting\gamma to 1.
If edge weights are given, then these are considered as the element of theA adjacency matrix, andk_i is the sum of weights ofadjacent edges for vertexi.
modularity_matrix() calculates the modularity matrix. This is a dense matrix,and it is defined as the difference of the adjacency matrix and theconfiguration model null model matrix. In other words elementM_{ij} is given asA_{ij}-d_id_j/(2m), whereA_{ij} is the (possiblyweighted) adjacency matrix,d_i is the degree of vertexi,andm is the number of edges (or the total weights in the graph, if itis weighed).
Value
Formodularity() a numeric scalar, the modularity score of thegiven configuration.
Formodularity_matrix() a numeric square matrix, its order is the number ofvertices in the graph.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
Clauset, A.; Newman, M. E. J. & Moore, C. Finding communitystructure in very large networks,Physical Review E 2004, 70, 066111
See Also
cluster_walktrap(),cluster_edge_betweenness(),cluster_fast_greedy(),cluster_spinglass(),cluster_louvain() andcluster_leiden() forvarious community detection methods.
Community detectionas_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()
Examples
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
Description
Graph motifs are small connected induced subgraphs with a well-definedstructure. These functions search a graph for various motifs.
Usage
motifs(graph, size = 3, cut.prob = NULL)Arguments
graph | Graph object, the input graph. |
size | The size of the motif, currently sizes 3 and 4 are supported indirected graphs and sizes 3-6 in undirected graphs. |
cut.prob | Numeric vector giving the probabilities that the searchgraph is cut at a certain level. Its length should be the same as the sizeof the motif (the |
Details
motifs() searches a graph for motifs of a given size and returns anumeric vector containing the number of different motifs. The order ofthe motifs is defined by their isomorphism class, seeisomorphism_class().
Value
motifs() returns a numeric vector, the number of occurrences ofeach motif in the graph. The motifs are ordered by their isomorphismclasses. Note that for unconnected subgraphs, which are not considered to bemotifs, the result will beNA.
See Also
Other graph motifs:count_motifs(),dyad_census(),sample_motifs()
Examples
g <- sample_pa(100)motifs(g, 3)count_motifs(g, 3)sample_motifs(g, 3)Minimum spanning tree
Description
Aspanning tree of a connected graph is a connected subgraph withthe smallest number of edges that includes all vertices of the graph.A graph will have many spanning trees. Among these, theminimum spanningtree will have the smallest sum of edge weights.
Usage
mst(graph, weights = NULL, algorithm = NULL, ...)Arguments
graph | The graph object to analyze. |
weights | Numeric vector giving the weights of the edges in thegraph. The order is determined by the edge ids. This is ignored if the |
algorithm | The algorithm to use for calculation. |
... | Additional arguments, unused. |
Details
Theminimum spanning forest of a disconnected graph is the collectionof minimum spanning trees of all of its components.
If the graph is not connected a minimum spanning forest is returned.
Value
A graph object with the minimum spanning forest. To check whether itis a tree, check that the number of its edges isvcount(graph)-1.The edge and vertex attributes of the original graph are preserved in theresult.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
Prim, R.C. 1957. Shortest connection networks and somegeneralizationsBell System Technical Journal, 37 1389–1401.
See Also
Examples
g <- sample_gnp(100, 3 / 100)g_mst <- mst(g)Finding community structure by multi-level optimization of modularity
Description
multilevel.community() was renamed tocluster_louvain() to create a moreconsistent API.
Usage
multilevel.community(graph, weights = NULL, resolution = 1)Arguments
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 toadjust the resolution parameter of the modularity function that the algorithmuses internally. Lower values typically yield fewer, larger clusters. Theoriginal definition of modularity is recovered when the resolution parameteris set to 1. |
Neighborhood of graph vertices
Description
neighborhood.size() was renamed toego_size() to create a moreconsistent API.
Usage
neighborhood.size( graph, order = 1, nodes = V(graph), mode = c("all", "out", "in"), mindist = 0)Arguments
graph | The input graph. |
order | Integer giving the order of the neighborhood. Negative valuesindicate an infinite order. |
nodes | The vertices for which the calculation is performed. |
mode | Character constant, it specifies how to use the direction ofthe edges if a directed graph is analyzed. For ‘out’ only theoutgoing edges are followed, so all vertices reachable from the sourcevertex in at most |
mindist | The minimum distance to include the vertex in the result. |
Neighboring (adjacent) vertices in a graph
Description
A vertex is a neighbor of another one (in other words, the twovertices are adjacent), if they are incident to the same edge.
Usage
neighbors(graph, v, mode = c("out", "in", "all", "total"))Arguments
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 isignored for undirected graphs. |
Value
A vertex sequence containing the neighbors of the input vertex.
See Also
Other structural queries:[.igraph(),[[.igraph(),adjacent_vertices(),are_adjacent(),ends(),get_edge_ids(),gorder(),gsize(),head_of(),incident(),incident_edges(),is_directed(),tail_of()
Examples
g <- make_graph("Zachary")n1 <- neighbors(g, 1)n34 <- neighbors(g, 34)intersection(n1, n34)Connected components of a graph
Description
no.clusters() was renamed tocount_components() to create a moreconsistent API.
Usage
no.clusters(graph, mode = c("weak", "strong"))Arguments
graph | The graph to analyze. |
mode | Character string, either “weak” or “strong”. Fordirected graphs “weak” implies weakly, “strong” stronglyconnected components to search. It is ignored for undirected graphs. |
Normalize coordinates for plotting graphs
Description
Rescale coordinates linearly to be within given bounds.
Usage
norm_coords( layout, xmin = -1, xmax = 1, ymin = -1, ymax = 1, zmin = -1, zmax = 1)Arguments
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 bothare |
ymin,ymax | The limits for the second coordinate, if one of them orboth are |
zmin,zmax | The limits for the third coordinate, if one of them or bothare |
Details
norm_coords() normalizes a layout, it linearly transforms eachcoordinate separately to fit into the given limits.
Value
A numeric matrix with at the same dimension aslayout.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
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()
Normalize layout
Description
Scale coordinates of a layout.
Usage
normalize( xmin = -1, xmax = 1, ymin = xmin, ymax = xmax, zmin = xmin, zmax = xmax)Arguments
xmin,xmax | Minimum and maximum for x coordinates. |
ymin,ymax | Minimum and maximum for y coordinates. |
zmin,zmax | Minimum and maximum for z coordinates. |
See Also
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()
Examples
layout_(make_ring(10), with_fr(), normalize())Optimal community structure
Description
optimal.community() was renamed tocluster_optimal() to create a moreconsistent API.
Usage
optimal.community(graph, weights = NULL)Arguments
graph | The input graph. It may be undirected or directed. |
weights | The weights of the edges. It must be a positive numericvector, |
The Page Rank algorithm
Description
page.rank() was renamed topage_rank() to create a moreconsistent API.
Usage
page.rank( graph, algo = c("prpack", "arpack"), vids = V(graph), directed = TRUE, damping = 0.85, personalized = NULL, weights = NULL, options = NULL)Arguments
graph | The graph object. |
algo | Character scalar, which implementation to use to carry out thecalculation. The default is |
vids | The vertices of interest. |
directed | Logical, if true directed paths will be considered fordirected graphs. It is ignored for undirected graphs. |
damping | The damping factor (‘d’ in the original paper). |
personalized | Optional vector giving a probability distribution tocalculate personalized PageRank. For personalized PageRank, the probabilityof jumping to a node when abandoning the random walk is not uniform, but itis given by this vector. The vector should contains an entry for each vertexand it will be rescaled to sum up to one. |
weights | A numerical vector or |
options | A named list, to override some ARPACK options. See |
The Page Rank algorithm
Description
Calculates the Google PageRank for the specified vertices.
Usage
page_rank( graph, algo = c("prpack", "arpack"), vids = V(graph), directed = TRUE, damping = 0.85, personalized = NULL, weights = NULL, options = NULL)Arguments
graph | The graph object. |
algo | Character scalar, which implementation to use to carry out thecalculation. The default is |
vids | The vertices of interest. |
directed | Logical, if true directed paths will be considered fordirected graphs. It is ignored for undirected graphs. |
damping | The damping factor (‘d’ in the original paper). |
personalized | Optional vector giving a probability distribution tocalculate personalized PageRank. For personalized PageRank, the probabilityof jumping to a node when abandoning the random walk is not uniform, but itis given by this vector. The vector should contains an entry for each vertexand it will be rescaled to sum up to one. |
weights | A numerical vector or |
options | A named list, to override some ARPACK options. See |
Details
For the explanation of the PageRank algorithm, see the following webpage:http://infolab.stanford.edu/~backrub/google.html, or the followingreference:
Sergey Brin and Larry Page: The Anatomy of a Large-Scale Hypertextual WebSearch Engine. Proceedings of the 7th World-Wide Web Conference, Brisbane,Australia, April 1998.
Thepage_rank() function can use either the PRPACK library or ARPACK(seearpack()) to perform the calculation.
Please note that the PageRank of a given vertex depends on the PageRank ofall other vertices, so even if you want to calculate the PageRank for onlysome of the vertices, all of them must be calculated. Requesting thePageRank for only some of the vertices does not result in any performanceincrease at all.
Value
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
arpack()for details. This entry isNULLif not the ARPACK implementation was used.
Related documentation in the C library
Author(s)
Tamas Nepuszntamas@gmail.com and Gabor Csardicsardi.gabor@gmail.com
References
Sergey Brin and Larry Page: The Anatomy of a Large-ScaleHypertextual Web Search Engine. Proceedings of the 7th World-Wide WebConference, Brisbane, Australia, April 1998.
See Also
Other centrality scores:closeness(),betweenness(),degree()
Centrality measuresalpha_centrality(),authority_score(),betweenness(),closeness(),diversity(),eigen_centrality(),harmonic_centrality(),hits_scores(),power_centrality(),spectrum(),strength(),subgraph_centrality()
Examples
g <- sample_gnp(20, 5 / 20, directed = TRUE)page_rank(g)$vectorg2 <- make_star(10)page_rank(g2)$vector# Personalized PageRankg3 <- make_ring(10)page_rank(g3)$vectorreset <- seq(vcount(g3))page_rank(g3, personalized = reset)$vectorHelper function to add or delete edges along a path
Description
This function can be used to add or delete edges that form a path.
Usage
path(...)Arguments
... | See details below. |
Details
When adding edges via+, all unnamed arguments areconcatenated, and each element of a final vector is interpretedas a vertex in the graph. For a vector of lengthn+1,nedges are then added, from vertex 1 to vertex 2, from vertex 2 to vertex3, etc. Named arguments will be used as edge attributes for the newedges.
When deleting edges, all attributes are concatenated and then passedtodelete_edges().
Value
A special object that can be used together with igraphgraphs and the plus and minus operators.
See Also
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()
Examples
# Create a (directed) wheelg <- 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)[[]]Shortest (directed or undirected) paths between vertices
Description
path.length.hist() was renamed todistance_table() to create a moreconsistent API.
Usage
path.length.hist(graph, directed = TRUE)Arguments
graph | The graph to work on. |
directed | Whether to consider directed paths in directed graphs,this argument is ignored for undirected graphs. |
Permute the vertices of a graph
Description
Create a new graph, by permuting vertex ids.
Usage
permute(graph, permutation)Arguments
graph | The input graph, it can directed or undirected. |
permutation | A numeric vector giving the permutation to apply. Thefirst element is the new id of vertex 1, etc. Every number between one and |
Details
This function creates a new graph from the input graph by permuting itsvertices according to the specified mapping. Call this function with theoutput ofcanonical_permutation() to create the canonical formof a graph.
permute() keeps all graph, vertex and edge attributes of the graph.
Value
A new graph object.
Related documentation in the C library
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
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()
Examples
# Random permutation of a random graphg <- sample_gnm(20, 50)g2 <- permute(g, sample(vcount(g)))isomorphic(g, g2)# Permutation keeps all attributesg$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)))isomorphic(g, g2)g2$nameV(g2)$nameE(g2)$weightall(sort(E(g2)$weight) == sort(E(g)$weight))Permute the vertices of a graph
Description
permute.vertices() was renamed topermute() to create a moreconsistent API.
Usage
permute.vertices(graph, permutation)Arguments
graph | The input graph, it can directed or undirected. |
permutation | A numeric vector giving the permutation to apply. Thefirst element is the new id of vertex 1, etc. Every number between one and |
Merging graph layouts
Description
piecewise.layout() was renamed tolayout_components() to create a moreconsistent API.
Usage
piecewise.layout(graph, layout = layout_with_kk, ...)Arguments
graph | The input graph. |
layout | A function object, the layout function to use. |
... | Additional arguments to pass to the |
Drawing graphs
Description
The common bits of the three plotting functionsplot.igraph,tkplot andrglplot are discussed in this manual page.
Details
There are currently three different functions in the igraph package whichcan draw graph in various ways:
plot.igraph does simple non-interactive 2D plotting to R devices.Actually it is an implementation of thegraphics::plot() genericfunction, so you can writeplot(graph) instead ofplot.igraph(graph). As it used the standard R devices it supportsevery output format for which R has an output device. The list is quiteimpressing: PostScript, PDF files, XFig files, SVG files, JPG, PNG and ofcourse you can plot to the screen as well using the default devices, or thegood-looking anti-aliased Cairo device. Seeplot.igraph() forsome more information.
tkplot() does interactive 2D plotting using thetcltkpackage. It can only handle graphs of moderate size, a thousand vertices isprobably already too many. Some parameters of the plotted graph can bechanged interactively after issuing thetkplot command: the position,color and size of the vertices and the color and width of the edges. Seetkplot() for details.
rglplot() is an experimental function to draw graphs in 3D usingOpenGL. Seerglplot() for some more information.
Please also check the examples below.
How to specify graphical parameters
There are three ways to givevalues to the parameters described below, in section 'Parameters'. We givethese 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 globalparameters have no prefix. Eg. the color of the vertices can be given viaargumentvertex.color, whereasedge.color sets the color ofthe 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 fromthecolor vertex attribute and the color of the edges from thecolor edge attribute. The layout of the graph is given by thelayout graph attribute. (Always assuming that the correspondingcommand argument is not present.) Setting vertex and edge attributes arehandy if you want to assign a given ‘look’ to a graph, attributes aresaved with the graph is you save it withbase::save() or inGraphML format withwrite_graph(), so the graph will have thesame look after loading it again.
If a parameter is not given in the command line, and the correspondingvertex/edge/graph attribute is also missing then the general igraphparameters handled byigraph_options() are also checked. Vertexparameters have prefix ‘vertex.’, edge parameters are prefixedwith ‘edge.’, general parameters likelayout areprefixed with ‘plot’. These parameters are useful if you wantall 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'tneed to assign vertex/edge attributes to every graph.
If the value of a parameter is not specified by any of the three waysdescribed here, its default valued is used, as given in the source code.
Different parameters can have different type, eg. vertex colors can be givenas a character vector with color names, or as an integer vector with thecolor numbers from the current palette. Different types are valid fordifferent parameters, this is discussed in detail in the next section. It ishowever always true that the parameter can always be a function object inwhich it will be called with the graph as its single argument to get the“proper” value of the parameter. (If the function returns anotherfunction object that willnot be called again...)
The list of parameters
Vertex parameters first, note that the‘vertex.’ prefix needs to be added if they are used as anargument or when setting viaigraph_options(). The value of theparameter may be scalar valid for every vertex or a vector with a separatevalue for each vertex. (Shorter vectors are recycled.)
- size
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 verticesfor 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.If
size.scalingisTRUE,relative.sizeis used to scale the size appropriately.- size2
The “other” size of the vertex, for some vertex shapes.For the various rectangle shapes this gives the height of the vertices,whereas
sizegives the width.It is ignored by shapes for which the size can be specified with a single number.The default is 15.
- color
The fill color of the vertex. If it isnumeric then the current palette is used, see
grDevices::palette(). If it is a character vector then it mayeither contain integer values, named colors or RGB specified colors withthree or four bytes. All strings starting with ‘#’ are assumedto be RGB color specifications. It is possible to mix named color and RGBcolors. Note thattkplot()ignores the fourth byte (alphachannel) in the RGB color specification.For
plot.igraphand integer values, the default igraph palette isused (see the ‘palette’ parameter below. Note that this is differentfrom the R palette.If you don't want (some) vertices to have any color, supply
NAas thecolor name.The default value is “
SkyBlue2”.- frame.color
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
NAas the color name.By default it is “black”.
- frame.width
The width of the frame of the vertices. The default value is 1.
- shape
The shape of the vertex, currently “
circle”,“square”, “csquare”, “rectangle”,“crectangle”, “vrectangle”, “pie”(seevertex.shape.pie()), ‘sphere’, and“none” are supported, and only by theplot.igraph()command. “none” does not draw thevertices at all, although vertex label are plotted (if given). Seeshapes()for details about vertex shapes andvertex.shape.pie()for using pie charts as vertices.The “
sphere” vertex shape plots vertices as 3D ray-tracedspheres, in the given color and size. This produces a raster image and it isonly supported with some graphics devices. On some devices rastertransparency is not supported and the spheres do not have a transparentbackground. Seedev.capabilities and the‘rasterImage’ capability to check that your device issupported.By default vertices are drawn as circles.
- label
The vertex labels. They will be converted to character.Specify
NAto omit vertex labels. The default vertex labels are the vertex ids.- label.family
Thefont family to be used for vertex labels. As different plotting commandscan used different fonts, they interpret this parameter different ways. Thebasic notation is, however, understood by both
plot.igraph()andtkplot().rglplot()does not support fonts at allright now, it ignores this parameter completely.For
plot.igraph()this parameter is simply passed tographics::text()as argumentfamily.For
tkplot()some conversion is performed. If this parameter isthe name of an existing Tk font, then that font is used and thelabel.fontandlabel.cexparameters are ignored completely. Ifit is one of the base families (serif, sans, mono) then Times, Helvetica orCourier fonts are used, there are guaranteed to exist on all systems. Forthe ‘symbol’ base family we used the symbol font is available,otherwise the first font which has ‘symbol’ in its name. If theparameter is not a name of the base families and it is also not a named Tkfont then we pass it totcltk::tkfont.create()and hope the userknows what she is doing. Thelabel.fontandlabel.cexparameters are also passed totcltk::tkfont.create()in thiscase.The default value is ‘serif’.
- label.font
The font within the font family to use for the vertex labels.It is interpreted the same way as the the
fontgraphical 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 tographics::text().For
tkplot(), if thelabel.familyparameter is not the name of a Tk fontthen 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.
- label.cex
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 tographics::text()as argumentcex.For
tkplot()it is multiplied by 12 and then used as thesizeargument fortcltk::tkfont.create().The base font is thus 12 for tkplot.For
rglplot()it is ignored.The default value is 1.
- label.dist
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.
- label.degree
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/2and down ispi/2.The default value is
-pi/4.- label.color
The color of the labels, see the
colorvertex parameterdiscussed earlier for the possible values.The default value is
black.- label.angle
The rotation of the vertex labels, in degrees. Corresponds to the
srtparameter ofgraphics::text().- label.adj
one or two numeric values, giving the horizontal and vertical adjustment of the vertex labels. See also
adjingraphics::text().- size.scaling
Switches between absolute vertex sizing (FALSE,default) and relative (TRUE).If FALSE,
vertex.sizeandvertex.size2are used as is.If TRUE,relative.sizeis used to scale both appropriately withrelative.size.- relative.size
The relative size of the smallest and largest vertices as percentage ofthe plotting region. When all vertices have the same size, then by defaultthe relative size observed in the plot will be equal to
relative.size[2].The default value isc(.01,.025)(1\Only used if
size.scalingis TRUE'.
Edge parameters require to add the ‘edge.’ prefix when used asarguments or set byigraph_options(). The edge parameters:
- color
The color of the edges, see the
colorvertex parameter for the possible values.By default this parameter isdarkgrey.- width
The width of the edges. The default value is 1.
- arrow.size
The size of the arrows. The default value is 1.
- arrow.width
The width of the arrows. The default value is 1.
- lty
The line type for the edges. Almost thesame format is accepted as for the standard graphics
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 nothowever 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.
- label
The edge labels.They will be converted to character. Specify
NAto omit edge labels.Edge labels are omitted by default.
- label.family
Font family of the edge labels. See the vertex parameter with the same name for the details.
- label.font
The font for the edge labels. See the corresponding vertex parameter discussed earlier for details.
- label.cex
The font size for the edge labels, see the corresponding vertex parameter for details.
- label.color
The color of the edge labels, see the
colorvertex parameters on how to specify colors.- label.x
The horizontal
NAelements will be replaced by automatically calculated coordinates.IfNULL, then all edge horizontal coordinates are calculated automatically.This parameter is only supported byplot.igraph.- label.y
The same as
label.x, but for vertical coordinates.- curved
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.
TRUEmeans curvature 0.5,FALSEmeans curvature zero.By default the vector specifying the curvatureis 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().- arrow.mode
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 adirected 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.
- loop.angle
Gives the angle in radians for plotting loop edges.See the
label.distvertex parameter to see how this is interpreted.The default value is NULL. This means that the loop edges will be drawn automatically in the largest gap possible.
- loop.angle2
Gives the second angle in radians for plotting loop edges.This is only used in 3D,
loop.angleis enough in 2D.The default value is 0.
Other parameters:
- layout
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
xandycoordinates,and it can also have third column,this will be thezcoordinate 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
layoutis a function, this function will be called with thegraphas 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 islayout_nicely, a smart function that chooses a layout based on the graph.- margin
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.- palette
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 byplot, and not bytkplotandrglplot.- rescale
Logical constant, whether to rescale the coordinates to the
[-1,1]x[-1,1](x[-1,1])interval.This parameter is not implemented fortkplot.Defaults toTRUE, the layout will be rescaled.- asp
A numeric constant, it gives the
aspparameter forplot(), the aspect ratio.Supply 0 here if you don't want to give an aspect ratio.It is ignored bytkplotandrglplot.Defaults to 1.- frame
Boolean, whether to plot a frame around the graph.It is ignored by
tkplotandrglplot.Defaults toFALSE.- main
Overall title for the main plot.The default is empty if the
annotate.plotigraph option isFALSE,and the graph'snameattribute otherwise.See the same argument of the baseplotfunction.Only supported byplot.- sub
Subtitle of the main plot, the default is empty.Only supported by
plot.- xlab
Title for the x axis, the default is empty if the
annotate.plotigraph option isFALSE,and the number of vertices and edges, if it isTRUE.Only supported byplot.- ylab
Title for the y axis, the default is empty.Only supported by
plot.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
plot.igraph(),tkplot(),rglplot(),igraph_options()
Examples
## Not run: # plotting a simple ring graph, all default parameters, except the layoutg <- make_ring(10)g$layout <- layout_in_circleplot(g)tkplot(g)rglplot(g)# plotting a random graph, set the parameters in the command argumentsg <- 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 componentg <- sample_gnp(100, 1 / 100)comps <- components(g)$membershipcolbar <- 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 graphg <- 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 + 1g <- set_graph_attr(g, "layout", layout_with_kk(g))plot(g, vertex.label.dist = 1.5)# draw a bunch of trees, fix layoutigraph_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")# use relative scaling instead of absoluteg <- make_famous_graph("Zachary")igraph_options(plot.layout = layout_nicely)plot(g, vertex.size = degree(g))plot(g, vertex.size = degree(g), size.scaling = TRUE)plot(g, vertex.size = degree(g), size.scaling = TRUE, relative.size = c(0.05, 0.1))## End(Not run)Plotting of graphs
Description
plot.igraph() is able to plot graphs to any R device. It is thenon-interactive companion of thetkplot() function.
Usage
## S3 method for class 'igraph'plot( x, axes = FALSE, add = FALSE, xlim = NULL, ylim = NULL, 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, mark.lwd = 1, loop.size = 1, ...)Arguments
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, ordelete the device's current contents first. |
xlim | The limits for the horizontal axis, it is unlikely that you wantto modify this. |
ylim | The limits for the vertical axis, it is unlikely that you wantto modify this. |
mark.groups | A list of vertex id vectors. It is interpreted as a setof vertex groups. Each vertex group is highlighted, by plotting a coloredsmoothed polygon around and “under” it. See the arguments below tocontrol the look of the polygons. |
mark.shape | A numeric scalar or vector. Controls the smoothness of thevertex group marking polygons. This is basically the ‘shape’parameter of the |
mark.col | A scalar or vector giving the colors of marking thepolygons, in any format accepted by |
mark.border | A scalar or vector giving the colors of the borders ofthe vertex group marking polygons. If it is |
mark.expand | A numeric scalar or vector, the size of the border aroundthe marked vertex groups. It is in the same units as the vertex sizes. If avector is given, then different values are used for the different vertexgroups. |
mark.lwd | A numeric scalar or vector, the linewidth of the border aroundthe marked vertex groups. If avector is given, then different values are used for the different vertexgroups. |
loop.size | A numeric scalar that allows the user to scale the loop edgesof the network. The default loop size is 1. Larger values will produce largerloops. |
... | Additional plotting parameters. Seeigraph.plotting forthe complete list. |
Details
One convenient way to plot graphs is to plot withtkplot()first, handtune the placement of the vertices, query the coordinates by thetk_coords() function and use them withplot() toplot the graph to any R device.
Value
ReturnsNULL, invisibly.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
layout() for different layouts,igraph.plotting for the detailed description of the plottingparameters andtkplot() andrglplot() for othergraph plotting functions.
Other plot:rglplot()
Examples
g <- make_ring(10)plot(g, layout = layout_with_kk, vertex.color = "green")Plotting the results on multiple SIR model runs
Description
This function can conveniently plot the results of multiple SIR modelsimulations.
Usage
## 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, ...)Arguments
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 ifneeded 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 |
Details
The number of susceptible/infected/recovered individuals is plotted overtime, for multiple simulations.
Value
Nothing.
Author(s)
Eric Kolaczyk (https://kolaczyk.github.io/) and GaborCsardicsardi.gabor@gmail.com.
References
Bailey, Norman T. J. (1975). The mathematical theory ofinfectious diseases and its applications (2nd ed.). London: Griffin.
See Also
sir() for running the actual simulation.
Processes on graphstime_bins()
Examples
g <- sample_gnm(100, 100)sm <- sir(g, beta = 5, gamma = 1)plot(sm)Calculate Cohesive Blocks
Description
plotHierarchy() was renamed toplot_hierarchy() to create a moreconsistent API.
Usage
plotHierarchy( blocks, layout = layout_as_tree(hierarchy(blocks), root = 1), ...)Arguments
layout | The layout of a plot, it is simply passed on to |
... | Additional arguments. |
Community structure dendrogram plots
Description
Plot a hierarchical community structure as a dendrogram.
Usage
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))Arguments
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 plottingfunction. |
use.modularity | Logical scalar, whether to use the modularity valuesto define the height of the branches. |
palette | The color palette to use for colored plots. |
Details
plot_dendrogram() supports three different plotting functions, selected viathemode argument. By default the plotting function is taken from thedend.plot.type igraph option, and it has for possible values:
autoChoose automatically between the plottingfunctions. Asplot.phylois the most sophisticated, that is choosen,whenever theapepackage is available. Otherwiseplot.hclustis used.phyloUseplot.phylofrom theapepackage.hclustUseplot.hclustfrom thestatspackage.dendrogramUseplot.dendrogramfrom thestatspackage.
The different plotting functions take different sets of arguments. Whenusingplot.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:
colbarColor bar for the edges.edge.colorEdge colors. IfNULL, then thecolbarargument is used.use.edge.lengthPassed toplot.phylo.dotsAttitional arguments to pass toplot.phylo.
The syntax forplot.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:
rectA numeric scalar, the number of groups to mark onthe dendrogram. The dendrogram is cut into exactlyrectgroups and they are marked via therect.hclustcommand. Setthis to zero if you don't want to mark any groups.colbarThe colors of the rectangles that mark thevertex groups via therectargument.hangWhere to put the leaf nodes, this corresponds to thehangargument ofplot.hclust.annWhether to annotate the plot, theannargument ofplot.hclust.mainThe main title of the plot, themainargumentofplot.hclust.subThe sub-title of the plot, thesubargument ofplot.hclust.xlabThe label on the horizontal axis, passed toplot.hclust.ylabThe label on the vertical axis, passed toplot.hclust.dotsAttitional arguments to pass toplot.hclust.
The syntax forplot.dendrogram (mode="dendrogram"):
plot_dendrogram(x, \dots)
The extra arguments are simply passed toas.dendrogram().
Value
Returns whatever the return value was from the plotting function,plot.phylo,plot.dendrogram orplot.hclust.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
Community detectionas_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()
Examples
karate <- make_graph("Zachary")fc <- cluster_fast_greedy(karate)plot_dendrogram(fc)HRG dendrogram plot
Description
Plot a hierarchical random graph as a dendrogram.
Usage
## S3 method for class 'igraphHRG'plot_dendrogram(x, mode = igraph_opt("dend.plot.type"), ...)Arguments
x | An |
mode | Which dendrogram plotting function to use. See details below. |
... | Additional arguments to supply to the dendrogram plottingfunction. |
Details
plot_dendrogram() supports three different plotting functions, selected viathemode argument. By default the plotting function is taken from thedend.plot.type igraph option, and it has for possible values:
autoChoose automatically between the plottingfunctions. Asplot.phylois the most sophisticated, that is choosen,whenever theapepackage is available. Otherwiseplot.hclustis used.phyloUseplot.phylofrom theapepackage.hclustUseplot.hclustfrom thestatspackage.dendrogramUseplot.dendrogramfrom thestatspackage.
The different plotting functions take different sets of arguments. Whenusingplot.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:
colbarColor bar for the edges.edge.colorEdge colors. IfNULL, then thecolbarargument is used.use.edge.lengthPassed toplot.phylo.dotsAttitional arguments to pass toplot.phylo.
The syntax forplot.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:
rectA numeric scalar, the number of groups to mark onthe dendrogram. The dendrogram is cut into exactlyrectgroups and they are marked via therect.hclustcommand. Setthis to zero if you don't want to mark any groups.colbarThe colors of the rectangles that mark thevertex groups via therectargument.hangWhere to put the leaf nodes, this corresponds to thehangargument ofplot.hclust.annWhether to annotate the plot, theannargumentofplot.hclust.mainThe main title of the plot, themainargumentofplot.hclust.subThe sub-title of the plot, thesubargument ofplot.hclust.xlabThe label on the horizontal axis, passed toplot.hclust.ylabThe label on the vertical axis, passed toplot.hclust.dotsAttitional arguments to pass toplot.hclust.
The syntax forplot.dendrogram (mode="dendrogram"):
plot_dendrogram(x, \dots)
The extra arguments are simply passed toas.dendrogram().
Value
Returns whatever the return value was from the plotting function,plot.phylo,plot.dendrogram orplot.hclust.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
Examples
g <- make_full_graph(5) + make_full_graph(5)hrg <- fit_hrg(g)plot_dendrogram(hrg)Fitting a power-law distribution function to discrete data
Description
power.law.fit() was renamed tofit_power_law() to create a moreconsistent API.
Usage
power.law.fit( x, xmin = NULL, start = 2, force.continuous = FALSE, implementation = c("plfit", "R.mle"), ...)Arguments
x | The data to fit, a numeric vector. For implementation‘ |
xmin | Numeric scalar, or |
start | Numeric scalar. The initial value of the exponent for theminimizing function, for the ‘ |
force.continuous | Logical scalar. Whether to force a continuousdistribution for the ‘ |
implementation | Character scalar. Which implementation to use. Seedetails below. |
... | Additional arguments, passed to the maximum likelihoodoptimizing function, |
Find Bonacich Power Centrality Scores of Network Positions
Description
power_centrality() takes a graph (dat) and returns the Boncich powercentralities of positions (selected bynodes). The decay rate forpower contributions is specified byexponent (1 by default).
Usage
power_centrality( graph, nodes = V(graph), loops = FALSE, exponent = 1, rescale = FALSE, tol = 1e-07, sparse = TRUE)Arguments
graph | the input graph. |
nodes | vertex sequence indicating which vertices are to be included inthe calculation. By default, all vertices are included. |
loops | boolean indicating whether or not the diagonal should betreated as valid data. Set this true if and only if the data can containloops. |
exponent | exponent (decay rate) for the Bonacich power centralityscore; can be negative |
rescale | if true, centrality scores are rescaled such that they sum to1. |
tol | tolerance for near-singularities during matrix inversion (see |
sparse | Logical scalar, whether to use sparse matrices for thecalculation. The ‘Matrix’ package is required for sparse matrixsupport |
Details
Bonacich's power centrality measure is defined byC_{BP}\left(\alpha,\beta\right)=\alpha\left(\mathbf{I}-\beta\mathbf{A}\right)^{-1}\mathbf{A}\mathbf{1}, where\beta is an attenuation parameter (sethere byexponent) and\mathbf{A} is the graph adjacencymatrix. (The coefficient\alpha acts as a scaling parameter,and is set here (following Bonacich (1987)) such that the sum of squaredscores is equal to the number of vertices. This allows 1 to be used as areference value for the “middle” of the centrality range.) When\beta \rightarrow1/\lambda_{\mathbf{A}1} (the reciprocal of the largesteigenvalue of\mathbf{A}), this is to within a constant multiple ofthe familiar eigenvector centrality score; for other values of\beta,the behavior of the measure is quite different. In particular,\betagives positive and negative weight to even and odd walks, respectively, ascan be seen from the series expansionC_{BP}\left(\alpha,\beta\right)=\alpha \sum_{k=0}^\infty \beta^k\mathbf{A}^{k+1} \mathbf{1} which converges so long as|\beta| < 1/\lambda_{\mathbf{A}1}.The magnitude of\beta controls the influence of distant actorson ego's centrality score, with larger magnitudes indicating slower rates ofdecay. (High rates, hence, imply a greater sensitivity to edge effects.)
Interpretively, the Bonacich power measure corresponds to the notion thatthe power of a vertex is recursively defined by the sum of the power of itsalters. The nature of the recursion involved is then controlled by thepower exponent: positive values imply that vertices become more powerful astheir alters become more powerful (as occurs in cooperative relations),while negative values imply that vertices become more powerful only as theiralters becomeweaker (as occurs in competitive or antagonisticrelations). The magnitude of the exponent indicates the tendency of theeffect to decay across long walks; higher magnitudes imply slower decay.One interesting feature of this measure is its relative instability tochanges in exponent magnitude (particularly in the negative case). If yourtheory motivates use of this measure, you should be very careful to choose adecay parameter on a non-ad hoc basis.
For directed networks, the Bonacich power measure can be understood assimilar to status in the network where higher status nodes have more edgesthat point from them to others with status. Node A's centrality dependson the centrality of all the nodes that A points toward, and their centralitydepends on the nodes they point toward, etc. Note, this means that a nodewith an out-degree of 0 will have a Bonacich power centrality of 0 as theydo not point towards anyone. When using this with directed network itis important to think about the edge direction and what it represents.
Value
A vector, containing the centrality scores.
Warning
Singular adjacency matrices cause no end of headaches forthis algorithm; thus, the routine may fail in certain cases. This will befixed when we get a better algorithm.
Note
This function was ported (i.e. copied) from the SNA package.
Author(s)
Carter T. Butts(https://www.faculty.uci.edu/profile.cfm?faculty_id=5057), ported toigraph by Gabor Csardicsardi.gabor@gmail.com
References
Bonacich, P. (1972). “Factoring and Weighting Approaches toStatus Scores and Clique Identification.”Journal of MathematicalSociology, 2, 113-120.
Bonacich, P. (1987). “Power and Centrality: A Family of Measures.”American Journal of Sociology, 92, 1170-1182.
See Also
eigen_centrality() andalpha_centrality()
Centrality measuresalpha_centrality(),authority_score(),betweenness(),closeness(),diversity(),eigen_centrality(),harmonic_centrality(),hits_scores(),page_rank(),spectrum(),strength(),subgraph_centrality()
Examples
# 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 scoresfor (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 based on a hierarchical random graph model
Description
predict_edges() uses a hierarchical random graph model to predictmissing edges from a network. This is done by sampling hierarchical modelsaround the optimum model, proportionally to their likelihood. The MCMCsampling is stated fromhrg(), if it is given and thestartargument is set toTRUE. Otherwise a HRG is fitted to the graphfirst.
Usage
predict_edges( graph, hrg = NULL, start = FALSE, num.samples = 10000, num.bins = 25)Arguments
graph | The graph to fit the model to. Edge directions are ignored indirected graphs. |
hrg | A hierarchical random graph model, in the form of an |
start | Logical, whether to start the fitting/sampling from thesupplied |
num.samples | Number of samples to use for consensus generation ormissing edge prediction. |
num.bins | Number of bins for the edge probabilities. Give a highernumber for a more accurate prediction. |
Value
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.
References
A. Clauset, C. Moore, and M.E.J. Newman. Hierarchical structureand the prediction of missing links in networks.Nature 453, 98–101(2008);
A. Clauset, C. Moore, and M.E.J. Newman. Structural Inference of Hierarchiesin Networks. In E. M. Airoldi et al. (Eds.): ICML 2006 Ws,LectureNotes in Computer Science 4503, 1–13. Springer-Verlag, Berlin Heidelberg(2007).
See Also
Other hierarchical random graph functions:consensus_tree(),fit_hrg(),hrg(),hrg-methods,hrg_tree(),print.igraphHRG(),print.igraphHRGConsensus(),sample_hrg()
Examples
## A graph with two dense groupsg <- sample_gnp(10, p = 1 / 2) + sample_gnp(10, p = 1 / 2)hrg <- fit_hrg(g)hrg## The consensus tree for itconsensus_tree(g, hrg = hrg, start = TRUE)## Prediction of missing edgesg2 <- make_full_graph(4) + (make_full_graph(4) - path(1, 2))predict_edges(g2)Trait-based random generation
Description
preference.game() was renamed tosample_pref() to create a moreconsistent API.
Usage
preference.game( nodes, types, type.dist = rep(1, types), fixed.sizes = FALSE, pref.matrix = matrix(1, types, types), directed = FALSE, loops = FALSE)Arguments
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 oflength ‘types’ containing non-negative numbers. The vector will benormed to obtain probabilities. |
fixed.sizes | Fix the number of vertices with a given vertex typelabel. The |
pref.matrix | A square matrix giving the preferences of the vertextypes. The matrix has ‘types’ rows and columns. When generatingan 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. |
Print graphs to the terminal
Description
These functions attempt to print a graph to the terminal in a human readableform.
Usage
## 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, ...)Arguments
x | The graph to print. |
full | Logical scalar, whether to print the graph structure itself aswell. |
graph.attributes | Logical constant, whether to print graph attributes. |
vertex.attributes | Logical constant, whether to print vertexattributes. |
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 theoutput will be truncated. |
id | Whether to print the graph ID. |
... | Additional agruments. |
object | The graph of which the summary will be printed. |
Details
summary.igraph prints the number of vertices, edges and whether thegraph is directed.
print_all() prints the same information, and also lists the edges, andoptionally graph, vertex and/or edge attributes.
print.igraph() behaves either assummary.igraph orprint_all() depending on thefull argument. See also the‘print.full’ igraph option andigraph_opt().
The graph summary printed bysummary.igraph (andprint.igraph()andprint_all()) consists of one or more lines. The first line containsthe basic properties of the graph, and the rest contains its attributes.Here is an example, a small star graph with weighted directed edges and namedvertices:
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 alwaysstarts withIGRAPH, showing you that the object is an igraph graph.Then a seven character code is printed, this the first seven charactersof the unique id of the graph. Seegraph_id() for more.Then a four letter long code string is printed. The first letterdistinguishes between directed (‘D’) and undirected(‘U’) graphs. The second letter is ‘N’ for namedgraphs, i.e. graphs with thename vertex attribute set. The thirdletter is ‘W’ for weighted graphs, i.e. graphs with theweight edge attribute set. The fourth letter is ‘B’ forbipartite graphs, i.e. for graphs with thetype 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 thename graph attribute is set.
From the second line, the attributes of the graph are listed, separated by acomma. 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.4print_all() andprint.igraph() use themax.print option, seebase::options() for details.
As of igraph 1.1.1, thestr.igraph function is defunct, useprint_all().
Value
All these functions return the graph invisibly.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
Examples
g <- make_ring(10)gsummary(g)Print an edge sequence to the screen
Description
For long edge sequences, the printing is truncated to fit to thescreen. Useprint() explicitly and thefull argument tosee the full sequence.
Usage
## S3 method for class 'igraph.es'print(x, full = igraph_opt("print.full"), id = igraph_opt("print.id"), ...)Arguments
x | An edge sequence. |
full | Whether to show the full sequence, or truncate the outputto the screen size. |
id | Whether to print the graph ID. |
... | Currently ignored. |
Details
Edge sequences created with the double bracket operator are printeddifferently, together with all attributes of the edges in the sequence,as a table.
Value
The edge sequence, invisibly.
See Also
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()
Examples
# Unnamed graphsg <- make_ring(10)E(g)# Named graphsg2 <- make_ring(10) %>% set_vertex_attr("name", value = LETTERS[1:10])E(g2)# All edges in a long sequenceg3 <- make_ring(200)E(g3)E(g3) %>% print(full = TRUE)# Metadatag4 <- 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]]Show a vertex sequence on the screen
Description
For long vertex sequences, the printing is truncated to fit to thescreen. Useprint() explicitly and thefull argument tosee the full sequence.
Usage
## S3 method for class 'igraph.vs'print(x, full = igraph_opt("print.full"), id = igraph_opt("print.id"), ...)Arguments
x | A vertex sequence. |
full | Whether to show the full sequence, or truncate the outputto the screen size. |
id | Whether to print the graph ID. |
... | These arguments are currently ignored. |
Details
Vertex sequence created with the double bracket operator areprinted differently, together with all attributes of the verticesin the sequence, as a table.
Value
The vertex sequence, invisibly.
See Also
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()
Examples
# Unnamed graphsg <- make_ring(10)V(g)# Named graphsg2 <- make_ring(10) %>% set_vertex_attr("name", value = LETTERS[1:10])V(g2)# All vertices in the sequenceg3 <- make_ring(1000)V(g3)print(V(g3), full = TRUE)# Metadatag4 <- 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]]Print a hierarchical random graph model to the screen
Description
igraphHRG objects can be printed to the screen in two forms: asa tree or as a list, depending on thetype argument of theprint function. By default theauto type is used, which selectstree for small graphs andsimple (=list) for biggerones. Thetree format looks likethis:
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 thetop three levels of the fitted hierarchical random graph areprinted. The root node of the HRG is always vertex group #1(‘g1’ in the the printout). Vertex pairs in the leftsubtree ofg1 connect to vertices in the right subtree withprobability zero, according to the fitted model.g1 has twosubgroups,g15 andg8.g15 has a subgroup of asingle vertex (vertex 1), and another larger subgroup that containsvertices 6, 3, etc. on lower levels, etc.Theplain printing is simpler and faster to produce, but lessvisual:
Hierarchical random graph:g1 p=0.0 -> g12 g10 g2 p=1.0 -> 7 10 g3 p=1.0 -> g18 14g4 p=1.0 -> g17 15 g5 p=0.4 -> g15 17 g6 p=0.0 -> 1 4g7 p=1.0 -> 11 16 g8 p=0.1 -> g9 3 g9 p=0.3 -> g11 g16g10 p=0.2 -> g4 g5 g11 p=1.0 -> g6 5 g12 p=0.8 -> g8 8g13 p=0.0 -> g14 9 g14 p=1.0 -> 2 6 g15 p=0.2 -> g19 18g16 p=1.0 -> g13 g2 g17 p=0.5 -> g7 13 g18 p=1.0 -> 12 19g19 p=0.7 -> g3 20
It lists the two subgroups of each internal node, inas many columns as the screen width allows.
Usage
## S3 method for class 'igraphHRG'print(x, type = c("auto", "tree", "plain"), level = 3, ...)Arguments
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. |
Value
The hierarchical random graph model itself, invisibly.
See Also
Other hierarchical random graph functions:consensus_tree(),fit_hrg(),hrg(),hrg-methods,hrg_tree(),predict_edges(),print.igraphHRGConsensus(),sample_hrg()
Print a hierarchical random graph consensus tree to the screen
Description
Consensus dendrograms (igraphHRGConsensus objects) are printedsimply by listing the children of each internal node of thedendrogram:
HRG consensus tree:g1 -> 11 12 13 14 15 16 17 18 19 20g2 -> 1 2 3 4 5 6 7 8 9 10g3 -> g1 g2
The root of the dendrogram isg3 (because it has no incomingedges), and it has two subgroups,g1 andg2.
Usage
## S3 method for class 'igraphHRGConsensus'print(x, ...)Arguments
x |
|
... | Ignored. |
Value
The input object, invisibly, to allow method chaining.
See Also
Other hierarchical random graph functions:consensus_tree(),fit_hrg(),hrg(),hrg-methods,hrg_tree(),predict_edges(),print.igraphHRG(),sample_hrg()
Create a printer callback function
Description
A printer callback function is a function can performs the actualprinting. It has a number of subcommands, that are called bytheprinter package, in a form
printer_callback("subcommand", argument1, argument2, ...)See the examples below.
Usage
printer_callback(fun)Arguments
fun | The function to use as a printer callback function. |
Details
The subcommands:
lengthThe 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_widthTODO
widthWidth of one item, if
noitems will be printed. TODOprintArgument:
no. Do the actual printing, printnoitems.doneTODO
See Also
Other printer callbacks:is_printer_callback()
The default R palette
Description
This is the default R palette, to be able to reproduce thecolors of older igraph versions. Its colors are appropriatefor categories, but they are not very attractive.
Usage
r_pal(n)Arguments
n | The number of colors to use, the maximum is eight. |
Value
A character vector of color names.
See Also
Other palettes:categorical_pal(),diverging_pal(),sequential_pal()
Radius of a graph
Description
The eccentricity of a vertex is its distance from the farthest other nodein the graph. The smallest eccentricity in a graph is called its radius.
Usage
radius(graph, ..., weights = NULL, mode = c("all", "out", "in", "total"))Arguments
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 fromthe given vertices should be calculated for directed graphs. If |
Details
The eccentricity of a vertex is calculated by measuring the shortestdistance from (or to) the vertex, to (or from) all vertices in thegraph, and taking the maximum.
This implementation ignores vertex pairs that are in differentcomponents. Isolated vertices have eccentricity zero.
Value
A numeric scalar, the radius of the graph.
Related documentation in the C library
References
Harary, F. Graph Theory. Reading, MA: Addison-Wesley, p. 35,1994.
See Also
eccentricity() for the underlyingcalculations,distances for general shortest pathcalculations.
Other paths:all_simple_paths(),diameter(),distance_table(),eccentricity(),graph_center()
Examples
g <- make_star(10, mode = "undirected")eccentricity(g)radius(g)Random walk on a graph
Description
random_walk() performs a random walk on the graph and returns thevertices that the random walk passed through.random_edge_walk()is the same but returns the edges that that random walk passed through.
Usage
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"))Arguments
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 theprobability that an edge is selected by the random walker. In otherwords, 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. |
Details
Do a random walk. From the given start vertex, take the given number ofsteps, choosing an edge from the actual vertex uniformly randomly. Edgedirections are observed in directed graphs (see themode argumentas well). Multiple and loop edges are also observed.
For igraph < 1.6.0,random_walk() counted steps differently,and returned a sequence of lengthsteps instead ofsteps + 1.This has changed to improve consistency with the underlying C library.
Value
Forrandom_walk(), a vertex sequence of lengthsteps + 1containing the vertices along the walk, starting withstart.Forrandom_edge_walk(), an edge sequence of lengthsteps containingthe edges along the walk.
Related documentation in the C library
Examples
## Stationary distribution of a Markov chaing <- make_ring(10, directed = TRUE) %u% make_star(11, center = 11) + edge(11, 1)ec <- eigen_centrality(g, directed = TRUE)$vectorpg <- page_rank(g, damping = 0.999)$vectorw <- random_walk(g, start = 1, steps = 10000)## These are similar, but not exactly the samecor(table(w), ec)## But these are (almost) the samecor(table(w), pg)Reading foreign file formats
Description
read.graph() was renamed toread_graph() to create a moreconsistent API.
Usage
read.graph( file, format = c("edgelist", "pajek", "ncol", "lgl", "graphml", "dimacs", "graphdb", "gml", "dl"), ...)Arguments
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. |
Reading foreign file formats
Description
Theread_graph() function is able to read graphs in variousrepresentations from a file, or from a http connection. Various formatsare supported.
Usage
read_graph( file, format = c("edgelist", "pajek", "ncol", "lgl", "graphml", "dimacs", "graphdb", "gml", "dl"), ...)Arguments
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. |
Details
Theread_graph() function may have additional arguments depending onthe file format (theformat argument). See the details separately foreach file format, below.
Value
A graph object.
Edge list format
This format is a simple text file with numericvertex IDs defining the edges. There is no need to have newline charactersbetween the edges, a simple space will also do. Vertex IDs contained inthe file are assumed to start at zero.
Additional arguments:
- n
The number of vertices in thegraph. 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).
- directed
Logical scalar, whether to create a directed graph. Thedefault value is
TRUE.
Pajek format
Currently igraph only supports Pajek networkfiles, with a.net extension, but not Pajek project files witha.paj extension. Only network data is supported; permutations,hierarchies, clusters and vectors are not.
NCOL format
Additional arguments:
- predef
Names of the vertices in the file.If
character(0)(the default) is given herethen vertex IDs will be assigned to vertex names in the order oftheir appearance in the .ncol file.If it is notcharacter(0)and some unknown vertex names are foundin the .ncol file then new vertex ids will be assigned to them.- names
Logical value, if
TRUE(the default)the symbolic names of the vertices will be added to the graphas a vertex attribute called “name”.- weights
Whether to add the weights of the edges to the graphas an edge attribute called “weight”.
"yes"adds the weights (even if they are not present in the file,in this case they are assumed to be zero)."no"does not add any edge attribute."auto"(the default) adds the attribute if and onlyif there is at least one explicit edge weight in the input file.- directed
Whether to create a directed graph (default:
FALSE).As this format was originally used only for undirected graphsthere is no information in the file about the directedness of the graph.
GraphML format
GraphML is an XML-based file format for representing various types of graphs.Currently only the most basic import functionality is implemented in igraph:it can read GraphML files without nested graphs and hyperedges.
- index
Integer, specifies which graph to read from a GraphML filecontaining multiple graphs. Defaults to 0 for the first graph.
LGL format
The .lgl format is used by the Large Graph Layout visualization software (https://lgl.sourceforge.net), it can describe undirected optionally weighted graphs
- names
Logical, whether to add vertex names as a vertex attributecalled "name". Default is TRUE.
- weights
Whether to add the weights of the edges to the graphas an edge attribute called “weight”.
"yes"adds the weights (even if they are not present in the file,in this case they are assumed to be zero)."no"does not add any edge attribute."auto"(the default) adds the attribute if and onlyif there is at least one explicit edge weight in the input file.- directed
Logical, whether to create a directed graph. Default is FALSE.
DIMACS format
This is a line-oriented text file (ASCII) format.The first character of each line defines the type of the line.If the first character is c the line is a comment line and it is ignored.There is one problem line (p in the file),it must appear before any node and arc descriptor lines.The problem line has three fields separated by spaces: the problem type (max or edge),the number of vertices, and number of edges in the graph. In MAX problems,exactly two node identification lines are expected (n), one for the source, and one for the target vertex.These have two fields: the ID of the vertex and the type of the vertex, either s ( = source) or t ( = target).Arc lines start with a and have three fields: the source vertex, the target vertex and the edge capacity.In EDGE problems, there may be a node line (n) for each node. It specifies the node index and aninteger node label. Nodes for which no explicit label was specified will use their index as label.In EDGE problems, each edge is specified as an edge line (e).
- directed
Logical, whether to create a directed graph. Default is TRUE.
DL format
This is a simple textual file format used by UCINET.Seehttp://www.analytictech.com/networks/dataentry.htm for examples.All the forms described here are supported by igraph.Vertex names and edge weights are also supported and they are added as attributes.(If an attribute handler is attached.)Note the specification does not mention whether the format is case sensitive or not.For igraph DL files are case sensitive, i.e. Larry and larry are not the same.
- directed
Logical, whether to create a directed graph. Default is TRUE.
GML format
GML is a quite general textual format. For the specifics of the implementation, see the linked documentation of the cClibrary.
GraphDB format
This is a binary format, used in the ARG Graph Database for isomorphism testing. For more information, seehttps://mivia.unisa.it/datasets/graph-database/arg-database/
- directed
Logical, whether to create a directed graph. Default is TRUE.
Related documentation in the C library
read_graph_dimacs_flow(),read_graph_dl(),read_graph_edgelist(),read_graph_gml(),read_graph_graphdb(),read_graph_graphml(),read_graph_lgl(),read_graph_ncol(),read_graph_pajek().
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
Foreign format readersgraph_from_graphdb(),write_graph()
Creating a bipartite graph from two degree sequences, deterministically
Description
Constructs a bipartite graph from the degree sequences of its partitions,if one exists. This function uses a Havel-Hakimi style constructionalgorithm.
Usage
realize_bipartite_degseq( degrees1, degrees2, ..., allowed.edge.types = c("simple", "multiple"), method = c("smallest", "largest", "index"))Arguments
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. |
Details
The ‘method’ argument controls in which order the vertices areselected during the course of the algorithm.
The “smallest” method selects the vertex with the smallest remainingdegree, from either partition. The result is usually a graph with highnegative degree assortativity. In the undirected case, this method isguaranteed to generate a connected graph, regardless of whether multi-edgesare allowed, provided that a connected realization exists. This is thedefault method.
The “largest” method selects the vertex with the largest remainingdegree. The result is usually a graph with high positive degreeassortativity, and is often disconnected.
The “index” method selects the vertices in order of their index.
Value
The new graph object.
Related documentation in the C library
realize_bipartite_degree_sequence().
See Also
realize_degseq() to create a not necessarily bipartite graph.
Examples
g <- realize_bipartite_degseq(c(3, 3, 2, 1, 1), c(2, 2, 2, 2, 2))degree(g)Creating a graph from a given degree sequence, deterministically
Description
It is often useful to create a graph with given vertex degrees. This functioncreates such a graph in a deterministic manner.
Usage
realize_degseq( out.deg, in.deg = NULL, allowed.edge.types = c("simple", "loops", "multi", "all"), method = c("smallest", "largest", "index"))Arguments
out.deg | Numeric vector, the sequence of degrees (for undirectedgraphs) or out-degrees (for directed graphs). For undirected graphs its sumshould 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 (currentlyunimplemented). “all” allows all types of edges. The default is“simple”. |
method | Character, the method for generating the graph; see below. |
Details
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 itsstubs to other vertices. This step is repeated until all degrees have beenconnected up.
The ‘method’ argument controls in which order the vertices areselected during the course of the algorithm.
The “smallest” method selects the vertex with the smallest remainingdegree. The result is usually a graph with high negative degree assortativity.In the undirected case, this method is guaranteed to generate a connectedgraph, regardless of whether multi-edges are allowed, provided that aconnected realization exists. See Horvát and Modes (2021) for details.In the directed case it tends to generate weakly connected graphs, but thisis not guaranteed. This is the default method.
The “largest” method selects the vertex with the largest remainingdegree. 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.
Value
The new graph object.
Related documentation in the C library
References
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
See Also
sample_degseq() for a randomized variant that samplesfrom graphs with the given degree sequence.
Examples
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)Reciprocity of graphs
Description
Calculates the reciprocity of a directed graph.
Usage
reciprocity(graph, ignore.loops = TRUE, mode = c("default", "ratio"))Arguments
graph | The graph object. |
ignore.loops | Logical constant, whether to ignore loop edges. |
mode | See below. |
Details
The measure of reciprocity defines the proportion of mutual connections, ina directed graph. It is most commonly defined as the probability that theopposite counterpart of a directed edge is also included in the graph. Or inadjacency matrix notation:1 - \left(\sum_{i,j} |A_{ij} - A_{ji}|\right) / \left(2\sum_{i,j} A_{ij}\right).This measure is calculated if themode argument isdefault.
Prior to igraph version 0.6, another measure was implemented, defined as theprobability of mutual connection between a vertex pair, if we know thatthere 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 ifmode isratio.
Value
A numeric scalar between zero and one.
Related documentation in the C library
Author(s)
Tamas Nepuszntamas@gmail.com and Gabor Csardicsardi.gabor@gmail.com
See Also
Other structural.properties:bfs(),component_distribution(),connect(),constraint(),coreness(),degree(),dfs(),distance_table(),edge_density(),feedback_arc_set(),feedback_vertex_set(),girth(),is_acyclic(),is_dag(),is_matching(),k_shortest_paths(),knn(),subcomponent(),subgraph(),topo_sort(),transitivity(),unfold_tree(),which_multiple(),which_mutual()
Examples
g <- sample_gnp(20, 5 / 20, directed = TRUE)reciprocity(g)Delete an edge attribute
Description
remove.edge.attribute() was renamed todelete_edge_attr() to create a moreconsistent API.
Usage
remove.edge.attribute(graph, name)Arguments
graph | The graph |
name | The name of the edge attribute to delete. |
Delete a graph attribute
Description
remove.graph.attribute() was renamed todelete_graph_attr() to create a moreconsistent API.
Usage
remove.graph.attribute(graph, name)Arguments
graph | The graph. |
name | Name of the attribute to delete. |
Delete a vertex attribute
Description
remove.vertex.attribute() was renamed todelete_vertex_attr() to create a moreconsistent API.
Usage
remove.vertex.attribute(graph, name)Arguments
graph | The graph |
name | The name of the vertex attribute to delete. |
Replicate a graph multiple times
Description
The new graph will contain the input graph the given numberof times, as unconnected components.
Usage
## S3 method for class 'igraph'rep(x, n, mark = TRUE, ...)## S3 method for class 'igraph'x * nArguments
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. |
See Also
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()
Examples
rings <- make_ring(5) * 5Reverse the order in an edge sequence
Description
Reverse the order in an edge sequence
Usage
## S3 method for class 'igraph.es'rev(x)Arguments
x | The edge sequence to reverse. |
Value
The reversed edge sequence.
See Also
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()
Examples
g <- make_(ring(10), with_vertex_(name = LETTERS[1:10]))E(g)E(g) %>% rev()Reverse the order in a vertex sequence
Description
Reverse the order in a vertex sequence
Usage
## S3 method for class 'igraph.vs'rev(x)Arguments
x | The vertex sequence to reverse. |
Value
The reversed vertex sequence.
See Also
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()
Examples
g <- make_(ring(10), with_vertex_(name = LETTERS[1:10]))V(g) %>% rev()Reverse edges in a graph
Description
The new graph will contain the same vertices, edges and attributes asthe original graph, except that the direction of the edges selected bytheir edge IDs in theeids argument will be reversed. When reversingall edges, this operation is also known as graph transpose.
Usage
reverse_edges(graph, eids = E(graph))## S3 method for class 'igraph't(x)Arguments
graph | The input graph. |
eids | The edge IDs of the edges to reverse. |
x | The input graph. |
Value
The result graph where the direction of the edges with the givenIDs are reversed
Related documentation in the C library
See Also
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()
Examples
g <- make_graph(~ 1 -+ 2, 2 -+ 3, 3 -+ 4)reverse_edges(g, 2)Rewiring edges of a graph
Description
See the links below for the implemented rewiring methods.
Usage
rewire(graph, with)Arguments
graph | The graph to rewire |
with | A function call to one of the rewiring methods,see details below. |
Value
The rewired graph.
See Also
Other rewiring functions:each_edge(),keeping_degseq()
Examples
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)))3D plotting of graphs with OpenGL
Description
Using thergl package,rglplot() plots a graph in 3D. The plotcan be zoomed, rotated, shifted, etc. but the coordinates of the vertices isfixed.
Usage
rglplot(x, ...)Arguments
x | The graph to plot. |
... | Additional arguments, seeigraph.plotting for thedetails |
Details
Note thatrglplot() is considered to be highly experimental. It is notvery useful either. Seeigraph.plotting for the possiblearguments.
Value
NULL, invisibly.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
igraph.plotting,plot.igraph() for the 2Dversion,tkplot() for interactive graph drawing in 2D.
Other plot:plot.igraph()
Examples
g <- make_lattice(c(5, 5, 5))coords <- layout_with_fr(g, dim = 3)rglplot(g, layout = coords)Running mean of a time series
Description
running.mean() was renamed torunning_mean() to create a moreconsistent API.
Usage
running.mean(v, binwidth)Arguments
v | The numeric vector. |
binwidth | Numeric constant, the size of the bin, should be meaningful,i.e. smaller than the length of |
Running mean of a time series
Description
running_mean() calculates the running mean in a vector with the givenbin width.
Usage
running_mean(v, binwidth)Arguments
v | The numeric vector. |
binwidth | Numeric constant, the size of the bin, should be meaningful,i.e. smaller than the length of |
Details
The running mean ofv is aw vector of lengthlength(v)-binwidth+1. The first element ofw id the average ofthe firstbinwidth elements ofv, the second element ofw is the average of elements2:(binwidth+1), etc.
Value
A numeric vector of lengthlength(v)-binwidth+1
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
Other other:convex_hull(),sample_seq()
Examples
running_mean(1:100, 10)Sample from a random graph model
Description
Generic function for sampling from network models.
Usage
sample_(...)Arguments
... | Parameters, see details below. |
Details
sample_() is a generic function for creating graphs.For every graph constructor in igraph that has asample_ prefix,there is a corresponding function without the prefix: e.g.forsample_pa() there is alsopa(), etc.
The same is true for the deterministic graph samplers, i.e. for eachconstructor with amake_ prefix, there is a correspondingfunction without that prefix.
These shorter forms can be used together withsample_().The advantage of this form is that the user can specify constructormodifiers which work with all constructors. E.g. thewith_vertex_() modifier adds vertex attributesto the newly created graphs.
See the examples and the various constructor modifiers below.
See Also
Random graph models (games)bipartite_gnm(),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()
Examples
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_sbmblocky3 <- pref_matrix %>% sample_(sbm(), n = 20, block.sizes = c(10, 10))Bipartite random graphs
Description
Generate bipartite graphs using the Erdős-Rényi model.Use
sample_bipartite_gnm() andsample_bipartite_gnp() instead.
Usage
sample_bipartite( n1, n2, type = c("gnp", "gnm"), p, m, directed = FALSE, mode = c("out", "in", "all"))bipartite(..., type = NULL)Arguments
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 alsothe |
mode | Character scalar, specifies how to direct the edges in directedgraphs. If it is ‘out’, then directed edges point from bottomvertices to top vertices. If it is ‘in’, edges point from topvertices to bottom vertices. ‘out’ and ‘in’ do not generatemutual edges. If this argument is ‘all’, then each edge direction isconsidered independently and mutual edges might be generated. This argumentis ignored for undirected graphs. |
... | Passed to |
Value
A bipartite igraph graph.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
Random graph models (games)bipartite_gnm(),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()
Examples
## empty graphsample_bipartite(10, 5, p = 0)## full graphsample_bipartite(10, 5, p = 1)## random bipartite graphsample_bipartite(10, 5, p = .1)## directed bipartite graph, G(n,m)sample_bipartite(10, 5, type = "Gnm", m = 20, directed = TRUE, mode = "all")Random graph with given expected degrees
Description
The Chung-Lu model is useful for generating random graphs with fixed expecteddegrees. This function implements both the original model of Chung and Lu, aswell as some additional variants with useful properties.
Usage
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"))Arguments
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 tothe 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. Sincevertex pairs are connected independently, setting this to |
variant | The model variant to sample from, with different definitionsof the connection probability between vertices
|
Details
In the original Chung-Lu model, each pair of verticesi andj isconnected with independent probability
p_{ij} = \frac{w_i w_j}{S},
wherew_i is a weight associated with vertexi and
S = \sum_k w_k
is the sum of weights. In the directed variant, vertices have bothout-weights,w^\text{out}, and in-weights,w^\text{in}, with equal sums,
S = \sum_k w^\text{out}_k = \sum_k w^\text{in}_k.
The connection probability betweeni andj is
p_{ij} = \frac{w^\text{out}_i w^\text{in}_j.}{S}
This model is commonly used to create random graphs with a fixedexpected degree sequence. The expected degree of vertexi isapproximately equal to the weightw_i. Specifically, if the graph isdirected and self-loops are allowed, then the expected out- and in-degreesare preciselyw^\text{out} andw^\text{in}. Ifself-loops are disallowed, then the expected out- and in-degrees are\frac{w^\text{out} (S - w^\text{in})}{S}and\frac{w^\text{in} (S - w^\text{out})}{S},respectively. If the graph is undirected, then the expected degrees with andwithout self-loops are\frac{w (S + w)}{S}and\frac{w (S - w)}{S},respectively.
A limitation of the original Chung-Lu model is that when some of the weightsare large, the formula forp_{ij} yields values larger than 1.Chungand Lu's original paper excludes the use of such weights. Whenp_{ij} > 1, this function simply issues a warning and createsa connection betweeni andj. However, in this case the expecteddegrees 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 ofthe model, with modified expressions for the connection probabilityp_{ij} between verticesi andj. Letq_{ij} = \frac{w_i w_j}{S}, orq_{ij} = \frac{w^\text{out}_i w^\text{in}_j}{S}in the directed case. All model variants become equivalent in the limit of sparsegraphs whereq_{ij} approaches zero. In the original Chung-Lu model,selectable by settingvariant to “original”,p_{ij} =\min(q_{ij}, 1). The “maxent” variant,sometimes referred to as the generalized random graph, usesp_{ij} =\frac{q_{ij}}{1 + q_{ij}}, and is equivalent to amaximum entropy model (i.e., exponential random graph model) with aconstraint on expected degrees;see Park and Newman (2004), Section B, setting\exp(-\Theta_{ij}) =\frac{w_i w_j}{S}. This model is also discussedby Britton, Deijfen, and Martin-Löf (2006). By virtue of being adegree-constrained maximum entropy model, it generates graphs with the samedegree sequence with the same probability. A third variant can be requestedwith “nr”, and usesp_{ij} = 1 - \exp(-q_{ij}). This is the underlying simple graph of a multigraph modelintroduced by Norros and Reittu (2006). For a discussion of these three modelvariants, see Section 16.4 of Bollobás, Janson, Riordan (2007), as well asVan Der Hofstad (2013).
Value
An igraph graph.
Related documentation in the C library
References
Chung, F., and Lu, L. (2002). Connected components in a randomgraph with given degree sequences. Annals of Combinatorics, 6, 125-145.doi:10.1007/PL00012580
Miller, J. C., and Hagberg, A. (2011). Efficient Generation of Networkswith 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 SimpleRandom Graphs with Prescribed Degree Distribution. Journal of StatisticalPhysics, 124, 1377-1397.doi:10.1007/s10955-006-9168-x
Norros, I., and Reittu, H. (2006). On a conditionally Poissonian graphprocess. Advances in Applied Probability, 38, 59-75.doi:10.1239/aap/1143936140
Bollobás, B., Janson, S., and Riordan, O. (2007). The phase transition ininhomogeneous random graphs. Random Structures & Algorithms, 31, 3-122.doi:10.1002/rsa.20168
Van Der Hofstad, R. (2013). Critical behavior in inhomogeneous randomgraphs. Random Structures & Algorithms, 42, 480-508.doi:10.1002/rsa.20450
See Also
sample_fitness() implements a similar model with a sharpconstraint on the number of edges.sample_degseq() samples random graphswith sharply specified degrees.sample_gnp() creates random graphs with afixed connection probabilityp between all vertex pairs.
Random graph models (games)bipartite_gnm(),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()
Examples
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")))Generate a new random graph from a given graph by randomlyadding/removing edges
Description
Sample a new graph by perturbing the adjacency matrix of a given graphand shuffling its vertices.
Usage
sample_correlated_gnp( old.graph, corr, p = edge_density(old.graph), permutation = NULL)Arguments
old.graph | The original graph. |
corr | A scalar in the unit interval, the target Pearsoncorrelation between the adjacency matrices of the original and the generatedgraph (the adjacency matrix being used as a vector). |
p | A numeric scalar, the probability of an edge between twovertices, it must in the open (0,1) interval. The default is the empiricaledge density of the graph. If you are resampling an Erdős-Rényi graph andyou know the original edge probability of the Erdős-Rényi model, you shouldsupply that explicitly. |
permutation | A numeric vector, a permutation vector that isapplied on the vertices of the first graph, to get the second graph. If |
Details
Please see the reference given below.
Value
An unweighted graph of the same size asold.graph suchthat the correlation coefficient between the entries of the twoadjacency matrices iscorr. Note each pair of correspondingmatrix entries is a pair of correlated Bernoulli random variables.
Related documentation in the C library
References
Lyzinski, V., Fishkind, D. E., Priebe, C. E. (2013). Seededgraph matching for correlated Erdős-Rényi graphs.https://arxiv.org/abs/1304.7844
See Also
Random graph models (games)bipartite_gnm(),erdos.renyi.game(),sample_(),sample_bipartite(),sample_chung_lu(),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()
Examples
g <- sample_gnp(1000, .1)g2 <- sample_correlated_gnp(g, corr = 0.5)cor(as.vector(g[]), as.vector(g2[]))gg2Sample a pair of correlatedG(n,p) random graphs
Description
Sample a new graph by perturbing the adjacency matrix of a given graph andshuffling its vertices.
Usage
sample_correlated_gnp_pair(n, corr, p, directed = FALSE, permutation = NULL)Arguments
n | Numeric scalar, the number of vertices for the sampled graphs. |
corr | A scalar in the unit interval, the target Pearson correlationbetween the adjacency matrices of the original the generated graph (theadjacency matrix being used as a vector). |
p | A numeric scalar, the probability of an edge between two vertices,it must in the open (0,1) interval. |
directed | Logical scalar, whether to generate directed graphs. |
permutation | A numeric vector, a permutation vector that is applied onthe vertices of the first graph, to get the second graph. If |
Details
Please see the reference given below.
Value
A list of two igraph objects, namedgraph1 andgraph2, which are two graphs whose adjacency matrix entries arecorrelated withcorr.
Related documentation in the C library
References
Lyzinski, V., Fishkind, D. E., Priebe, C. E. (2013). Seededgraph matching for correlated Erdős-Rényi graphs.https://arxiv.org/abs/1304.7844
See Also
Random graph models (games)bipartite_gnm(),erdos.renyi.game(),sample_(),sample_bipartite(),sample_chung_lu(),sample_correlated_gnp(),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()
Examples
gg <- sample_correlated_gnp_pair( n = 10, corr = .8, p = .5, directed = FALSE)ggcor(as.vector(gg[[1]][]), as.vector(gg[[2]][]))Generate random graphs with a given degree sequence
Description
It is often useful to create a graph with given vertex degrees. This functioncreates such a graph in a randomized manner.
Usage
sample_degseq( out.deg, in.deg = NULL, method = c("configuration", "vl", "fast.heur.simple", "configuration.simple", "edge.switching.simple"))degseq(..., deterministic = FALSE)Arguments
out.deg | Numeric vector, the sequence of degrees (for undirectedgraphs) or out-degrees (for directed graphs). For undirected graphs its sumshould 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 |
Details
The “configuration” method (formerly called "simple") implements theconfiguration model. For undirected graphs, it puts all vertex IDs in a bagsuch 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 maygenerate both loop (self) edges and multiple edges. For directed graphs,the algorithm is basically the same, but two separate bags are usedfor the in- and out-degrees. Undirected graphs are generatedwith probability proportional to(\prod_{i<j} A_{ij} ! \prod_i A_{ii} !!)^{-1},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(\prod_{i,j} A_{ij}!)^{-1}.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 andself-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 andloop 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 succeedif the provided degree sequence is graphical, but there is no upper bound onthe number of iterations.
The “configuration.simple” method (formerly called "simple.no.multiple.uniform")isidentical 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 begenerated and execution time is not a concern. igraph usesthe original implementation of Fabien Viger; for the algorithm, seehttps://www-complexnetworks.lip6.fr/~latapy/FV/generation.htmland the paperhttps://arxiv.org/abs/cs/0502085.
The “edge.switching.simple” is an MCMC sampler based ondegree-preserving edge switches. It generates simple undirected or directed graphs.
Value
The new graph object.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
simplify() to get rid of the multiple and/or loops edges,realize_degseq() for a deterministic variant.
Random graph models (games)bipartite_gnm(),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()
Examples
## The simple generatorundirected_graph <- sample_degseq(rep(2, 100))degree(undirected_graph)is_simple(undirected_graph) # sometimes TRUE, but can be FALSEdirected_graph <- sample_degseq(1:10, 10:1)degree(directed_graph, mode = "out")degree(directed_graph, mode = "in")## The vl generatorvl_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 oddis_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 oddis_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 oddis_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 oddis_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 from a Dirichlet distribution
Description
Sample finite-dimensional vectors to use as latent position vectors inrandom dot product graphs
Usage
sample_dirichlet(n, alpha)Arguments
n | Integer scalar, the sample size. |
alpha | Numeric vector, the vector of |
Details
sample_dirichlet() generates samples from the Dirichlet distributionwith given\alpha parameter. The sample is drawn fromlength(alpha)-1-simplex.
Value
Adim (length of thealpha vector forsample_dirichlet()) timesn matrix, whose columns are the samplevectors.
See Also
Other latent position vector samplers:sample_sphere_surface(),sample_sphere_volume()
Examples
lpvs.dir <- sample_dirichlet(n = 20, alpha = rep(1, 10))RDP.graph.2 <- sample_dot_product(lpvs.dir)colSums(lpvs.dir)Generate random graphs according to the random dot product graph model
Description
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 oftheir latent position vectors.
Usage
sample_dot_product(vecs, directed = FALSE)dot_product(...)Arguments
vecs | A numeric matrix in which each latent position vector is acolumn. |
directed | A logical scalar, TRUE if the generated graph should bedirected. |
... | Passed to |
Details
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 edgesare added; dot products that are larger than one always add an edge.
Value
An igraph graph object which is the generated random dot productgraph.
Related documentation in the C library
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
Christine Leigh Myers Nickel: Random dot product graphs, a modelfor social networks. Dissertation, Johns Hopkins University, Maryland, USA,2006.
See Also
sample_dirichlet(),sample_sphere_surface()andsample_sphere_volume() for sampling position vectors.
Random graph models (games)bipartite_gnm(),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()
Examples
## A randomly generated graphlpvs <- 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 spherelpvs2 <- sample_sphere_surface(dim = 5, n = 20)g2 <- sample_dot_product(lpvs2)g2Random graphs from vertex fitness scores
Description
This function generates a non-growing random graph with edge probabilitiesproportional to node fitness scores.
Usage
sample_fitness( no.of.edges, fitness.out, fitness.in = NULL, loops = FALSE, multiple = FALSE)Arguments
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 thegraph. |
Details
This game generates a directed or undirected random graph where theprobability of an edge between verticesi andj depends on thefitness scores of the two vertices involved. For undirected graphs, eachvertex has a single fitness score. For directed graphs, each vertex has anout- and an in-fitness, and the probability of an edge fromi toj depends on the out-fitness of vertexi and the in-fitness ofvertexj.
The generation process goes as follows. We start fromN disconnectednodes (whereN is given by the length of the fitness vector). Then werandomly select two verticesi andj, with probabilitiesproportional to their fitnesses. (When the generated graph is directed,i is selected according to the out-fitnesses andj is selectedaccording to the in-fitnesses). If the vertices are not connected yet (or ifmultiple edges are allowed), we connect them; otherwise we select a newpair. This is repeated until the desired number of links are created.
It can be shown that theexpected degree of each vertex will beproportional to its fitness, although the actual, observed degree will notbe. If you need to generate a graph with an exact degree sequence, considersample_degseq() instead.
This model is commonly used to generate static scale-free networks. Toachieve this, you have to draw the fitness scores from the desired power-lawdistribution. Alternatively, you may usesample_fitness_pl()which generates the fitnesses for you with a given exponent.
Value
An igraph graph, directed or undirected.
Related documentation in the C library
Author(s)
Tamas Nepuszntamas@gmail.com
References
Goh K-I, Kahng B, Kim D: Universal behaviour of loaddistribution in scale-free networks.Phys Rev Lett 87(27):278701,2001.
See Also
Random graph models (games)bipartite_gnm(),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()
Examples
N <- 10000g <- sample_fitness(5 * N, sample((1:50)^-2, N, replace = TRUE))degree_distribution(g)plot(degree_distribution(g, cumulative = TRUE), log = "xy")Scale-free random graphs, from vertex fitness scores
Description
This function generates a non-growing random graph with expected power-lawdegree distributions.
Usage
sample_fitness_pl( no.of.nodes, no.of.edges, exponent.out, exponent.in = -1, loops = FALSE, multiple = FALSE, finite.size.correction = TRUE)Arguments
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 degreedistribution. For directed graphs, this specifies the exponent of theout-degree distribution. It must be greater than or equal to 2. If you pass |
exponent.in | Numeric scalar. If negative, the generated graph will beundirected. If greater than or equal to 2, this argument specifies theexponent of the in-degree distribution. If non-negative but less than 2, anerror will be generated. |
loops | Logical scalar, whether to allow loop edges in the generatedgraph. |
multiple | Logical scalar, whether to allow multiple edges in thegenerated graph. |
finite.size.correction | Logical scalar, whether to use the proposedfinite size correction of Cho et al., see references below. |
Details
This game generates a directed or undirected random graph where the degreesof vertices follow power-law distributions with prescribed exponents. Fordirected graphs, the exponents of the in- and out-degree distributions maybe specified separately.
The game simply usessample_fitness() with appropriatelyconstructed fitness vectors. In particular, the fitness of vertexi isi^{-\alpha}, where\alpha = 1/(\gamma-1)and\gamma is the exponent given in the arguments.
To remove correlations between in- and out-degrees in case of directedgraphs, the in-fitness vector will be shuffled after it has been set up andbeforesample_fitness() is called.
Note that significant finite size effects may be observed for exponentssmaller than 3 in the original formulation of the game. This functionprovides an argument that lets you remove the finite size effects byassuming that the fitness of vertexi is(i+i_0-1)^{-\alpha} wherei_0 is aconstant chosen appropriately to ensure that the maximum degree is less thanthe square root of the number of edges times the average degree; see thepaper of Chung and Lu, and Cho et al for more details.
Value
An igraph graph, directed or undirected.
Related documentation in the C library
Author(s)
Tamas Nepuszntamas@gmail.com
References
Goh K-I, Kahng B, Kim D: Universal behaviour of loaddistribution in scale-free networks.Phys Rev Lett 87(27):278701,2001.
Chung F and Lu L: Connected components in a random graph with given degreesequences.Annals of Combinatorics 6, 125-145, 2002.
Cho YS, Kim JS, Park J, Kahng B, Kim D: Percolation transitions inscale-free networks under the Achlioptas process.Phys Rev Lett103:135702, 2009.
See Also
Random graph models (games)bipartite_gnm(),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()
Examples
g <- sample_fitness_pl(10000, 30000, 2.2, 2.3)plot(degree_distribution(g, cumulative = TRUE, mode = "out"), log = "xy")Forest Fire Network Model
Description
This is a growing network model, which resembles of how the forest firespreads by igniting trees close by.
Usage
sample_forestfire(nodes, fw.prob, bw.factor = 1, ambs = 1, directed = TRUE)Arguments
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 burningprobability is calculated as |
ambs | The number of ambassador vertices. |
directed | Logical scalar, whether to create a directed graph. |
Details
The forest fire model intends to reproduce the following networkcharacteristics, observed in real networks:
Heavy-tailedin-degree distribution.
Heavy-tailed out-degree distribution.
Communities.
Densification power-law. The network is densifying intime, according to a power-law rule.
Shrinking diameter. The diameterof the network decreases in time.
The network is generated in the following way. One vertex is added at atime. This vertex connects to (cites)ambs vertices already presentin the network, chosen uniformly random. Now, for each cited vertexvwe do the following procedure:
We generate two randomnumber,
xandy, that are geometrically distributed with meansp/(1-p)andrp(1-rp). (pisfw.prob,risbw.factor.) The new vertex citesxoutgoing neighbors andyincoming neighbors ofv, from those which are not yet cited bythe new vertex. If there are less thanxorysuch verticesavailable then we cite all of them.The same procedure is applied toall the newly cited vertices.
Value
A simple graph, possibly directed if thedirected argument isTRUE.
Related documentation in the C library
Note
The version of the model in the published paper is incorrect in thesense that it cannot generate the kind of graphs the authors claim. Acorrected version is available fromhttps://www.cs.cmu.edu/~jure/pubs/powergrowth-tkdd.pdf, ourimplementation is based on this.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
Jure Leskovec, Jon Kleinberg and Christos Faloutsos. Graphs overtime: densification laws, shrinking diameters and possible explanations.KDD '05: Proceeding of the eleventh ACM SIGKDD internationalconference on Knowledge discovery in data mining, 177–187, 2005.
See Also
sample_pa() for the basic preferential attachmentmodel.
Random graph models (games)bipartite_gnm(),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()
Examples
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)Generate random graphs according to theG(n,m) Erdős-Rényi model
Description
Random graph with a fixed number of edges and vertices.
Usage
sample_gnm(n, m, directed = FALSE, loops = FALSE)gnm(...)Arguments
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 |
Details
The graph hasn vertices andm edges. The edges are chosen uniformlyat random from the set of all vertex pairs. This set includes potentialself-connections as well if theloops parameter isTRUE.
Value
A graph object.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
Erdős, P. and Rényi, A., On random graphs,PublicationesMathematicae 6, 290–297 (1959).
See Also
Random graph models (games)bipartite_gnm(),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()
Examples
g <- sample_gnm(1000, 1000)degree_distribution(g)Generate random graphs according to theG(n,p) Erdős-Rényi model
Description
Every possible edge is created independently with the same probabilityp.This model is also referred to as a Bernoulli random graph since theconnectivity status of vertex pairs follows a Bernoulli distribution.
Usage
sample_gnp(n, p, directed = FALSE, loops = FALSE)gnp(...)Arguments
n | The number of vertices in the graph. |
p | The probability for drawing an edge between twoarbitrary vertices ( |
directed | Logical, whether the graph will be directed, defaults to |
loops | Logical, whether to add loop edges, defaults to |
... | Passed to |
Details
The graph hasn vertices and each pair of vertices is connectedwith the same probabilityp. Theloops parameter controls whetherself-connections are also considered. This model effectively constrainsthe average number of edges,p m_\text{max}, wherem_\text{max}is the largest possible number of edges, which depends on whether thegraph is directed or undirected and whether self-loops are allowed.
Value
A graph object.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
Erdős, P. and Rényi, A., On random graphs,PublicationesMathematicae 6, 290–297 (1959).
See Also
Random graph models (games)bipartite_gnm(),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()
Examples
# Random graph with expected mean degree of 2g <- sample_gnp(1000, 2 / 1000)mean(degree(g))degree_distribution(g)# Pick a simple graph on 6 vertices uniformly at randomplot(sample_gnp(6, 0.5))Geometric random graphs
Description
Generate a random graph based on the distance of random point on a unitsquare
Usage
sample_grg(nodes, radius, torus = FALSE, coords = FALSE)grg(...)Arguments
nodes | The number of vertices in the graph. |
radius | The radius within which the vertices will be connected by anedge. |
torus | Logical constant, whether to use a torus instead of a square. |
coords | Logical scalar, whether to add the positions of the verticesas vertex attributes called ‘ |
... | Passed to |
Details
First a number of points are dropped on a unit square, these pointscorrespond to the vertices of the graph to create. Two points will beconnected with an undirected edge if they are closer to each other inEuclidean norm than a given radius. If thetorus argument isTRUE then a unit area torus is used instead of a square.
Value
A graph object. Ifcoords isTRUE then with vertexattributes ‘x’ and ‘y’.
Author(s)
Gabor Csardicsardi.gabor@gmail.com, first version waswritten by Keith Briggs (https://keithbriggs.info/).
See Also
Random graph models (games)bipartite_gnm(),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()
Examples
g <- sample_grg(1000, 0.05, torus = FALSE)g2 <- sample_grg(1000, 0.05, torus = TRUE)Growing random graph generation
Description
This function creates a random graph by simulating its stochastic evolution.
Usage
sample_growing(n, m = 1, ..., directed = TRUE, citation = FALSE)growing(...)Arguments
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 |
Details
This is discrete time step model, in each time step a new vertex is added tothe graph andm new edges are created. Ifcitation isFALSE these edges are connecting two uniformly randomly chosenvertices, otherwise the edges are connecting new vertex to uniformlyrandomly chosen old vertices.
Value
A new graph object.
Related documentation in the C library
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
Random graph models (games)bipartite_gnm(),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()
Examples
g <- sample_growing(500, citation = FALSE)g2 <- sample_growing(500, citation = TRUE)Sample the hierarchical stochastic block model
Description
Sampling from a hierarchical stochastic block model of networks.
Usage
sample_hierarchical_sbm(n, m, rho, C, p)hierarchical_sbm(...)Arguments
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 ablock. Must sum up to 1, and |
C | A square, symmetric numeric matrix, the Bernoulli rates for theclusters within a block. Its size must mach the size of the |
p | Numeric scalar, the Bernoulli rate of connections between verticesin different blocks. |
... | Passed to |
Details
The function generates a random graph according to the hierarchicalstochastic block model.
Value
An igraph graph.
Related documentation in the C library
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
Random graph models (games)bipartite_gnm(),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()
Examples
## Ten blocks with three clusters eachC <- 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)glibrary("Matrix")image(g[])Sample from a hierarchical random graph model
Description
sample_hrg() samples a graph from a given hierarchical random graphmodel.
Usage
sample_hrg(hrg)Arguments
hrg | A hierarchical random graph model. |
Value
An igraph graph.
Related documentation in the C library
See Also
Other hierarchical random graph functions:consensus_tree(),fit_hrg(),hrg(),hrg-methods,hrg_tree(),predict_edges(),print.igraphHRG(),print.igraphHRGConsensus()
A graph with subgraphs that are each a random graph.
Description
Create a number of Erdős-Rényi random graphs with identical parameters, andconnect them with the specified number of edges.
Usage
sample_islands(islands.n, islands.size, islands.pin, n.inter)Arguments
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 eachisland. |
n.inter | The number of edges to create between two islands. |
Value
An igraph graph.
Examples
g <- sample_islands(3, 10, 5/10, 1)oc <- cluster_optimal(g)oc
Related documentation in the C library
simple_interconnected_islands_game().
Author(s)
Samuel Thiriot
See Also
Random graph models (games)bipartite_gnm(),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()
Create a random regular graph
Description
Generate a random graph where each vertex has the same degree.
Usage
sample_k_regular(no.of.nodes, k, directed = FALSE, multiple = FALSE)Arguments
no.of.nodes | Integer scalar, the number of vertices in the generatedgraph. |
k | Integer scalar, the degree of each vertex in the graph, or theout-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. |
Details
This game generates a directed or undirected random graph where the degreesof vertices are equal to a predefined constant k. For undirected graphs, atleast one of k and the number of vertices must be even.
The game simply usessample_degseq() with appropriatelyconstructed degree sequences.
Value
An igraph graph.
Related documentation in the C library
Author(s)
Tamas Nepuszntamas@gmail.com
See Also
sample_degseq() for a generator with prescribed degreesequence.
Random graph models (games)bipartite_gnm(),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()
Examples
## A simple ringring <- sample_k_regular(10, 2)plot(ring)## k-regular graphs on 10 vertices, with k=1:9k10 <- lapply(1:9, sample_k_regular, no.of.nodes = 10)layout(matrix(1:9, nrow = 3, byrow = TRUE))sapply(k10, plot, vertex.label = NA)Random citation graphs
Description
sample_last_cit() creates a graph, where vertices age, andgain new connections based on how long ago their last citationhappened.
Usage
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(...)Arguments
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 generatedgraph as a vertex attribute called ‘ |
Details
sample_cit_cit_types() is a stochastic block model where thegraph is growing.
sample_cit_types() is similarly a growing stochastic block model,but the probability of an edge depends on the (potentially) citedvertex only.
Value
A new graph.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
Random graph models (games)bipartite_gnm(),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
Description
Graph motifs are small connected induced subgraphs with a well-definedstructure. These functions search a graph for various motifs.
Usage
sample_motifs( graph, size = 3, cut.prob = rep(0, size), sample.size = NULL, sample = NULL)Arguments
graph | Graph object, the input graph. |
size | The size of the motif, currently size 3 and 4 are supportedin directed graphs and sizes 3-6 in undirected graphs. |
cut.prob | Numeric vector giving the probabilities that the searchgraph is cut at a certain level. Its length should be the same as the sizeof the motif (the |
sample.size | The number of vertices to use as a starting point forfinding motifs. Only used if the |
sample | If not |
Details
sample_motifs() estimates the total number of motifs of a givensize in a graph based on a sample.
Value
A numeric scalar, an estimate for the total number of motifs inthe graph.
See Also
Other graph motifs:count_motifs(),dyad_census(),motifs()
Examples
g <- sample_pa(100)motifs(g, 3)count_motifs(g, 3)sample_motifs(g, 3)Generate random graphs using preferential attachment
Description
Preferential attachment is a family of simple stochastic algorithms for buildinga graph. Variants include the Barabási-Abert model and the Price model.
Usage
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(...)Arguments
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 Thisargument is only used if both |
out.dist | Numeric vector, the distribution of the number of edges toadd in each time step. This argument is only used if the |
out.seq | Numeric vector giving the number of edges to add in each timestep. Its first element is ignored as no edges are added in the first timestep. |
out.pref | Logical, if true the total degree is used for calculatingthe citation probability, otherwise the in-degree is used. |
zero.appeal | The ‘attractiveness’ of the vertices with noadjacent edges. See details below. |
directed | Whether to create a directed graph. |
algorithm | The algorithm to use for the graph generation. |
start.graph |
|
... | Passed to |
Details
This is a simple stochastic algorithm to generate a graph. It is a discretetime 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 weadd one vertex in each time step and the new vertex initiates some edges toold vertices. The probability that an old vertex is chosen is given by
P[i] \sim k_i^\alpha+a
wherek_iis the in-degree of vertexi in the current time step (more preciselythe number of adjacent edges ofi which were not initiated byiitself) and\alpha anda are parameters given by thepower andzero.appeal arguments.
The number of edges initiated in a time step is given by them,out.dist andout.seq arguments. Ifout.seq is given andnot NULL then it gives the number of edges to add in a vector, the firstelement is ignored, the second is the number of edges to add in the secondtime step and so on. Ifout.seq is not given or null andout.dist is given and not NULL then it is used as a discretedistribution to generate the number of edges in each time step. Its firstelement is the probability that no edges will be added, the second is theprobability that one edge is added, etc. (out.dist does not need tosum up to one, it normalized automatically.)out.dist should containnon-negative numbers and at east one element should be positive.
If bothout.seq andout.dist are omitted or NULL thenmwill be used, it should be a positive integer constant andm edgeswill be added in each time step.
sample_pa() generates a directed graph by default, setdirected toFALSE to generate an undirected graph. Note thateven if an undirected graph is generatedk_i denotes the numberof adjacent edges not initiated by the vertex itself and not the total(in- + out-) degree of the vertex, unless theout.pref argument is set toTRUE.
Value
A graph object.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
Barabási, A.-L. and Albert R. 1999. Emergence of scaling inrandom networksScience, 286 509–512.
de Solla Price, D. J. 1965. Networks of Scientific PapersScience,149 510–515.
See Also
Random graph models (games)bipartite_gnm(),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()
Examples
g <- sample_pa(10000)degree_distribution(g)Generate an evolving random graph with preferential attachment and aging
Description
This function creates a random graph by simulating its evolution. Each timea new vertex is added it creates a number of links to old vertices and theprobability that an old vertex is cited depends on its in-degree(preferential attachment) and age.
Usage
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(...)Arguments
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 firstvertex). This argument is used only if both the |
aging.bin | The number of bins to use for measuring the age ofvertices, see details below. |
out.dist | The discrete distribution to generate the number of edges toadd in each time step if |
out.seq | The number of edges to add in each time step, a vectorcontaining as many elements as the number of vertices. See details below. |
out.pref | Logical constant, whether to include edges not initiated bythe vertex as a basis of preferential attachment. See details below. |
directed | Logical constant, whether to generate a directed graph. Seedetails below. |
zero.deg.appeal | The degree-dependent part of the‘attractiveness’ of the vertices with no adjacent edges. See alsodetails 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 |
Details
This is a discrete time step model of a growing graph. We start with anetwork 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 andit initiates a number of edges to the old vertices in the network. Theprobability that an old vertex is connected to is proportional to
P[i] \sim (c\cdot k_i^\alpha+a)(d\cdot l_i^\beta+b)
.
Herek_i is the in-degree of vertexi in the current timestep andl_i is the age of vertexi. The age is simplydefined as the number of time steps passed since the vertex is added, withthe extension that vertex age is divided to be inaging.bin bins.
c,\alpha,a,d,\beta andb are parameters and they can be set via the following arguments:pa.exp (\alpha, mandatory argument),aging.exp(\beta, mandatory argument),zero.deg.appeal (a,optional, the default value is 1),zero.age.appeal (b,optional, the default is 0),deg.coef (c, optional, the defaultis 1), andage.coef (d, optional, the default is 1).
The number of edges initiated in each time step is governed by them,out.seq andout.pref parameters. Ifout.seq is giventhen it is interpreted as a vector giving the number of edges to be added ineach time step. It should be of lengthn (the number of vertices),and its first element will be ignored. Ifout.seq is not given (orNULL) andout.dist is given then it will be used as a discreteprobability distribution to generate the number of edges. Its first elementgives the probability that zero edges are added at a time step, the secondelement is the probability that one edge is added, etc. (out.seqshould contain non-negative numbers, but if they don't sum up to 1, theywill be normalized to sum up to 1. This behavior is similar to theprob argument of thesample command.)
By default a directed graph is generated, but itdirected is set toFALSE then an undirected is created. Even if an undirected graph isgeneratedk_i denotes only the adjacent edges not initiated bythe vertex itself except ifout.pref is set toTRUE.
If thetime.window argument is given (and not NULL) thenk_i means only the adjacent edges added in the previoustime.window time steps.
This function might generate graphs with multiple edges.
Value
A new graph.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
Random graph models (games)bipartite_gnm(),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()
Examples
# The maximum degree for graph with different aging exponentsg1 <- 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))Trait-based random generation
Description
Generation of random graphs based on different vertex types.
Usage
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(...)Arguments
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 oflength ‘types’ containing non-negative numbers. The vector will benormed to obtain probabilities. |
fixed.sizes | Fix the number of vertices with a given vertex typelabel. The |
pref.matrix | A square matrix giving the preferences of the vertextypes. The matrix has ‘types’ rows and columns. When generatingan 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-vertextypes. |
Details
Both models generate random graphs with given vertex types. Forsample_pref() the probability that two vertices will be connecteddepends on their type and is given by the ‘pref.matrix’ argument.This matrix should be symmetric to make sense but this is not checked. Thedistribution of the different vertex types is given by the‘type.dist’ vector.
Forsample_asym_pref() each vertex has an in-type and anout-type and a directed graph is created. The probability that a directededge is realized from a vertex with a given out-type to a vertex with agiven in-type is given in the ‘pref.matrix’ argument, which can beasymmetric. 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 thetype vertex attribute forsample_pref() and from theintype andouttype vertex attribute forsample_asym_pref().
Value
An igraph graph.
Author(s)
Tamas Nepuszntamas@gmail.com and Gabor Csardicsardi.gabor@gmail.com for the R interface
See Also
Random graph models (games)bipartite_gnm(),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()
Examples
pf <- matrix(c(1, 0, 0, 1), nrow = 2)g <- sample_pref(20, 2, pref.matrix = pf)# example codetkplot(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)Sample stochastic block model
Description
Sampling from the stochastic block model of networks
Usage
sample_sbm(n, pref.matrix, block.sizes, directed = FALSE, loops = FALSE)sbm(...)Arguments
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 eachgroup. 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 |
Details
This function samples graphs from a stochastic block model by (doing theequivalent of) Bernoulli trials for each potential edge with theprobabilities given by the Bernoulli rate matrix,pref.matrix.The order of the vertices in the generated graph corresponds to theblock.sizes argument.
Value
An igraph graph.
Related documentation in the C library
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
Faust, K., & Wasserman, S. (1992a). Blockmodels: Interpretationand evaluation.Social Networks, 14, 5–61.
See Also
Random graph models (games)bipartite_gnm(),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()
Examples
## Two groups with not only few connection between groupspm <- cbind(c(.1, .001), c(.001, .05))g <- sample_sbm(1000, pref.matrix = pm, block.sizes = c(300, 700))gSampling a random integer sequence
Description
This function provides a very efficient way to pull an integer random samplesequence from an integer interval.
Usage
sample_seq(low, high, length)Arguments
low | The lower limit of the interval (inclusive). |
high | The higher limit of the interval (inclusive). |
length | The length of the sample. |
Details
The algorithm runs inO(length) expected time, even ifhigh-low is big. It is much faster (but of course less general) thanthe builtinsample function of R.
Value
An increasing numeric vector containing integers, the sample.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
Jeffrey Scott Vitter: An Efficient Algorithm for SequentialRandom Sampling,ACM Transactions on Mathematical Software, 13/1,58–67.
See Also
Other other:convex_hull(),running_mean()
Examples
rs <- sample_seq(1, 100000000, 10)rsThe Watts-Strogatz small-world model
Description
This function generates networks with the small-world propertybased on a variant of the Watts-Strogatz model. The network is obtainedby first creating a periodic undirected lattice, then rewiring bothendpoints of each edge with probabilityp, while avoiding thecreation of multi-edges.
Usage
sample_smallworld(dim, size, nei, p, loops = FALSE, multiple = FALSE)smallworld(...)Arguments
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 ofthe lattice will be connected. |
p | Real constant between zero and one, the rewiring probability. |
loops | Logical scalar, whether loops edges are allowed in thegenerated graph. |
multiple | Logical scalar, whether multiple edges are allowed int thegenerated graph. |
... | Passed to |
Details
Note that this function might create graphs with loops and/or multipleedges. You can usesimplify() to get rid of these.
This process differs from the original model of Watts and Strogatz(see reference) in that it rewiresboth endpoints of edges. Thus inthe limit ofp=1, we obtain a G(n,m) random graph with thesame 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 forp=1.For appropriate choices ofp, both models exhibit the property ofsimultaneously having short path lengths and high clustering.
Value
A graph object.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
Duncan J Watts and Steven H Strogatz: Collective dynamics of‘small world’ networks, Nature 393, 440-442, 1998.
See Also
Random graph models (games)bipartite_gnm(),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()
Examples
g <- sample_smallworld(1, 100, 5, 0.05)mean_distance(g)transitivity(g, type = "average")Samples from the spanning trees of a graph randomly and uniformly
Description
sample_spanning_tree() picks a spanning tree of an undirected graphrandomly and uniformly, using loop-erased random walks.
Usage
sample_spanning_tree(graph, vid = 0)Arguments
graph | The input graph to sample from. Edge directions are ignored ifthe graph is directed. |
vid | When the graph is disconnected, this argument specifies how tohandle the situation. When the argument is zero (the default), the samplingwill be performed component-wise, and the result will be a spanning forest.When the argument contains a vertex ID, only the component containing thegiven vertex will be processed, and the result will be a spanning tree of thecomponent of the graph. |
Value
An edge sequence containing the edges of the spanning tree. Usesubgraph_from_edges() to extract the corresponding subgraph.
Related documentation in the C library
See Also
subgraph_from_edges() to extract the tree itself
Other trees:is_forest(),is_tree(),make_from_prufer(),to_prufer()
Examples
g <- make_full_graph(10) %du% make_full_graph(5)edges <- sample_spanning_tree(g)forest <- subgraph_from_edges(g, edges)Sample vectors uniformly from the surface of a sphere
Description
Sample finite-dimensional vectors to use as latent position vectors inrandom dot product graphs
Usage
sample_sphere_surface(dim, n = 1, radius = 1, positive = TRUE)Arguments
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 orthantof the sphere. |
Details
sample_sphere_surface() generates uniform samples fromS^{dim-1}(the(dim-1)-sphere) with radiusradius, i.e. the Euclideannorm of the samples equalradius.
Value
Adim (length of thealpha vector forsample_dirichlet()) timesn matrix, whose columns are the samplevectors.
See Also
Other latent position vector samplers:sample_dirichlet(),sample_sphere_volume()
Examples
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.normSample vectors uniformly from the volume of a sphere
Description
Sample finite-dimensional vectors to use as latent position vectors inrandom dot product graphs
Usage
sample_sphere_volume(dim, n = 1, radius = 1, positive = TRUE)Arguments
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 orthantof the sphere. |
Details
sample_sphere_volume() generates uniform samples fromS^{dim-1}(the(dim-1)-sphere) i.e. the Euclidean norm of the samples issmaller or equal toradius.
Value
Adim (length of thealpha vector forsample_dirichlet()) timesn matrix, whose columns are the samplevectors.
See Also
Other latent position vector samplers:sample_dirichlet(),sample_sphere_surface()
Examples
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.normGraph generation based on different vertex types
Description
These functions implement evolving network models based on different vertextypes.
Usage
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(...)Arguments
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 bestationary in time. |
pref.matrix | A matrix giving the preferences of the given vertextypes. 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. |
Details
Forsample_traits_callaway() the simulation goes like this: in eachdiscrete time step a new vertex is added to the graph. The type of thisvertex is generated based ontype.dist. Then two vertices areselected uniformly randomly from the graph. The probability that they willbe connected depends on the types of these vertices and is taken frompref.matrix. Then another two vertices are selected and this isrepeatededges.per.step times in each time step.
Forsample_traits() the simulation goes like this: a single vertex isadded at each time step. This new vertex tries to connect tokvertices in the graph. The probability that such a connection is realizeddepends on the types of the vertices involved and is taken frompref.matrix.
Value
A new graph object.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
Random graph models (games)bipartite_gnm(),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()
Examples
# two types of vertices, they like only themselvesg1 <- 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 trees randomly and uniformly
Description
sample_tree() generates a random with a given number of nodes uniformat random from the set of labelled trees.
Usage
sample_tree(n, directed = FALSE, method = c("lerw", "prufer"))Arguments
n | The number of nodes in the tree |
directed | Whether to create a directed tree. The edges of the tree areoriented 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 toa tree. ‘lerw’ performs a loop-erased random walk on the completegraph to uniformly sampleits spanning trees. (This is also known as Wilson'salgorithm). The default is ‘lerw’. Note that the method based onPrüfer sequences does not support directed trees at the moment. |
Details
In other words, the function generates each possible labelled tree with thegiven number of nodes with the same probability.
Value
A graph object.
Related documentation in the C library
See Also
Random graph models (games)bipartite_gnm(),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()
Examples
g <- sample_tree(100, method = "lerw")Sample stochastic block model
Description
sbm.game() was renamed tosample_sbm() to create a moreconsistent API.
Usage
sbm.game(n, pref.matrix, block.sizes, directed = FALSE, loops = FALSE)Arguments
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 eachgroup. 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. |
Scan statistics on a time series of graphs
Description
Calculate scan statistics on a time series of graphs.This is done by calculating the local scan statistics foreach graph and each vertex, and then normalizing across thevertices and across the time steps.
Usage
scan_stat(graphs, tau = 1, ell = 0, locality = c("us", "them"), ...)Arguments
graphs | A list of igraph graph objects. They must be all directedor all undirected and they must have the same number of vertices. |
tau | The number of previous time steps to consider for thetime-dependent normalization for individual vertices. In other words,the current locality statistics of each vertex will be compared to thismany previous time steps of the same vertex to decide whether it issignificantly larger. |
ell | The number of previous time steps to considerfor the aggregated scan statistics. This is essentially a smoothingparameter. |
locality | Whether to calculate the ‘us’ or ‘them’statistics. |
... | Extra arguments are passed to |
Value
A list with entries:
- stat
The scan statistics in each time step.It is
NAfor the initialtau + elltime steps.- arg_max_v
The (numeric) vertex ids for the vertex with the largest locality statistics, at each time step.It is
NAfor the initialtau + elltime steps.
See Also
Other scan statistics:local_scan()
Examples
## Generate a bunch of SBMs, with the last one being differentnum_t <- 20block_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$hPA <- P0PA[3, 3] <- p_ij$qnum_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)Sequential palette
Description
This is the ‘OrRd’ palette fromhttps://colorbrewer2.org/.It has at most nine colors.
Usage
sequential_pal(n)Arguments
n | The number of colors in the palette. The maximum is ninecurrently. |
Details
Use this palette, if vertex colors mark some ordinal quantity, e.g. somecentrality measure, or some ordinal vertex covariate, like the age ofpeople, or their seniority level.
Value
A character vector of RGB color codes.
See Also
Other palettes:categorical_pal(),diverging_pal(),r_pal()
Examples
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
Description
set.edge.attribute() was renamed toset_edge_attr() to create a moreconsistent API.
Usage
set.edge.attribute(graph, name, index = E(graph), value)Arguments
graph | The graph |
name | The name of the attribute to set. |
index | An optional edge sequence to set the attributes ofa subset of edges. |
value | The new value of the attribute for all (or |
Set a graph attribute
Description
set.graph.attribute() was renamed toset_graph_attr() to create a moreconsistent API.
Usage
set.graph.attribute(graph, name, value)Arguments
graph | The graph. |
name | The name of the attribute to set. |
value | New value of the attribute. |
Set vertex attributes
Description
set.vertex.attribute() was renamed toset_vertex_attr() to create a moreconsistent API.
Usage
set.vertex.attribute(graph, name, index = V(graph), value)Arguments
graph | The graph. |
name | The name of the attribute to set. |
index | An optional vertex sequence to set the attributesof a subset of vertices. |
value | The new value of the attribute for all (or |
Set edge attributes
Description
Set edge attributes
Usage
set_edge_attr(graph, name, index = E(graph), value)Arguments
graph | The graph |
name | The name of the attribute to set. |
index | An optional edge sequence to set the attributes ofa subset of edges. |
value | The new value of the attribute for all (or |
Value
The graph, with the edge attribute added or set.
See Also
Vertex, edge and graph attributesdelete_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(),set_vertex_attrs(),vertex_attr(),vertex_attr<-(),vertex_attr_names()
Examples
g <- make_ring(10) %>% set_edge_attr("label", value = LETTERS[1:10])gplot(g)Set a graph attribute
Description
An existing attribute with the same name is overwritten.
Usage
set_graph_attr(graph, name, value)Arguments
graph | The graph. |
name | The name of the attribute to set. |
value | New value of the attribute. |
Value
The graph with the new graph attribute added or set.
See Also
Vertex, edge and graph attributesdelete_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(),set_vertex_attrs(),vertex_attr(),vertex_attr<-(),vertex_attr_names()
Examples
g <- make_ring(10) %>% set_graph_attr("layout", layout_with_fr)gplot(g)Set vertex attributes
Description
Set vertex attributes
Usage
set_vertex_attr(graph, name, index = V(graph), value)Arguments
graph | The graph. |
name | The name of the attribute to set. |
index | An optional vertex sequence to set the attributesof a subset of vertices. |
value | The new value of the attribute for all (or |
Value
The graph, with the vertex attribute added or set.
See Also
Vertex, edge and graph attributesdelete_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_attrs(),vertex_attr(),vertex_attr<-(),vertex_attr_names()
Examples
g <- make_ring(10) %>% set_vertex_attr("label", value = LETTERS[1:10])gplot(g)Set multiple vertex attributes
Description
Set multiple vertex attributes
Usage
set_vertex_attrs(graph, ..., index = V(graph))Arguments
graph | The graph. |
... | < |
index | An optional vertex sequence to set the attributesof a subset of vertices. |
Value
The graph, with the vertex attributes added or set.
See Also
Vertex, edge and graph attributesdelete_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<-(),vertex_attr_names()
Examples
g <- make_ring(10)set_vertex_attrs(g, color = "blue", size = 10, name = LETTERS[1:10])# use splicing if suplying a listx <- list(color = "red", name = LETTERS[1:10])set_vertex_attrs(g, !!!x)# to set an attribute named "index" use `:=`set_vertex_attrs(g, color = "blue", index := 10, name = LETTERS[1:10])Various vertex shapes when plotting igraph graphs
Description
Starting from version 0.5.1 igraph supports differentvertex shapes when plotting graphs.
Usage
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())Arguments
shape | Character scalar, name of a vertex shape. If it is |
coords,el,params,end,v | See parameters of the clipping/plottingfunctions below. |
clip | An R function object, the clipping function. |
plot | An R function object, the plotting function. |
parameters | Named list, additional plot/vertex/edgeparameters. The element named define the new parameters, and theelements themselves define their default values.Vertex parameters should have a prefix‘ |
Details
In igraph a vertex shape is defined by two functions: 1) providesinformation about the size of the shape for clipping the edges and 2)plots the shape if requested. These functions are called “shapefunctions” in the rest of this manual page. The first one is theclipping function and the second is the plotting function.
The clipping function has the following arguments:
- coords
A matrix with four columns, it contains the coordinates of the verticesfor the edge list supplied in the
elargument.- el
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.- params
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").- end
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 theeledge list,“to” selects the second column, “both” selects both.
The clipping function should return a matrixwith the same number of rows as theel arguments.Ifend isboth then the matrix must have fourcolumns, otherwise two. The matrix contains the modified coordinates,with the clipping applied.
The plotting function has the following arguments:
- coords
The coordinates of the vertices, a matrix with two columns.
- v
The ids of the vertices to plot. It should match the number of rows in the
coordsargument.- params
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 installedvertex shapes, by calling it without arguments, or setting theshape argument toNULL. If a shape name is given, thenthe clipping and plotting functions of that shape are returned in anamed list.
add_shape() can be used to add new vertex shapes toigraph. For this one must give the clipping and plotting functions ofthe new shape. It is also possible to list the plot/vertex/edgeparameters, in theparameters argument, that the clippingand/or plotting functions can make use of. An example would be ageneric regular polygon shape, which can have a parameter for thenumber of sides.
shape_noclip() is a very simple clipping function that theuser can use in their own shape definitions. It does no clipping, theedges will be drawn exactly until the listed vertex positioncoordinates.
shape_noplot() is a very simple (and probably not veryuseful) plotting function, that does not plot anything.
Value
shapes() returns a character vector if theshape argument isNULL. It returns a named list withentries named ‘clip’ and ‘plot’, both of them Rfunctions.
add_shape() returnsTRUE, invisibly.
shape_noclip() returns the appropriate columns of itscoords argument.
Examples
# all vertex shapes, minus "raster", that might not be availableshapes <- 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 clippingadd_shape("nil")plot(g, vertex.shape = "nil")################################################################## triangle vertex shapemytriangle <- 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 <- 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 circleadd_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 raysmystar <- 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 <- 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 anywayadd_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)))Shortest (directed or undirected) paths between vertices
Description
shortest.paths() was renamed todistances() to create a moreconsistent API.
Usage
shortest.paths( graph, v = V(graph), to = V(graph), mode = c("all", "out", "in"), weights = NULL, algorithm = c("automatic", "unweighted", "dijkstra", "bellman-ford", "johnson"))Arguments
graph | The graph to work on. |
v | Numeric vector, the vertices from which the shortest paths will becalculated. |
to | Numeric vector, the vertices to which the shortest paths will becalculated. By default it includes all vertices. Note that for |
mode | Character constant, gives whether the shortest paths to or fromthe given vertices should be calculated for directed graphs. If |
weights | Possibly a numeric vector giving edge weights. If this is |
algorithm | Which algorithm to use for the calculation. By defaultigraph tries to select the fastest suitable algorithm. If there are noweights, then an unweighted breadth-first search is used, otherwise if allweights are positive, then Dijkstra's algorithm is used. If there arenegative weights and we do the calculation for more than 100 sources, thenJohnson's algorithm is used. Otherwise the Bellman-Ford algorithm is used.You can override igraph's choice by explicitly giving this parameter. Notethat 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 beused, regardless of this argument. |
Functions to deal with the result of network community detection
Description
showtrace() was renamed toshow_trace() to create a moreconsistent API.
Usage
showtrace(communities)Similarity measures of two vertices
Description
These functions calculates similarity scores for vertices based on theirconnection patterns.
Usage
similarity( graph, vids = V(graph), mode = c("all", "out", "in", "total"), loops = FALSE, method = c("jaccard", "dice", "invlogweighted"))Arguments
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 neighborsets. |
method | The method to use. |
Details
The Jaccard similarity coefficient of two vertices is the number of commonneighbors divided by the number of vertices that are neighbors of at leastone of the two vertices being considered. Thejaccard methodcalculates the pairwise Jaccard similarities for some (or all) of thevertices.
The Dice similarity coefficient of two vertices is twice the number ofcommon neighbors divided by the sum of the degrees of the vertices.Methofdice calculates the pairwise Dice similarities for some(or all) of the vertices.
The inverse log-weighted similarity of two vertices is the number of theircommon neighbors, weighted by the inverse logarithm of their degrees. It isbased on the assumption that two vertices should be considered more similarif they share a low-degree common neighbor, since high-degree commonneighbors are more likely to appear even by pure chance. Isolated verticeswill have zero similarity to any other vertex. Self-similarities are notcalculated. See the following paper for more details: Lada A. Adamic andEytan Adar: Friends and neighbors on the Web. Social Networks,25(3):211-230, 2003.
Value
Alength(vids) bylength(vids) numeric matrixcontaining the similarity scores. This argument is ignored by theinvlogweighted method.
Related documentation in the C library
similarity_jaccard(),similarity_dice(),similarity_inverse_log_weighted().
Author(s)
Tamas Nepuszntamas@gmail.com and Gabor Csardicsardi.gabor@gmail.com for the manual page.
References
Lada A. Adamic and Eytan Adar: Friends and neighbors on the Web.Social Networks, 25(3):211-230, 2003.
See Also
Other cocitation:cocitation()
Examples
g <- make_ring(5)similarity(g, method = "dice")similarity(g, method = "jaccard")Similarity measures of two vertices (Dice)
Description
Please usesimilarity() withmethod = "dice" instead.
Usage
similarity.dice( graph, vids = V(graph), mode = c("all", "out", "in", "total"), loops = FALSE)Arguments
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 neighborsets. |
Similarity measures of two vertices (inverse log-weighted)
Description
Please usesimilarity() withmethod = "invlogweighted" instead.
Usage
similarity.invlogweighted( graph, vids = V(graph), mode = c("all", "out", "in", "total"))Arguments
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: ‘ |
Similarity measures of two vertices (Jaccard)
Description
Please usesimilarity() withmethod = "jaccard" instead.
Usage
similarity.jaccard( graph, vids = V(graph), mode = c("all", "out", "in", "total"), loops = FALSE)Arguments
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 neighborsets. |
Finds all simple cycles in a graph.
Description
This function lists all simple cycles in a graph within a range of cyclelengths. A cycle is called simple if it has no repeated vertices.
Multi-edges and self-loops are taken into account. Note that typical graphshave exponentially many cycles and the presence of multi-edges exacerbatesthis combinatorial explosion.
Usage
simple_cycles( graph, mode = c("out", "in", "all", "total"), min = NULL, max = NULL)Arguments
graph | The input graph. |
mode | Character constant specifying how to handle directed graphs. |
min | Lower limit on cycle lengths to consider. |
max | Upper limit on cycle lengths to consider. |
Value
A named list, with two entries:
vertices | The list of cycles in terms of their vertices. |
edges | The list of cycles in terms of their edges. |
Related documentation in the C library
See Also
Graph cyclesfeedback_arc_set(),feedback_vertex_set(),find_cycle(),girth(),has_eulerian_path(),is_acyclic(),is_dag()
Examples
g <- graph_from_literal(A -+ B -+ C -+ A -+ D -+ E +- F -+ A, E -+ E, A -+ F, simplify = FALSE)simple_cycles(g)simple_cycles(g, mode = "all") # ignore edge directionssimple_cycles(g, mode = "all", min = 2, max = 3) # limit cycle lengthsConstructor modifier to drop multiple and loop edges
Description
Constructor modifier to drop multiple and loop edges
Usage
simplified()See Also
Constructor modifiers (and related functions)make_(),sample_(),with_edge_(),with_graph_(),with_vertex_(),without_attr(),without_loops(),without_multiples()
Examples
sample_(pa(10, m = 3, algorithm = "bag"))sample_(pa(10, m = 3, algorithm = "bag"), simplified())Simple graphs
Description
Simple graphs are graphs which do not contain loop and multiple edges.
Usage
simplify( graph, remove.multiple = TRUE, remove.loops = TRUE, edge.attr.comb = igraph_opt("edge.attr.comb"))is_simple(graph)simplify_and_colorize(graph)Arguments
graph | The graph to work on. |
remove.multiple | Logical, whether the multiple edges are to beremoved. |
remove.loops | Logical, whether the loop edges are to be removed. |
edge.attr.comb | Specifies what to do with edge attributes, if |
Details
A loop edge is an edge for which the two endpoints are the samevertex. Two edges are multiple edges if they have exactly the same twoendpoints (for directed graphs order does matter). A graph is simple isit 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. Ifbothremove.loops andremove.multiple areTRUE thefunction returns a simple graph.
simplify_and_colorize() constructs a new, simple graph from a graph andalso sets acolor attribute on both the vertices and the edges.The colors of the vertices represent the number of self-loops that wereoriginally incident on them, while the colors of the edges represent themultiplicities of the same edges in the original graph. This allows one totake into account the edge multiplicities and the number of loop edges inthe VF2 isomorphism algorithm. Other graph, vertex and edge attributes fromthe original graph are discarded as the primary purpose of this function isto facilitate the usage of multigraphs with the VF2 algorithm.
Value
a new graph object with the edges deleted.
Related documentation in the C library
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
which_loop(),which_multiple() andcount_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()
Examples
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))Eigenvalues and eigenvectors of the adjacency matrix of a graph
Description
Calculate selected eigenvalues and eigenvectors of a (supposedly sparse)graph.
Usage
spectrum( graph, algorithm = c("arpack", "auto", "lapack", "comp_auto", "comp_lapack", "comp_arpack"), which = list(), options = arpack_defaults())Arguments
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 tocalculate. By default the leading (i.e. largest magnitude) eigenvalue andthe corresponding eigenvector is calculated. |
options | Options for the ARPACK solver. See |
Details
Thewhich argument is a list and it specifies which eigenvalues andcorresponding eigenvectors to calculate: There are eight options:
Eigenvalues with the largest magnitude. Set
postoLM, andhowmanyto the number of eigenvalues you want.Eigenvalues with the smallest magnitude. Set
postoSMandhowmanyto the number of eigenvalues you want.Largesteigenvalues. Set
postoLAandhowmanyto the number ofeigenvalues you want.Smallest eigenvalues. Set
postoSAandhowmanyto the number of eigenvalues you want.Eigenvalues from both ends of the spectrum. Set
postoBEandhowmanyto the number of eigenvalues you want. Ifhowmanyisodd, 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.
Alleigenvalues. This is not implemented yet. The standard
eigenfunctiondoes a better job at this, anyway.
Note that ARPACK might be unstable for graphs with multiple components, e.g.graphs with isolate vertices.
Value
Depends on the algorithm used.
Forarpack a list with three entries is returned:
- options
See the return value for
arpack()for a complete description.- values
Numeric vector, the eigenvalues.
- vectors
Numeric matrix, with the eigenvectors as columns.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
as_adjacency_matrix() to create a (sparse) adjacency matrix.
Centrality measuresalpha_centrality(),authority_score(),betweenness(),closeness(),diversity(),eigen_centrality(),harmonic_centrality(),hits_scores(),page_rank(),power_centrality(),strength(),subgraph_centrality()
Examples
## Small example graph, leading eigenvector by defaultkite <- make_graph("Krackhardt_kite")spectrum(kite)[c("values", "vectors")]## Double checkeigen(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 eigenvaluesspectrum(kite, which = list(pos = "SM", howmany = 2))$valuesFinding communities in graphs based on statistical meachanics
Description
spinglass.community() was renamed tocluster_spinglass() to create a moreconsistent API.
Usage
spinglass.community( 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)Arguments
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 agiven vertex without calculating all communities. Note that if this argumentis present then some other arguments are ignored. |
spins | Integer constant, the number of spins to use. This is the upperlimit for the number of communities. It is not a problem to supply a(reasonably) big number here, in which case some spin states will beunpopulated. |
parupdate | Logical constant, whether to update the spins of thevertices in parallel (synchronously) or not. This argument is ignored if thesecond form of the function is used (i.e. the ‘ |
start.temp | Real constant, the start temperature. This argument isignored if the second form of the function is used (i.e. the‘ |
stop.temp | Real constant, the stop temperature. The simulationterminates if the temperature lowers below this level. This argument isignored if the second form of the function is used (i.e. the‘ |
cool.fact | Cooling factor for the simulated annealing. This argumentis ignored if the second form of the function is used (i.e. the‘ |
update.rule | Character constant giving the ‘null-model’ of thesimulation. Possible values: “simple” and “config”.“simple” uses a random graph with the same number of edges as thebaseline probability and “config” uses a random graph with the samevertex degrees as the input graph. |
gamma | Real constant, the gamma argument of the algorithm. Thisspecifies the balance between the importance of present and non-presentedges in a community. Roughly, a comunity is a set of vertices having manyedges inside the community and few edges outside the community. The default1.0 value makes existing and non-existing links equally important. Smallervalues make the existing links, greater values the missing links moreimportant. |
implementation | Character scalar. Currently igraph contains twoimplementations for the Spin-glass community finding algorithm. The fasteroriginal implementation is the default. The other implementation, that takesinto account negative weights, can be chosen by supplying ‘neg’ here. |
gamma.minus | Real constant, the gamma.minus parameter of thealgorithm. This specifies the balance between the importance of present andnon-present negative weighted edges in a community. Smaller values ofgamma.minus, leads to communities with lesser negative intra-connectivity.If this argument is set to zero, the algorithm reduces to a graph coloringalgorithm, using the number of spins as the number of colors. This argumentis ignored if the ‘orig’ implementation is chosen. |
Split-join distance of two community structures
Description
The split-join distance between partitions A and B is the sum of theprojection distance of A from B and the projection distance of B fromA. The projection distance is an asymmetric measure and it is defined asfollows:
Usage
split_join_distance(comm1, comm2)Arguments
comm1 | The first community structure. |
comm2 | The second community structure. |
Details
First, each set in partition A is evaluated against all sets inpartition B. For each set in partition A, the best matching set inpartition B is found and the overlap size is calculated. (Matching isquantified by the size of the overlap between the two sets). Then, themaximal overlap sizes for each set in A are summed together andsubtracted from the number of elements in A.
The split-join distance will be returned as two numbers, the first isthe projection distance of the first partition from thesecond, while the second number is the projection distance of the secondpartition from the first. This makes it easier to detect whether apartition is a subpartition of the other, since in this case, thecorresponding distance will be zero.
Value
Two integer numbers, see details below.
References
van Dongen S: Performance criteria for graph clustering and Markovcluster experiments. Technical Report INS-R0012, National ResearchInstitute for Mathematics and Computer Science in the Netherlands,Amsterdam, May 2000.
See Also
Community detectionas_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 of a graph
Description
stCuts() was renamed tost_cuts() to create a moreconsistent API.
Usage
stCuts(graph, source, target)Arguments
graph | The input graph. It must be directed. |
source | The source vertex. |
target | The target vertex. |
List all minimum \((s,t)\)-cuts of a graph
Description
stMincuts() was renamed tost_min_cuts() to create a moreconsistent API.
Usage
stMincuts(graph, source, target, capacity = NULL)Arguments
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 |
List all (s,t)-cuts of a graph
Description
List all (s,t)-cuts in a directed graph.
Usage
st_cuts(graph, source, target)Arguments
graph | The input graph. It must be directed. |
source | The source vertex. |
target | The target vertex. |
Details
Given aG directed graph and two, different and non-ajacent vertices,s andt, an(s,t)-cut is a set of edges, such that afterremoving these edges fromG there is no directed path froms tot.
Value
A list with entries:
- cuts
A list of numeric vectors containing edge ids.Each vector is an
(s,t)-cut.- 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
G=(V,E),the vertex setXand its complementerV-X,generates the cut that contains exactly the edges that go fromXtoV-X.
Related documentation in the C library
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
JS Provan and DR Shier: A Paradigm for listing (s,t)-cuts ingraphs,Algorithmica 15, 351–372, 1996.
See Also
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()
Examples
# A very simple graphg <- graph_from_literal(a -+ b -+ c -+ d -+ e)st_cuts(g, source = "a", target = "e")# A somewhat more difficult graphg2 <- graph_from_literal( s --+ a:b, a:b --+ t, a --+ 1:2:3, 1:2:3 --+ b)st_cuts(g2, source = "s", target = "t")List all minimum(s,t)-cuts of a graph
Description
Listing all minimum(s,t)-cuts of a directed graph, for givensandt.
Usage
st_min_cuts(graph, source, target, capacity = NULL)Arguments
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 |
Details
Given aG directed graph and two, different and non-ajacent vertices,s andt, an(s,t)-cut is a set of edges, such that afterremoving these edges fromG there is no directed path froms tot.
The size of an(s,t)-cut is defined as the sum of the capacities (orweights) in the cut. For unweighted (=equally weighted) graphs, this issimply the number of edges.
An(s,t)-cut is minimum if it is of the smallest possible size.
Value
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
(s,t)-cut.- 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
G=(V,E),the vertex setXand its complementerV-X,generates the cut that contains exactly the edges that go fromXtoV-X.
Related documentation in the C library
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
JS Provan and DR Shier: A Paradigm for listing (s,t)-cuts ingraphs,Algorithmica 15, 351–372, 1996.
See Also
Other flow:dominator_tree(),edge_connectivity(),is_min_separator(),is_separator(),max_flow(),min_cut(),min_separators(),min_st_separators(),st_cuts(),vertex_connectivity()
Examples
# A difficult graph, from the Provan-Shier paperg <- 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")Random graphs from vertex fitness scores
Description
static.fitness.game() was renamed tosample_fitness() to create a moreconsistent API.
Usage
static.fitness.game( no.of.edges, fitness.out, fitness.in = NULL, loops = FALSE, multiple = FALSE)Arguments
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 thegraph. |
Scale-free random graphs, from vertex fitness scores
Description
static.power.law.game() was renamed tosample_fitness_pl() to create a moreconsistent API.
Usage
static.power.law.game( no.of.nodes, no.of.edges, exponent.out, exponent.in = -1, loops = FALSE, multiple = FALSE, finite.size.correction = TRUE)Arguments
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 degreedistribution. For directed graphs, this specifies the exponent of theout-degree distribution. It must be greater than or equal to 2. If you pass |
exponent.in | Numeric scalar. If negative, the generated graph will beundirected. If greater than or equal to 2, this argument specifies theexponent of the in-degree distribution. If non-negative but less than 2, anerror will be generated. |
loops | Logical scalar, whether to allow loop edges in the generatedgraph. |
multiple | Logical scalar, whether to allow multiple edges in thegenerated graph. |
finite.size.correction | Logical scalar, whether to use the proposedfinite size correction of Cho et al., see references below. |
Stochastic matrix of a graph
Description
Retrieves the stochastic matrix of a graph of classigraph.
Usage
stochastic_matrix( graph, column.wise = FALSE, sparse = igraph_opt("sparsematrices"))Arguments
graph | The input graph. Must be of class |
column.wise | If |
sparse | Logical scalar, whether to return a sparse matrix. The |
Details
LetM be ann \times n adjacency matrix with realnon-negative entries. Let us defineD = \textrm{diag}(\sum_{i}M_{1i},\dots, \sum_{i}M_{ni})
The (row) stochastic matrix is defined as
W = D^{-1}M,
where it is assumed thatD is non-singular. Column stochasticmatrices are defined in a symmetric way.
Value
A regular matrix or a matrix of classMatrix if asparse argument wasTRUE.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
Examples
library(Matrix)## g is a large sparse graphg <- 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 memoryclass(W)## may not be exactly 1, due to numerical errorsmax(abs(rowSums(W)) - 1)Strength or weighted vertex degree
Description
Summing up the edge weights of the adjacent edges for each vertex.
Usage
strength( graph, vids = V(graph), mode = c("all", "out", "in", "total"), loops = TRUE, weights = NULL)Arguments
graph | The input graph. |
vids | The vertices for which the strength will be calculated. |
mode | Character string, “out” for out-degree, “in” forin-degree or “all” for the sum of the two. For undirected graphs thisargument is ignored. |
loops | Logical; whether the loop edges are also counted. |
weights | Weight vector. If the graph has a |
Value
A numeric vector giving the strength of the vertices.
Related documentation in the C library
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
Alain Barrat, Marc Barthelemy, Romualdo Pastor-Satorras,Alessandro Vespignani: The architecture of complex weighted networks, Proc.Natl. Acad. Sci. USA 101, 3747 (2004)
See Also
degree() for the unweighted version.
Centrality measuresalpha_centrality(),authority_score(),betweenness(),closeness(),diversity(),eigen_centrality(),harmonic_centrality(),hits_scores(),page_rank(),power_centrality(),spectrum(),subgraph_centrality()
Examples
g <- make_star(10)E(g)$weight <- seq(ecount(g))strength(g)strength(g, mode = "out")strength(g, mode = "in")# No weightsg <- make_ring(10)strength(g)In- or out- component of a vertex
Description
Finds all vertices reachable from a given vertex, or the opposite: allvertices from which a given vertex is reachable via a directed path.
Usage
subcomponent(graph, v, mode = c("all", "out", "in"))Arguments
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 |
Details
A breadth-first search is conducted starting from vertexv.
Value
Numeric vector, the ids of the vertices in the same component asv.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
Other structural.properties:bfs(),component_distribution(),connect(),constraint(),coreness(),degree(),dfs(),distance_table(),edge_density(),feedback_arc_set(),feedback_vertex_set(),girth(),is_acyclic(),is_dag(),is_matching(),k_shortest_paths(),knn(),reciprocity(),subgraph(),topo_sort(),transitivity(),unfold_tree(),which_multiple(),which_mutual()
Examples
g <- sample_gnp(100, 1 / 200)subcomponent(g, 1, "in")subcomponent(g, 1, "out")subcomponent(g, 1, "all")Subgraph of a graph
Description
subgraph() creates a subgraph of a graph, containing only the specifiedvertices and all the edges among them.
Usage
subgraph(graph, vids)induced_subgraph( graph, vids, impl = c("auto", "copy_and_delete", "create_from_scratch"))subgraph_from_edges(graph, eids, delete.vertices = TRUE)Arguments
graph | The original graph. |
vids | Numeric vector, the vertices of the original graph which willform the subgraph. |
impl | Character scalar, to choose between two implementation of thesubgraph 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 donot have any adjacent edges in |
Details
induced_subgraph() calculates the induced subgraph of a set of verticesin a graph. This means that exactly the specified vertices and all the edgesbetween them will be kept in the result graph.
subgraph_from_edges() calculates the subgraph of a graph. For this functionone can specify the vertices and edges to keep. This function will berenamed tosubgraph() in the next major version of igraph.
Thesubgraph() function currently does the same asinduced_subgraph()(assuming ‘auto’ as theimpl argument), but this behaviouris deprecated. In the next major version,subgraph() will overtake thefunctionality ofsubgraph_from_edges().
Value
A new graph object.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
Other structural.properties:bfs(),component_distribution(),connect(),constraint(),coreness(),degree(),dfs(),distance_table(),edge_density(),feedback_arc_set(),feedback_vertex_set(),girth(),is_acyclic(),is_dag(),is_matching(),k_shortest_paths(),knn(),reciprocity(),subcomponent(),topo_sort(),transitivity(),unfold_tree(),which_multiple(),which_mutual()
Examples
g <- make_ring(10)g2 <- induced_subgraph(g, 1:7)g3 <- subgraph_from_edges(g, 1:5)Find subgraph centrality scores of network positions
Description
subgraph.centrality() was renamed tosubgraph_centrality() to create a moreconsistent API.
Usage
subgraph.centrality(graph, diag = FALSE)Arguments
graph | The input graph. It will be treated as undirected. |
diag | Boolean scalar, whether to include the diagonal of the adjacencymatrix in the analysis. Giving |
Subgraph of a graph
Description
subgraph.edges() was renamed tosubgraph_from_edges() to create a moreconsistent API.
Usage
subgraph.edges(graph, eids, delete.vertices = TRUE)Arguments
graph | The original graph. |
eids | The edge ids of the edges that will be kept in the result graph. |
delete.vertices | Logical scalar, whether to remove vertices that donot have any adjacent edges in |
Find subgraph centrality scores of network positions
Description
Subgraph centrality of a vertex measures the number of subgraphs a vertexparticipates in, weighting them according to their size.
Usage
subgraph_centrality(graph, diag = FALSE)Arguments
graph | The input graph. It will be treated as undirected. |
diag | Boolean scalar, whether to include the diagonal of the adjacencymatrix in the analysis. Giving |
Details
The subgraph centrality of a vertex is defined as the number of closed walksoriginating at the vertex, where longer walks are downweighted by thefactorial of their length.
Currently the calculation is performed by explicitly calculating alleigenvalues and eigenvectors of the adjacency matrix of the graph. Thiseffectively means that the measure can only be calculated for small graphs.
Value
A numeric vector, the subgraph centrality scores of the vertices.
Author(s)
Gabor Csardicsardi.gabor@gmail.com based on the Matlabcode by Ernesto Estrada
References
Ernesto Estrada, Juan A. Rodriguez-Velazquez: Subgraphcentrality in Complex Networks.Physical Review E 71, 056103 (2005).
See Also
eigen_centrality(),page_rank()
Centrality measuresalpha_centrality(),authority_score(),betweenness(),closeness(),diversity(),eigen_centrality(),harmonic_centrality(),hits_scores(),page_rank(),power_centrality(),spectrum(),strength()
Examples
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
Description
Decide if a graph is subgraph isomorphic to another one
Usage
subgraph_isomorphic(pattern, target, method = c("auto", "lad", "vf2"), ...)is_subgraph_isomorphic_to( pattern, target, method = c("auto", "lad", "vf2"), ...)Arguments
pattern | The smaller graph, it might be directed orundirected. Undirected graphs are treated as directed graphs withmutual edges. |
target | The bigger graph, it might be directed orundirected. Undirected graphs are treated as directed graphs withmutual edges. |
method | The method to use. Possible values: ‘auto’,‘lad’, ‘vf2’. See their details below. |
... | Additional arguments, passed to the various methods. |
Value
Logical scalar,TRUE if thepattern isisomorphic to a (possibly induced) subgraph oftarget.
‘auto’ method
This method currently selects ‘lad’, always, as it seemsto be superior on most graphs.
‘lad’ method
This is the LAD algorithm by Solnon, see the reference below. It hasthe following extra arguments:
- domains
If not
NULL, then it specifies matching restrictions.It must be a list oftargetvertex sets, given as numeric vertex ids or symbolic vertex names.The length of the list must bevcount(pattern)and for each vertex inpatternit gives the allowed matching vertices intarget.Defaults toNULL.- induced
Logical scalar, whether to search for an induced subgraph.It is
FALSEby default.- time.limit
The processor time limit for the computation, in seconds.It defaults to
Inf, which means no limit.
‘vf2’ method
This method uses the VF2 algorithm by Cordella, Foggia et al., seereferences below. It supports vertex and edge colors and have thefollowing extra arguments:
- vertex.color1, vertex.color2
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
NULLfor both of these arguments.See also examples below.- edge.color1, edge.color2
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
NULLfor both of these arguments.
References
LP Cordella, P Foggia, C Sansone, and M Vento: An improved algorithmfor matching large graphs,Proc. of the 3rd IAPR TC-15 Workshopon Graphbased Representations in Pattern Recognition, 149–159, 2001.
C. Solnon: AllDifferent-based Filtering for Subgraph Isomorphism,Artificial Intelligence 174(12-13):850–864, 2010.
See Also
Other graph isomorphism:canonical_permutation(),count_isomorphisms(),count_subgraph_isomorphisms(),graph_from_isomorphism_class(),isomorphic(),isomorphism_class(),isomorphisms(),subgraph_isomorphisms()
Examples
# A LAD examplepattern <- 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 examplepattern <- 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
Description
All isomorphic mappings between a graph and subgraphs of another graph
Usage
subgraph_isomorphisms(pattern, target, method = c("lad", "vf2"), ...)Arguments
pattern | The smaller graph, it might be directed orundirected. Undirected graphs are treated as directed graphs withmutual edges. |
target | The bigger graph, it might be directed orundirected. Undirected graphs are treated as directed graphs withmutual edges. |
method | The method to use. Possible values: ‘auto’,‘lad’, ‘vf2’. See their details below. |
... | Additional arguments, passed to the various methods. |
Value
A list of vertex sequences, corresponding to allmappings from the first graph to the second.
‘lad’ method
This is the LAD algorithm by Solnon, see the reference below. It hasthe following extra arguments:
- domains
If not
NULL, then it specifies matching restrictions.It must be a list oftargetvertex sets, given as numeric vertex ids or symbolic vertex names.The length of the list must bevcount(pattern)and for each vertex inpatternit gives the allowed matching vertices intarget.Defaults toNULL.- induced
Logical scalar, whether to search for an induced subgraph.It is
FALSEby default.- time.limit
The processor time limit for the computation, in seconds.It defaults to
Inf, which means no limit.
‘vf2’ method
This method uses the VF2 algorithm by Cordella, Foggia et al., seereferences below. It supports vertex and edge colors and have thefollowing extra arguments:
- vertex.color1, vertex.color2
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
NULLfor both of these arguments.See also examples below.- edge.color1, edge.color2
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
NULLfor both of these arguments.
See Also
Other graph isomorphism:canonical_permutation(),count_isomorphisms(),count_subgraph_isomorphisms(),graph_from_isomorphism_class(),isomorphic(),isomorphism_class(),isomorphisms(),subgraph_isomorphic()
Tails of the edge(s) in a graph
Description
For undirected graphs, head and tail is not defined. In this casetail_of() returns vertices incident to the supplied edges, andhead_of() returns the other end(s) of the edge(s).
Usage
tail_of(graph, es)Arguments
graph | The input graph. |
es | The edges to query. |
Value
A vertex sequence with the tail(s) of the edge(s).
See Also
Other structural queries:[.igraph(),[[.igraph(),adjacent_vertices(),are_adjacent(),ends(),get_edge_ids(),gorder(),gsize(),head_of(),incident(),incident_edges(),is_directed(),neighbors()
SIR model on graphs
Description
Run simulations for an SIR (susceptible-infected-recovered) model, on agraph
Usage
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)Arguments
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 thequantiles to calculate. |
graph | The graph to run the model on. If directed, then edgedirections are ignored and a warning is given. |
beta | Non-negative scalar. The rate of infection of an individual thatis susceptible and has a single infected neighbor. The infection rate of asusceptible individual with n infected neighbors is n times beta. Formallythis is the rate parameter of an exponential distribution. |
gamma | Positive scalar. The rate of recovery of an infectedindividual. Formally, this is the rate parameter of an exponentialdistribution. |
no.sim | Integer scalar, the number simulation runs to perform. |
Details
The SIR model is a simple model from epidemiology. The individuals of thepopulation might be in three states: susceptible, infected and recovered.Recovered people are assumed to be immune to the disease. Susceptiblesbecome infected with a rate that depends on their number of infectedneighbors. Infected people become recovered with a constant rate.
The functionsir() simulates the model. This function runs multiplesimulations, all starting with a single uniformly randomly chosen infectedindividual. A simulation is stopped when no infected individuals are left.
Functiontime_bins() bins the simulation steps, using theFreedman-Diaconis heuristics to determine the bin width.
Functionmedian andquantile calculate the median andquantiles of the results, respectively, in bins calculated withtime_bins().
Value
Forsir() 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 allnumeric vectors, with equal length:
- times
The times of the events.
- NS
The number of susceptibles in the population, over time.
- NI
The number of infected individuals in the population, over time.
- NR
The number of recovered individuals in the population, over time.
Functiontime_bins() returns a numeric vector, the middle or theboundaries of the time bins, depending on themiddle argument.
median returns a list of three named numeric vectors,NS,NI andNR. The names within the vectors are created from thetime bins.
quantile returns the same vector asmedian (but only one, theone requested) if only one quantile is requested. If multiple quantiles arerequested, then a list of these vectors is returned, one for each quantile.
Related documentation in the C library
Author(s)
Gabor Csardicsardi.gabor@gmail.com. Eric Kolaczyk(https://kolaczyk.github.io/) wrote the initial version in R.
References
Bailey, Norman T. J. (1975). The mathematical theory ofinfectious diseases and its applications (2nd ed.). London: Griffin.
See Also
plot.sir() to conveniently plot the results
Processes on graphsplot.sir()
Examples
g <- sample_gnm(100, 100)sm <- sir(g, beta = 5, gamma = 1)plot(sm)tkigraph
Description
Find tkigraph athttps://github.com/igraph/tkigraph.
Interactive plotting of graphs
Description
tkplot() and its companion functions serve as an interactive graphdrawing facility. Not all parameters of the plot can be changedinteractively right now though, e.g. the colors of vertices, edges, and alsoothers have to be pre-defined.
Usage
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)Arguments
graph | The |
canvas.width,canvas.height | The size of the tkplot drawing area. |
... | Additional plotting parameters. Seeigraph.plotting forthe 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 thevertices, in absolute coordinates. |
degree | The degree to rotate the plot. |
rad | The degree to rotate the plot, in radian. |
Details
tkplot() is an interactive graph drawing facility. It is not very welldeveloped at this stage, but it should be still useful.
It's handling should be quite straightforward most of the time, here aresome remarks and hints.
There are different popup menus, activated by the right mouse button, forvertices and edges. Both operate on the current selection if the vertex/edgeunder the cursor is part of the selection and operate on the vertex/edgeunder 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 thecontrol keywhile clicking on it with the left mouse button. Doing this again deselectthe vertex/edge.
Selections can be made also from the "Select" menu. The "Select somevertices" dialog allows to give an expression for the vertices to beselected: this can be a list of numeric R expessions separated by commas,like1,2:10,12,14,15 for example. Similarly in the "Select someedges" dialog two such lists can be given and all edges connecting a vertexin 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 beused.
Thetkplot() command creates a new Tk window with the graphicalrepresentation ofgraph. The command returns an integer number, thetkplot id. The other commands utilize this id to be able to query ormanipulate the plot.
tk_close() closes the Tk plot with idtkp.id.
tk_off() closes all Tk plots.
tk_fit() fits the plot to the given rectangle(width andheight), if some of these areNULL theactual physical width od height of the plot window is used.
tk_reshape() applies a new layout to the plot, its optionalparameters will be collected to a list analogous tolayout.par.
tk_postscript() creates a dialog window for saving the plotin postscript format.
tk_canvas() returns the Tk canvas object that belongs to a graphplot. 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-columnmatrix specifies the new positions, with each row corresponding to a singlevertex.
tk_center() shifts the figure to the center of its plot window.
tk_rotate() rotates the figure, its parameter can be given eitherin degrees or in radians.
tkplot.center tkplot.rotate
Value
tkplot() returns an integer, the id of the plot, this can beused to manipulate it from the command line.
tk_canvas() returnstkwin object, the Tk canvas.
tk_coords() returns a matrix with the coordinates.
tk_close(),tk_off(),tk_fit(),tk_reshape(),tk_postscript(),tk_center()andtk_rotate() returnNULL invisibly.
Examples
g <- make_ring(10)tkplot(g)## Saving a tkplot() to a file programmaticallyg <- 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 labelg <- make_ring(10)id <- tkplot(make_ring(10), canvas.width=450, canvas.height=500)canvas <- tk_canvas(id)padding <- 20coords <- 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"))
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
Interactive plotting of graphs
Description
tkplot.canvas() was renamed totk_canvas() to create a moreconsistent API.
Usage
tkplot.canvas(tkp.id)Arguments
tkp.id | The id of the tkplot window to close/reshape/etc. |
Interactive plotting of graphs
Description
tkplot.center() was renamed totk_center() to create a moreconsistent API.
Usage
tkplot.center(tkp.id)Arguments
tkp.id | The id of the tkplot window to close/reshape/etc. |
Interactive plotting of graphs
Description
tkplot.close() was renamed totk_close() to create a moreconsistent API.
Usage
tkplot.close(tkp.id, window.close = TRUE)Arguments
tkp.id | The id of the tkplot window to close/reshape/etc. |
window.close | Leave this on the default value. |
Interactive plotting of graphs
Description
tkplot.export.postscript() was renamed totk_postscript() to create a moreconsistent API.
Usage
tkplot.export.postscript(tkp.id)Arguments
tkp.id | The id of the tkplot window to close/reshape/etc. |
Interactive plotting of graphs
Description
tkplot.fit.to.screen() was renamed totk_fit() to create a moreconsistent API.
Usage
tkplot.fit.to.screen(tkp.id, width = NULL, height = NULL)Arguments
tkp.id | The id of the tkplot window to close/reshape/etc. |
width | The width of the rectangle for generating new coordinates. |
height | The height of the rectangle for generating new coordinates. |
Interactive plotting of graphs
Description
tkplot.getcoords() was renamed totk_coords() to create a moreconsistent API.
Usage
tkplot.getcoords(tkp.id, norm = FALSE)Arguments
tkp.id | The id of the tkplot window to close/reshape/etc. |
norm | Logical, should we norm the coordinates. |
Interactive plotting of graphs
Description
tkplot.off() was renamed totk_off() to create a moreconsistent API.
Usage
tkplot.off()Interactive plotting of graphs
Description
tkplot.reshape() was renamed totk_reshape() to create a moreconsistent API.
Usage
tkplot.reshape(tkp.id, newlayout, ..., params)Arguments
tkp.id | The id of the tkplot window to close/reshape/etc. |
newlayout | The new layout, see the |
... | Additional plotting parameters. Seeigraph.plotting forthe complete list. |
params | Extra parameters in a list, to pass to the layout function. |
Interactive plotting of graphs
Description
tkplot.rotate() was renamed totk_rotate() to create a moreconsistent API.
Usage
tkplot.rotate(tkp.id, degree = NULL, rad = NULL)Arguments
tkp.id | The id of the tkplot window to close/reshape/etc. |
degree | The degree to rotate the plot. |
rad | The degree to rotate the plot, in radian. |
Interactive plotting of graphs
Description
tkplot.setcoords() was renamed totk_set_coords() to create a moreconsistent API.
Usage
tkplot.setcoords(tkp.id, coords)Arguments
tkp.id | The id of the tkplot window to close/reshape/etc. |
coords | Two-column numeric matrix, the new coordinates of thevertices, in absolute coordinates. |
Convert a tree graph to its Prüfer sequence
Description
to_prufer() converts a tree graph into its Prüfer sequence.
Usage
to_prufer(graph)Arguments
graph | The graph to convert to a Prüfer sequence |
Details
The Prüfer sequence of a tree graph with n labeled vertices is a sequence ofn-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 ofthe vertex that it was connected to to the sequence. Repeat until there areonly two vertices in the remaining graph.
Value
The Prüfer sequence of the graph, represented as a numeric vector ofvertex IDs in the sequence.
Related documentation in the C library
See Also
make_from_prufer() to construct a graph from itsPrüfer sequence
Other trees:is_forest(),is_tree(),make_from_prufer(),sample_spanning_tree()
Examples
g <- make_tree(13, 3)to_prufer(g)Topological sorting of vertices in a graph
Description
A topological sorting of a directed acyclic graph is a linear ordering ofits nodes where each node comes before all nodes to which it has edges.
Usage
topo_sort(graph, mode = c("out", "all", "in"))Arguments
graph | The input graph, should be directed |
mode | Specifies how to use the direction of the edges. For“ |
Details
Every DAG has at least one topological sort, and may have many. Thisfunction returns a possible topological sort among them. If the graph is notacyclic (it has at least one cycle), a partial topological sort is returnedand a warning is issued.
Value
A vertex sequence (by default, but see thereturn.vs.esoption ofigraph_options()) containing vertices intopologically sorted order.
Author(s)
Tamas Nepuszntamas@gmail.com and Gabor Csardicsardi.gabor@gmail.com for the R interface
See Also
Other structural.properties:bfs(),component_distribution(),connect(),constraint(),coreness(),degree(),dfs(),distance_table(),edge_density(),feedback_arc_set(),feedback_vertex_set(),girth(),is_acyclic(),is_dag(),is_matching(),k_shortest_paths(),knn(),reciprocity(),subcomponent(),subgraph(),transitivity(),unfold_tree(),which_multiple(),which_mutual()
Examples
g <- sample_pa(100)topo_sort(g)Topological sorting of vertices in a graph
Description
topological.sort() was renamed totopo_sort() to create a moreconsistent API.
Usage
topological.sort(graph, mode = c("out", "all", "in"))Arguments
graph | The input graph, should be directed |
mode | Specifies how to use the direction of the edges. For“ |
Transitivity of a graph
Description
Transitivity measures the probability that the adjacent vertices of a vertexare connected. This is sometimes also called the clustering coefficient.
Usage
transitivity( graph, type = c("undirected", "global", "globalundirected", "localundirected", "local", "average", "localaverage", "localaverageundirected", "barrat", "weighted"), vids = NULL, weights = NULL, isolates = c("NaN", "zero"))Arguments
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 forother transitivity measures. If it is |
isolates | Character scalar, for local versions of transitivity, itdefines how to treat vertices with degree zero and one.If it is ‘ |
Details
Note that there are essentially two classes of transitivity measures, one isa vertex-level, the other a graph level property.
There are several generalizations of transitivity to weighted graphs, herewe use the definition by A. Barrat, this is a local vertex-level quantity,its formula is
C_i^w=\frac{1}{s_i(k_i-1)}\sum_{j,h}\frac{w_{ij}+w_{ih}}{2}a_{ij}a_{ih}a_{jh}
s_i is the strength of vertexi, seestrength(),a_{ij} are elements of theadjacency matrix,k_i is the vertex degree,w_{ij}are the weights.
This formula gives back the normal not-weighted local transitivity if allthe edge weights are the same.
Thebarrat type of transitivity does not work for graphs withmultiple and/or loop edges. If you want to calculate it for a directedgraph, callas_undirected() with thecollapse mode first.
Value
For ‘global’ a single number, orNaN if thereare no connected triples in the graph.
For ‘local’ a vector of transitivity scores, one for eachvertex in ‘vids’.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
Wasserman, S., and Faust, K. (1994).Social NetworkAnalysis: Methods and Applications. Cambridge: Cambridge University Press.
Alain Barrat, Marc Barthelemy, Romualdo Pastor-Satorras, AlessandroVespignani: The architecture of complex weighted networks, Proc. Natl. Acad.Sci. USA 101, 3747 (2004)
See Also
Other structural.properties:bfs(),component_distribution(),connect(),constraint(),coreness(),degree(),dfs(),distance_table(),edge_density(),feedback_arc_set(),feedback_vertex_set(),girth(),is_acyclic(),is_dag(),is_matching(),k_shortest_paths(),knn(),reciprocity(),subcomponent(),subgraph(),topo_sort(),unfold_tree(),which_multiple(),which_mutual()
Examples
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 papergw <- graph_from_literal(A - B:C:D:E, B - C:D, C - D)E(gw)$weight <- 1E(gw)[V(gw)[name == "A"] %--% V(gw)[name == "E"]]$weight <- 5transitivity(gw, vids = "A", type = "local")transitivity(gw, vids = "A", type = "weighted")# Weighted reduces to "local" if weights are the samegw2 <- sample_gnp(1000, 10 / 1000)E(gw2)$weight <- 1t1 <- transitivity(gw2, type = "local")t2 <- transitivity(gw2, type = "weighted")all(is.na(t1) == is.na(t2))all(na.omit(t1 == t2))Triad census, subgraphs with three vertices
Description
triad.census() was renamed totriad_census() to create a moreconsistent API.
Usage
triad.census(graph)Arguments
graph | The input graph, it should be directed. An undirected graphresults a warning, and undefined results. |
Triad census, subgraphs with three vertices
Description
This function counts the different induced subgraphs of three vertices ina graph.
Usage
triad_census(graph)Arguments
graph | The input graph, it should be directed. An undirected graphresults a warning, and undefined results. |
Details
Triad census was defined by David and Leinhardt (see References below).Every triple of vertices (A, B, C) are classified into the 16 possiblestates:
- 003
A,B,C, the empty graph.
- 012
A->B, C, the graph with a single directed edge.
- 102
A<->B, C, the graph with a mutual connection between two vertices.
- 021D
A<-B->C, the out-star.
- 021U
A->B<-C, the in-star.
- 021C
A->B->C, directed line.
- 111D
A<->B<-C.
- 111U
A<->B->C.
- 030T
A->B<-C, A->C.
- 030C
A<-B<-C, A->C.
- 201
A<->B<->C.
- 120D
A<-B->C, A<->C.
- 120U
A->B<-C, A<->C.
- 120C
A->B->C, A<->C.
- 210
A->B<->C, A<->C.
- 300
A<->B<->C, A<->C, the complete graph.
This functions uses the RANDESU motif finder algorithm to find and count thesubgraphs, seemotifs().
Value
A numeric vector, the subgraph counts, in the order given in theabove description.
Related documentation in the C library
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
See also Davis, J.A. and Leinhardt, S. (1972). The Structureof Positive Interpersonal Relations in Small Groups. In J. Berger (Ed.),Sociological Theories in Progress, Volume 2, 218-251. Boston: HoughtonMifflin.
See Also
dyad_census() for classifying binary relationships,motifs() for the underlying implementation.
Examples
g <- sample_gnm(15, 45, directed = TRUE)triad_census(g)Find triangles in graphs
Description
Count how many triangles a vertex is part of, in a graph, or just list thetriangles of a graph.
Usage
triangles(graph)count_triangles(graph, vids = V(graph))Arguments
graph | The input graph. It might be directed, but edge directions areignored. |
vids | The vertices to query, all of them by default. This might be avector of numeric ids, or a character vector of symbolic vertex names fornamed graphs. |
Details
triangles() lists all triangles of a graph. For efficiency, alltriangles are returned in a single vector. The first three vertices belongto the first triangle, etc.
count_triangles() counts how many triangles a vertex is part of.
Value
Fortriangles() a numeric vector of vertex ids, the first threevertices belong to the first triangle found, etc.
Forcount_triangles() a numeric vector, the number of triangles for allvertices queried.
Related documentation in the C library
list_triangles(),adjacent_triangles().
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
Examples
## A small graphkite <- make_graph("Krackhardt_Kite")plot(kite)matrix(triangles(kite), nrow = 3)## Adjacenct trianglesatri <- count_triangles(kite)plot(kite, vertex.label = atri)## Always truesum(count_triangles(kite)) == length(triangles(kite))## Should match, local transitivity is the## number of adjacent triangles divided by the number## of adjacency triplestransitivity(kite, type = "local")count_triangles(kite) / (degree(kite) * (degree(kite) - 1) / 2)Convert a general graph into a forest
Description
unfold.tree() was renamed tounfold_tree() to create a moreconsistent API.
Usage
unfold.tree(graph, mode = c("all", "out", "in", "total"), roots)Arguments
graph | The input graph, it can be either directed or undirected. |
mode | Character string, defined the types of the paths used for thebreadth-first search. “out” follows the outgoing, “in” theincoming edges, “all” and “total” both of them. This argumentis ignored for undirected graphs. |
roots | A vector giving the vertices from which the breadth-firstsearch is performed. Typically it contains one vertex per component. |
Convert a general graph into a forest
Description
Perform a breadth-first search on a graph and convert it into a tree orforest by replicating vertices that were found more than once.
Usage
unfold_tree(graph, mode = c("all", "out", "in", "total"), roots)Arguments
graph | The input graph, it can be either directed or undirected. |
mode | Character string, defined the types of the paths used for thebreadth-first search. “out” follows the outgoing, “in” theincoming edges, “all” and “total” both of them. This argumentis ignored for undirected graphs. |
roots | A vector giving the vertices from which the breadth-firstsearch is performed. Typically it contains one vertex per component. |
Details
A forest is a graph, whose components are trees.
Theroots vector can be calculated by simply doing a topological sortin all components of the graph, see the examples below.
Value
A list with two components:
- tree
The result, an
igraphobject, a tree or a forest.- vertex_index
A numeric vector, it gives a mapping from the vertices of the new graph to the vertices of the old graph.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
Other structural.properties:bfs(),component_distribution(),connect(),constraint(),coreness(),degree(),dfs(),distance_table(),edge_density(),feedback_arc_set(),feedback_vertex_set(),girth(),is_acyclic(),is_dag(),is_matching(),k_shortest_paths(),knn(),reciprocity(),subcomponent(),subgraph(),topo_sort(),transitivity(),which_multiple(),which_mutual()
Examples
g <- make_tree(10) %du% make_tree(10)V(g)$id <- seq_len(vcount(g)) - 1roots <- sapply(decompose(g), function(x) { V(x)$id[topo_sort(x)[1] + 1]})tree <- unfold_tree(g, roots = roots)Union of two or more sets
Description
This is an S3 generic function. Seemethods("union")for the actual implementations for various S3 classes. Initiallyit is implemented for igraph graphs and igraph vertex and edgesequences. Seeunion.igraph(), andunion.igraph.vs().
Usage
union(...)Arguments
... | Arguments, their number and interpretation depends onthe function that implements |
Value
Depends on the function that implements this method.
See Also
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()
Union of graphs
Description
The union of two or more graphs are created. The graphs may have identicalor overlapping vertex sets.
Usage
## S3 method for class 'igraph'union(..., byname = "auto")Arguments
... | Graph objects or lists of graph objects. |
byname | A logical scalar, or the character scalar |
Details
union() creates the union of two or more graphs. Edges which areincluded in at least one graph will be part of the new graph. This functioncan be also used via the%u% operator.
If thebyname argument isTRUE (orauto and all graphsare named), then the operation is performed on symbolic vertex names insteadof the internal numeric vertex ids.
union() keeps the attributes of all graphs. All graph, vertex andedge attributes are copied to the result. If an attribute is present inmultiple graphs and would result a name clash, then this attribute isrenamed by adding suffixes: _1, _2, etc.
Thename vertex attribute is treated specially if the operation isperformed based on symbolic vertex names. In this casename must bepresent in all graphs, and it is not renamed in the result graph.
An error is generated if some input graphs are directed and others areundirected.
Value
A new graph object.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
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()
Examples
## Union of two social networks with overlapping sets of actorsnet1 <- 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
Description
Union of edge sequences
Usage
## S3 method for class 'igraph.es'union(...)Arguments
... | The edge sequences to take the union of. |
Details
They must belong to the same graph. Note that this function has‘set’ semantics and the multiplicity of edges is lost in theresult. (This is to match the behavior of the baseduniquefunction.)
Value
An edge sequence that contains all edges in the givensequences, exactly once.
See Also
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()
Examples
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
Description
Union of vertex sequences
Usage
## S3 method for class 'igraph.vs'union(...)Arguments
... | The vertex sequences to take the union of. |
Details
They must belong to the same graph. Note that this function has‘set’ semantics and the multiplicity of vertices is lost in theresult. (This is to match the behavior of the baseduniquefunction.)
Value
A vertex sequence that contains all vertices in the givensequences, exactly once.
See Also
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()
Examples
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
Description
Remove duplicate edges from an edge sequence
Usage
## S3 method for class 'igraph.es'unique(x, incomparables = FALSE, ...)Arguments
x | An edge sequence. |
incomparables | a vector of values that cannot be compared.Passed to base function |
... | Passed to base function |
Value
An edge sequence with the duplicate vertices removed.
See Also
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()
Examples
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
Description
Remove duplicate vertices from a vertex sequence
Usage
## S3 method for class 'igraph.vs'unique(x, incomparables = FALSE, ...)Arguments
x | A vertex sequence. |
incomparables | a vector of values that cannot be compared.Passed to base function |
... | Passed to base function |
Value
A vertex sequence with the duplicate vertices removed.
See Also
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()
Examples
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 data structure versions
Description
igraph's internal data representation changes sometimes betweenversions. This means that it is not possible to use igraph objectsthat were created (and possibly saved to a file) with an olderigraph version.
Usage
upgrade_graph(graph)Arguments
graph | The input graph. |
Details
graph_version() queries the current data format,or the data format of a possibly older igraph graph.
upgrade_graph() can convert an older data formatto the current one.
Value
The graph in the current format.
See Also
graph_version to check the current data format versionor the version of a graph.
Other versions:graph_version()
Helper function for adding and deleting vertices
Description
This is a helper function that simplifies adding and deletingvertices to/from graphs.
Usage
vertex(...)vertices(...)Arguments
... | See details below. |
Details
vertices() is an alias forvertex().
When adding vertices via+, all unnamed arguments are interpretedas vertex names of the new vertices. Named arguments are interpreted asvertex attributes for the new vertices.
When deleting vertices via-, all arguments ofvertex() (orvertices()) are concatenated viac() and passed todelete_vertices().
Value
A special object that can be used with together withigraph graphs and the plus and minus operators.
See Also
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()
Examples
g <- make_(ring(10), with_vertex_(name = LETTERS[1:10])) + vertices("X", "Y")gplot(g)Vertex connectivity
Description
vertex.connectivity() was renamed tovertex_connectivity() to create a moreconsistent API.
Usage
vertex.connectivity(graph, source = NULL, target = NULL, checks = TRUE)Arguments
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 connectedand also the degree of the vertices. If the graph is not (strongly)connected then the connectivity is obviously zero. Otherwise if the minimumdegree is one then the vertex connectivity is also one. It is a good idea toperform these checks, as they can be done quickly compared to theconnectivity calculation itself. They were suggested by Peter McMahan,thanks Peter. |
Vertex connectivity
Description
vertex.disjoint.paths() was renamed tovertex_disjoint_paths() to create a moreconsistent API.
Usage
vertex.disjoint.paths(graph, source = NULL, target = NULL)Arguments
source | The id of the source vertex, for |
target | The id of the target vertex, for |
Using pie charts as vertices in graph plots
Description
More complex vertex images can be used to express addtional informationabout vertices. E.g. pie charts can be used as vertices, to denote vertexclasses, fuzzy classification of vertices, etc.
Details
The vertex shape ‘pie’ makes igraph draw a pie chart for everyvertex. There are some extra graphical vertex parameters that specify howthe pie charts will look like:
- pie
Numeric vector, gives the sizes of the pie slices.
- pie.color
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.
- pie.angle
The slope of shading lines, given as an angle in degrees (counter-clockwise).
- pie.density
The density of the shading lines, in lines per inch.Non-positive values inhibit the drawing of shading lines.
- pie.lty
The line type of the border of the slices.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
igraph.plotting(),plot.igraph()
Examples
g <- make_ring(10)values <- lapply(1:10, function(x) sample(1:10, 3))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)Various vertex shapes when plotting igraph graphs
Description
vertex.shapes() was renamed toshapes() to create a moreconsistent API.
Usage
vertex.shapes(shape = NULL)Arguments
shape | Character scalar, name of a vertex shape. If it is |
Query vertex attributes of a graph
Description
Query vertex attributes of a graph
Usage
vertex_attr(graph, name, index = V(graph))Arguments
graph | The graph. |
name | Name of the attribute to query. If missing, thenall vertex attributes are returned in a list. |
index | An optional vertex sequence to query the attribute onlyfor these vertices. |
Value
The value of the vertex attribute, or the list ofall vertex attributes, ifname is missing.
See Also
Vertex, edge and graph attributesdelete_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(),set_vertex_attrs(),vertex_attr<-(),vertex_attr_names()
Examples
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)Set one or more vertex attributes
Description
Set one or more vertex attributes
Usage
vertex_attr(graph, name, index = V(graph)) <- valueArguments
graph | The graph. |
name | The name of the vertex attribute to set. If missing,then |
index | An optional vertex sequence to set the attributesof a subset of vertices. |
value | The new value of the attribute(s) for all(or |
Value
The graph, with the vertex attribute(s) added or set.
See Also
Vertex, edge and graph attributesdelete_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(),set_vertex_attrs(),vertex_attr(),vertex_attr_names()
Examples
g <- make_ring(10)vertex_attr(g) <- list( name = LETTERS[1:10], color = rep("yellow", gorder(g)))vertex_attr(g, "label") <- V(g)$namegplot(g)List names of vertex attributes
Description
List names of vertex attributes
Usage
vertex_attr_names(graph)Arguments
graph | The graph. |
Value
Character vector, the names of the vertex attributes.
See Also
Vertex, edge and graph attributesdelete_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(),set_vertex_attrs(),vertex_attr(),vertex_attr<-()
Examples
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)Vertex connectivity
Description
The vertex connectivity of a graph or two vertices, this is recently alsocalled group cohesion.
Usage
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, ...)Arguments
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 connectedand also the degree of the vertices. If the graph is not (strongly)connected then the connectivity is obviously zero. Otherwise if the minimumdegree is one then the vertex connectivity is also one. It is a good idea toperform these checks, as they can be done quickly compared to theconnectivity calculation itself. They were suggested by Peter McMahan,thanks Peter. |
... | Additional arguments passed to methods. Not used by |
Details
The vertex connectivity of two vertices (source andtarget) ina graph is the minimum number of vertices that must be deleted toeliminate all (directed) paths fromsource totarget.vertex_connectivity() calculates this quantity if both thesource andtarget arguments are given and they're notNULL.
The vertex connectivity of a pair is the same as the numberof different (i.e. node-independent) paths from source totarget, 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 minimumnumber of vertices needed to remove to make the graph not stronglyconnected. (If the graph is not strongly connected then this is zero.)vertex_connectivity() calculates this quantity if neither thesource nortarget arguments are given. (I.e. they are bothNULL.)
A set of vertex disjoint directed paths fromsource tovertexis a set of directed paths between them whose vertices do not contain commonvertices (apart fromsource andtarget). The maximum number ofvertex disjoint paths between two vertices is the same as their vertexconnectivity in most cases (if the two vertices are not connected by anedge).
The cohesion of a graph (as defined by White and Harary, see references), isthe vertex connectivity of the graph. This is calculated bycohesion().
These three functions essentially calculate the same measure(s), morepreciselyvertex_connectivity() is the most general, the other two areincluded only for the ease of using more descriptive function names.
Value
A scalar real value.
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
White, Douglas R and Frank Harary 2001. The Cohesiveness ofBlocks In Social Networks: Node Connectivity and Conditional Density.Sociological Methodology 31 (1) : 305-359.
See Also
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()
Examples
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)Voronoi partitioning of a graph
Description
This function partitions the vertices of a graph based on a set of generatorvertices. Each vertex is assigned to the generator vertex from (or to) whichit is closest.
groups() may be used on the output of this function.
Usage
voronoi_cells( graph, generators, ..., weights = NULL, mode = c("out", "in", "all", "total"), tiebreaker = c("random", "first", "last"))Arguments
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 computedistances from generator vertices to other vertices ( |
tiebreaker | Character string that specifies what to do when a vertexis at the same distance from multiple generators. |
Value
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
Related documentation in the C library
See Also
Community detectionas_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()
Examples
g <- make_lattice(c(10, 10))clu <- voronoi_cells(g, c(25, 43, 67))groups(clu)plot(g, vertex.color = clu$membership)Community structure via short random walks
Description
walktrap.community() was renamed tocluster_walktrap() to create a moreconsistent API.
Usage
walktrap.community( graph, weights = NULL, steps = 4, merges = TRUE, modularity = TRUE, membership = TRUE)Arguments
graph | The input graph. Edge directions are ignored in directedgraphs. |
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 theresult. |
modularity | Logical scalar, whether to include the vector of themodularity scores in the result. If the |
membership | Logical scalar, whether to calculate the membership vectorfor the split corresponding to the highest modularity value. |
The Watts-Strogatz small-world model
Description
watts.strogatz.game() was renamed tosample_smallworld() to create a moreconsistent API.
Usage
watts.strogatz.game(dim, size, nei, p, loops = FALSE, multiple = FALSE)Arguments
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 ofthe lattice will be connected. |
p | Real constant between zero and one, the rewiring probability. |
loops | Logical scalar, whether loops edges are allowed in thegenerated graph. |
multiple | Logical scalar, whether multiple edges are allowed int thegenerated graph. |
Functions to find weighted cliques, i.e. vertex-weighted complete subgraphs in a graph
Description
These functions find all, the largest or all the maximal weighted cliques inan undirected graph. The weight of a clique is the sum of the weights of itsvertices.
Usage
weighted_cliques( graph, vertex.weights = NULL, min.weight = 0, max.weight = 0, maximal = FALSE)Arguments
graph | The input graph, directed graphs will be considered asundirected 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 ( |
Details
weighted_cliques() finds all complete subgraphs in the input graph,obeying the weight limitations given in themin andmaxarguments.
largest_weighted_cliques() finds all largest weighted cliques in theinput graph. A clique is largest if there is no other clique whose totalweight is larger than the weight of this clique.
weighted_clique_num() calculates the weight of the largest weighted clique(s).
Value
weighted_cliques() andlargest_weighted_cliques() return alist containing numeric vectors of vertex IDs. Each list element is a weightedclique, i.e. a vertex sequence of classigraph.vs.
weighted_clique_num() returns an integer scalar.
Related documentation in the C library
Author(s)
Tamas Nepuszntamas@gmail.com and Gabor Csardicsardi.gabor@gmail.com
See Also
Other cliques:cliques(),is_complete(),ivs()
Examples
g <- make_graph("zachary")V(g)$weight <- 1V(g)[c(1, 2, 3, 4, 14)]$weight <- 3weighted_cliques(g)weighted_cliques(g, maximal = TRUE)largest_weighted_cliques(g)weighted_clique_num(g)Find the multiple or loop edges in a graph
Description
A loop edge is an edge from a vertex to itself. An edge is a multiple edgeif it has exactly the same head and tail vertices as another edge. A graphwithout multiple and loop edges is called a simple graph.
Usage
which_multiple(graph, eids = E(graph))any_multiple(graph)count_multiple(graph, eids = E(graph))which_loop(graph, eids = E(graph))any_loop(graph)Arguments
graph | The input graph. |
eids | The edges to which the query is restricted. By default this isall edges in the graph. |
Details
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 multipleedges.
count_multiple() counts the multiplicity of each edge of a graph.
Note that the semantics forwhich_multiple() andcount_multiple() isdifferent.which_multiple() givesTRUE for all occurrences of amultiple edge except for one. I.e. if there are threei-j edges in thegraph thenwhich_multiple() returnsTRUE for only two of them whilecount_multiple() returns ‘3’ for all three.
See the examples for getting rid of multiple edges while keeping theiroriginal multiplicity as an edge attribute.
Value
any_loop() andany_multiple() return a logical scalar.which_loop() andwhich_multiple() return a logical vector.count_multiple() returns a numeric vector.
Related documentation in the C library
is_multiple(),has_multiple(),count_multiple(),is_loop(),has_loop().
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
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(),feedback_vertex_set(),girth(),is_acyclic(),is_dag(),is_matching(),k_shortest_paths(),knn(),reciprocity(),subcomponent(),subgraph(),topo_sort(),transitivity(),unfold_tree(),which_mutual()
Examples
# Loopsg <- make_graph(c(1, 1, 2, 2, 3, 3, 4, 5))any_loop(g)which_loop(g)# Multiple edgesg <- 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 importantwhich_multiple(make_graph(c(1, 2, 2, 1)))which_multiple(make_graph(c(1, 2, 2, 1), dir = FALSE))# Remove multiple edges but keep multiplicityg <- 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)$weightFind mutual edges in a directed graph
Description
This function checks the reciprocal pair of the supplied edges.
Usage
which_mutual(graph, eids = E(graph), loops = TRUE)Arguments
graph | The input graph. |
eids | Edge sequence, the edges that will be probed. By default isincludes all edges in the order of their ids. |
loops | Logical, whether to consider directed self-loops to be mutual. |
Details
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 containstwo copies of (A,B) and one copy of (B,A), then these three edges areconsidered to be mutual.
Undirected graphs contain only mutual edges by definition.
Value
A logical vector of the same length as the number of edges supplied.
Related documentation in the C library
Author(s)
Gabor Csardicsardi.gabor@gmail.com
See Also
reciprocity(),dyad_census() if you justwant some statistics about mutual edges.
Other structural.properties:bfs(),component_distribution(),connect(),constraint(),coreness(),degree(),dfs(),distance_table(),edge_density(),feedback_arc_set(),feedback_vertex_set(),girth(),is_acyclic(),is_dag(),is_matching(),k_shortest_paths(),knn(),reciprocity(),subcomponent(),subgraph(),topo_sort(),transitivity(),unfold_tree(),which_multiple()
Examples
g <- sample_gnm(10, 50, directed = TRUE)reciprocity(g)dyad_census(g)which_mutual(g)sum(which_mutual(g)) / 2 == dyad_census(g)$mutConstructor modifier to add edge attributes
Description
Constructor modifier to add edge attributes
Usage
with_edge_(...)Arguments
... | The attributes to add. They must be named. |
See Also
Constructor modifiers (and related functions)make_(),sample_(),simplified(),with_graph_(),with_vertex_(),without_attr(),without_loops(),without_multiples()
Examples
make_( ring(10), with_edge_( color = "red", weight = rep(1:2, 5) )) %>% plot()Constructor modifier to add graph attributes
Description
Constructor modifier to add graph attributes
Usage
with_graph_(...)Arguments
... | The attributes to add. They must be named. |
See Also
Constructor modifiers (and related functions)make_(),sample_(),simplified(),with_edge_(),with_vertex_(),without_attr(),without_loops(),without_multiples()
Examples
make_(ring(10), with_graph_(name = "10-ring"))Run code with a temporary igraph options setting
Description
Run code with a temporary igraph options setting
Usage
with_igraph_opt(options, code)Arguments
options | A named list of the options to change. |
code | The code to run. |
Value
The result of thecode.
See Also
Other igraph options:igraph_options()
Examples
with_igraph_opt( list(sparsematrices = FALSE), make_ring(10)[])igraph_opt("sparsematrices")Constructor modifier to add vertex attributes
Description
Constructor modifier to add vertex attributes
Usage
with_vertex_(...)Arguments
... | The attributes to add. They must be named. |
See Also
Constructor modifiers (and related functions)make_(),sample_(),simplified(),with_edge_(),with_graph_(),without_attr(),without_loops(),without_multiples()
Examples
make_( ring(10), with_vertex_( color = "#7fcdbb", frame.color = "#7fcdbb", name = LETTERS[1:10] )) %>% plot()Construtor modifier to remove all attributes from a graph
Description
Construtor modifier to remove all attributes from a graph
Usage
without_attr()See Also
Constructor modifiers (and related functions)make_(),sample_(),simplified(),with_edge_(),with_graph_(),with_vertex_(),without_loops(),without_multiples()
Examples
g1 <- make_ring(10)g1g2 <- make_(ring(10), without_attr())g2Constructor modifier to drop loop edges
Description
Constructor modifier to drop loop edges
Usage
without_loops()See Also
Constructor modifiers (and related functions)make_(),sample_(),simplified(),with_edge_(),with_graph_(),with_vertex_(),without_attr(),without_multiples()
Examples
# An artificial examplemake_(full_graph(5, loops = TRUE))make_(full_graph(5, loops = TRUE), without_loops())Constructor modifier to drop multiple edges
Description
Constructor modifier to drop multiple edges
Usage
without_multiples()See Also
Constructor modifiers (and related functions)make_(),sample_(),simplified(),with_edge_(),with_graph_(),with_vertex_(),without_attr(),without_loops()
Examples
sample_(pa(10, m = 3, algorithm = "bag"))sample_(pa(10, m = 3, algorithm = "bag"), without_multiples())Writing the graph to a file in some format
Description
write.graph() was renamed towrite_graph() to create a moreconsistent API.
Usage
write.graph( graph, file, format = c("edgelist", "pajek", "ncol", "lgl", "graphml", "dimacs", "gml", "dot", "leda"), ...)Arguments
graph | The graph to export. |
file | A connection or a string giving the file name to write the graphto. |
format | Character string giving the file format. Right now |
... | Other, format specific arguments, see below. |
Writing the graph to a file in some format
Description
write_graph() is a general function for exporting graphs to foreignfile formats. The recommended formats for data exchange are GraphML and GML.
Usage
write_graph( graph, file, format = c("edgelist", "pajek", "ncol", "lgl", "graphml", "dimacs", "gml", "dot", "leda"), ...)Arguments
graph | The graph to export. |
file | A connection or a string giving the file name to write the graphto. |
format | Character string giving the file format. Right now |
... | Other, format specific arguments, see below. |
Value
A 'NULL“, invisibly.
Edge list format
Theedgelist format is a simple text file,with one edge per line, the two zero-based numerical vertex IDs separatedby 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 noadditional arguments.
NCOL format
This format is a plain text edge list in which verticesare referred to by name rather than numerical ID. Edge weights may beoptionally written. Additional parameters:
- names
The name of a vertex attribute to take vertex names from or
NULLto use zero-based numerical IDs.- weights
The name of an edge attribute to take edge weights from or
NULLto omit edge weights.
Pajek format
Thepajek format is provided for interoperabilitywith the Pajek software only. Since the format does not have a formalspecification, it is not recommended for general data exchange or archival.
LGL format
The .lgl format is used by the Large Graph Layout visualization software (https://lgl.sourceforge.net), it can describe undirected optionally weighted graphs.
- names
The name of a vertex attribute to use for vertex names, orNULL to use numeric IDs.
- weights
The name of an edge attribute to use for edge weights, orNULL to omit weights.
- isolates
Logical, whether to include isolated vertices in the file.Default is FALSE.
DIMACS format
This is a line-oriented text file (ASCII) format.The first character of each line defines the type of the line.If the first character is c the line is a comment line and it is ignored.There is one problem line (p in the file),it must appear before any node and arc descriptor lines.The problem line has three fields separated by spaces: the problem type (max or edge),the number of vertices, and number of edges in the graph. In MAX problems,exactly two node identification lines are expected (n), one for the source, and one for the target vertex.These have two fields: the ID of the vertex and the type of the vertex, either s ( = source) or t ( = target).Arc lines start with a and have three fields: the source vertex, the target vertex and the edge capacity.In EDGE problems, there may be a node line (n) for each node. It specifies the node index and aninteger node label. Nodes for which no explicit label was specified will use their index as label.In EDGE problems, each edge is specified as an edge line (e).
- source
Numeric ID of the source vertex.
- target
Numeric ID of the target vertex.
- capacity
The name of an edge attribute to use for edge capacities,or NULL to use the "capacity" attribute if it exists.
GML format
GML is a quite general textual format.
- id
Optional numeric vertex IDs to use.
- creator
Optional string specifying the creator of the file.
GraphML format
GraphML is an XML-based file format for representing various types of graphs.When a numerical attribute value is NaN, it will be omitted from the file.This function assumes that non-ASCII characters in attribute names and stringattribute values are UTF-8 encoded. If this is not the case, the resulting XML file will be invalid. Control characters, i.e. character codes up to and including 31 (with the exception of tab, cr and lf), are not allowed.
- prefixAttr
Logical, whether to prefix attribute names to ensureuniqueness across vertex/edge/graph attributes. Default is TRUE.
LEDA format
This function writes a graph to an output stream in LEDA format.Seehttps://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html.The support for the LEDA format is very basic at the moment; igraph writes only the LEDA graph section which supports one selected vertex and edgeattribute and no layout information or visual attributes.
- vertex.attr
Name of vertex attribute to include in the file.
- edge.attr
Name of edge attribute to include in the file.
DOT format
DOT is the format used by the widely known GraphViz software, seehttps://www.graphviz.org for details.The grammar of the DOT format can be found here:https://www.graphviz.org/doc/info/lang.html.This is only a preliminary implementation, no visualization information is written.This format is meant solely for interoperability with Graphviz. It is not recommended fordata exchange or archival.
Related documentation in the C library
write_graph_dimacs_flow(),write_graph_dot(),write_graph_edgelist(),write_graph_gml(),write_graph_graphml(),write_graph_leda(),write_graph_lgl(),write_graph_ncol(),write_graph_pajek().
Author(s)
Gabor Csardicsardi.gabor@gmail.com
References
Adai AT, Date SV, Wieland S, Marcotte EM. LGL: creating a map ofprotein function with an algorithm for visualizing very large biologicalnetworks.J Mol Biol. 2004 Jun 25;340(1):179-90.
See Also
Foreign format readersgraph_from_graphdb(),read_graph()
Examples
g <- make_ring(10)file <- tempfile(fileext = ".txt")write_graph(g, file, "edgelist")if (!interactive()) { unlink(file)}