library(igraph)
#>
#> Attaching package: 'igraph'
#> The following objects are masked from 'package:stats':
#>
#> decompose, spectrum
#> The following object is masked from 'package:base':
#>
#> unionigraph ships a native, dependency-light plotting engine
built on base R graphics. A single call to plot() “just
works”, and every visual detail (vertex shapes, edge routing, colours,
labels, legends) is controllable through arguments to
plot() or through vertex/edge/graph attributes.
This article is a complete tour of that engine: it walks through both the long-standing features and the more recent additions (scales and legends, label repelling and halos, richer edge styles, colour gradients and transparency, and SVG export). Everything is shown at least once.
# A small attributed social network used throughout this article.
g <- make_graph(
~ Alice - Boris:Himari:Moshe, Himari - Alice:Nang:Moshe:Samira,
Ibrahim - Nang:Moshe, Nang - Samira
)
V(g)$gender <- c("f", "m", "f", "m", "m", "f", "m")
E(g)$kind <- rep(c("friend", "colleague"), length.out = ecount(g))Quick start
The simplest possible call lays the graph out automatically and draws it:
plot(g)
There are two ways to control appearance:
-
As an argument to
plot(), prefixed withvertex./edge./ (none for plot-level), e.g.vertex.color = "tomato". -
As a graph attribute,
e.g.
V(g)$color <- "tomato".
Arguments to plot() take precedence over attributes,
which in turn take precedence over options and built-in defaults (see Setting defaults). Keeping the styling in
the plot() call keeps the visual representation separate
from the graph data:
plot(
g,
vertex.color = ifelse(V(g)$gender == "m", "skyblue", "pink"),
vertex.size = 30,
edge.width = ifelse(E(g)$kind == "colleague", 3, 1)
)
Layouts
A graph is an abstract object; to draw it we first map vertices to
coordinates with a layout algorithm. All layout functions start
with layout_:
| Method name | Algorithm description |
|---|---|
layout_randomly |
Places vertices completely randomly |
layout_in_circle |
Deterministic; places vertices on a circle |
layout_on_sphere |
Deterministic; places vertices evenly on a sphere surface |
layout_with_drl |
DrL (Distributed Recursive Layout), for large graphs |
layout_with_fr |
Fruchterman–Reingold force-directed algorithm |
layout_with_kk |
Kamada–Kawai force-directed algorithm |
layout_with_lgl |
LGL (Large Graph Layout), for large graphs |
layout_as_tree |
Reingold–Tilford tree layout |
layout_nicely |
Picks a sensible algorithm automatically (the default) |
A layout function returns a matrix with one row per vertex. You can pass either a precomputed matrix or the function itself:
lay <- layout_with_kk(g)
plot(g, layout = lay, main = "Kamada-Kawai layout")
plot(g, layout = layout_in_circle, main = "Circular layout")
By default coordinates are rescaled to fit a [-1, 1]
square with aspect ratio 1. Disable rescaling and set the
limits/aspect/margins yourself when you need the layout’s own
coordinates:
plot(
g,
layout = lay,
rescale = FALSE,
xlim = range(lay[, 1]),
ylim = range(lay[, 2]),
asp = 1,
margin = 0.1
)
Vertices
Vertex colour, size and frame are the basic knobs.
vertex.size2 sets the second dimension for non-square
shapes (e.g. rectangles).
plot(
g,
vertex.color = "gold",
vertex.size = 35,
vertex.frame.color = "grey30",
vertex.frame.width = 2
)
Transparency
vertex.alpha (and edge.alpha, later) set
opacity in [0, 1], folded into the fill colour:
plot(g, vertex.color = "purple", vertex.alpha = 0.4, vertex.size = 40)
Shape gallery
The built-in shapes are circle, square,
csquare (centred square), rectangle,
crectangle (centred rectangle), vrectangle
(vertical rectangle), none (labels only), pie,
sphere, and raster. Use shapes()
to list everything currently registered:
shapes()
#> [1] "circle" "crectangle" "csquare" "none" "pie"
#> [6] "raster" "rectangle" "sphere" "square" "vrectangle"
shp <- c(
"circle", "square", "csquare", "rectangle",
"crectangle", "vrectangle", "none", "pie", "sphere", "raster"
)
ring <- make_ring(length(shp))
plot(
ring,
vertex.shape = shp,
vertex.label = shp,
vertex.label.dist = 1.4,
vertex.size = 26,
vertex.size2 = 18,
# pie data is only used by the "pie" shape
vertex.pie = lapply(shp, function(s) if (s == "pie") c(2, 3, 1) else 0),
vertex.pie.color = list(c("tomato", "gold", "skyblue"))
)
The pie shape draws a small pie chart per vertex; its
slices, colours, shading angle, shading density and line type are
controlled by vertex.pie, vertex.pie.color,
vertex.pie.angle, vertex.pie.density and
vertex.pie.lty. The raster shape draws an
image (defaulting to the igraph logo); supply your own with
vertex.raster.
Vertex labels
Labels default to vertex names (or IDs). They are positioned at a
distance label.dist from the vertex, in the direction
label.degree (an angle in radians), and styled with the
usual font controls. label.angle rotates the text and
label.adj fine-tunes its anchor.
plot(
g,
vertex.size = 30,
vertex.label.color = "black",
vertex.label.family = "sans",
vertex.label.font = 2, # bold
vertex.label.cex = 1.1,
vertex.label.dist = 2.2,
vertex.label.degree = -pi / 2 # place labels above the vertices
)
vertex.label.angle rotates the label text (in degrees)
and vertex.label.adj adjusts its anchor, exactly like
srt and adj in
graphics::text():

Avoiding overlaps with label.repel
On dense graphs labels collide. Set
vertex.label.repel = TRUE to iteratively nudge overlapping
labels apart, drawing a thin leader line from each moved label back to
its vertex. Every iteration compares all pairs of labels, so this is
meant for up to a few hundred labels; on larger graphs, label fewer
vertices (see label_top()):
gr <- make_full_graph(25)
V(gr)$name <- paste0("node-", seq_len(vcount(gr)))
plot(gr, vertex.size = 25, vertex.label.cex = 2, vertex.label.repel = TRUE)
Legibility with label.halo
vertex.label.halo draws a halo (outline) behind the
label text so it stays readable over edges and other vertices.
vertex.label.halo.width controls the outline thickness as a
fraction of the label height. The default NA draws no
halo.
plot(
g,
vertex.size = 30,
vertex.color = "steelblue",
vertex.label.color = "white",
vertex.label.halo = "black",
vertex.label.halo.width = 0.3
)
Edges
Edges are styled with colour, width and line type, and (for directed
graphs) arrowheads. edge.arrow.mode chooses the arrow
direction (0 none, 1 backward, 2
forward, 3 both, or the symbolic "<",
">", "<>"); it also accepts
"a:attr" to read the mode from a vertex attribute.
dg <- make_graph(~ A -+ B, B -+ C, C -+ A, A -+ D)
plot(
dg,
edge.color = "grey40",
edge.width = 2,
edge.lty = "dashed",
edge.arrow.size = 0.8,
edge.arrow.width = 1.2
)
Curved edges and multi-edge fans
edge.curved bends edges: TRUE means
curvature 0.5, numeric values set the amount (negative bends the other
way). For graphs with parallel edges, curve_multiple() fans
them apart so they don’t overlap:
multi <- graph_from_edgelist(
matrix(c(1, 2, 1, 2, 1, 2, 2, 3), ncol = 2, byrow = TRUE)
)
plot(multi, edge.curved = curve_multiple(multi), edge.arrow.size = 0.6)
Edge styles
The edge.style argument selects an edge-routing
style:
-
"auto"(default): straight, or an arc whenedge.curvedis non-zero -
"straight": always straight -
"arc": a curved arc whose height comes fromedge.curved -
"elbow": a two-corner orthogonal (right-angle) connector -
"diagonal": a smooth S-curve with axis-aligned ends
The orthogonal and diagonal styles are well suited to tree- and grid-like layouts:
tree <- make_tree(7, children = 2)
op <- par(mfrow = c(1, 3), mar = c(1, 1, 2, 1))
plot(tree, layout = layout_as_tree, edge.style = "arc", main = "arc")
plot(tree, layout = layout_as_tree, edge.style = "elbow", main = "elbow")
plot(tree, layout = layout_as_tree, edge.style = "diagonal", main = "diagonal")
par(op)Transparency and colour gradients
edge.alpha sets edge opacity.
edge.gradient = TRUE colours each edge with a gradient
running from the source vertex’s colour to the target’s, a way to show
direction without arrowheads:
ring_d <- make_ring(8, directed = TRUE)
V(ring_d)$color <- rainbow(vcount(ring_d))
plot(
ring_d,
layout = layout_in_circle,
vertex.size = 18,
edge.gradient = TRUE,
edge.width = 4,
edge.arrow.mode = 0
)
plot(dg, edge.color = "navy", edge.alpha = 0.3, edge.width = 6)
Self-loops
Loops are drawn as small arcs. edge.loop.angle sets the
direction of a loop (in radians) and the plot-level
loop.size scales them:
# the formula interface drops self-loops, so build the edge list directly
loops <- make_graph(c("A", "A", "A", "B", "B", "B"), directed = TRUE)
plot(
loops,
layout = matrix(c(-0.5, 0.5, 0, 0), ncol = 2),
vertex.size = 36,
edge.loop.angle = pi / 2,
loop.size = 1.5,
edge.arrow.size = 0.6,
margin = 0.25
)
When a single vertex carries several loops, igraph spreads them around the vertex in a “flower-petal” arrangement so they don’t overlap:
# six self-loops on a single vertex
many <- make_graph(rep(1, 12), n = 1, directed = TRUE)
plot(many, vertex.size = 30, edge.arrow.size = 0.5, margin = 0.2)
Edge labels
Edge labels are added with edge.label and styled with
the matching edge.label.* controls, including a halo
(edge.label.halo) just like vertex labels.
edge.label.x / edge.label.y override the
automatic placement.
plot(
dg,
edge.label = c("a", "b", "c", "d"),
edge.label.color = "black",
edge.label.cex = 1.2,
edge.label.family = "sans",
edge.label.halo = "yellow",
edge.label.halo.width = 0.4,
edge.arrow.size = 0.6
)
Colours and palettes
igraph provides perceptually sensible palettes:
categorical_pal() for unordered categories,
sequential_pal() for ordered magnitudes,
diverging_pal() for signed data, and r_pal()
for R’s classic palette.
op <- par(mfrow = c(1, 4), mar = c(0, 1, 2, 1))
pie(rep(1, 8), col = categorical_pal(8), main = "categorical_pal(8)")
pie(rep(1, 9), col = sequential_pal(9), main = "sequential_pal(9)")
pie(rep(1, 9), col = diverging_pal(9), main = "diverging_pal(9)")
pie(rep(1, 8), col = r_pal(8), main = "r_pal(8)")
par(op)When a vertex/edge colour is given as a factor or integer, it indexes
into the active palette:
plot(
g,
vertex.color = as.factor(V(g)$gender),
palette = categorical_pal(8),
vertex.size = 30
)
Scales and legends
Passing a raw colour vector means igraph never learns what the
colours mean, so it cannot explain them. The scale helpers fix
this: they map a data column to an aesthetic and record the
mapping, so plot() can draw a matching guide
automatically. There is one helper per kind of aesthetic:
| Helper | Use with | Guide |
|---|---|---|
scale_vertex_color() |
vertex.color (and other vertex.*
colours) |
legend or colourbar |
scale_edge_color() |
edge.color |
legend or colourbar |
scale_vertex_size() |
vertex.size |
size legend |
scale_edge_width() |
edge.width |
width legend |
A vertex scale only works with a vertex.* argument and
an edge scale only with an edge.* argument;
plot() tells you if they are mixed up.
scale_vertex_color() on a discrete variable produces a
categorical legend:
plot(
g,
vertex.color = scale_vertex_color(V(g)$gender, name = "Gender"),
vertex.size = 30
)
On a numeric variable it produces a continuous colourbar:
plot(
g,
vertex.color = scale_vertex_color(degree(g), name = "Degree"),
vertex.size = 30
)
scale_vertex_size() maps a numeric variable to a size
range and draws a size legend. Its trans argument
transforms the data first, e.g. "sqrt" or
"log10" for skewed data such as degrees in a large network;
the legend then uses breaks that are evenly spaced on the transformed
scale.
plot(
g,
vertex.size = scale_vertex_size(degree(g), range = c(10, 35), name = "Degree"),
vertex.color = "lightgrey"
)
The edge helpers work the same way:
E(g)$weight <- seq_len(ecount(g))
plot(
g,
vertex.size = 25,
vertex.color = "lightgrey",
edge.color = scale_edge_color(E(g)$kind, name = "Tie"),
edge.width = scale_edge_width(E(g)$weight, range = c(1, 6), name = "Weight")
)
The legend argument controls placement:
TRUE (default, right side), "left",
"top", "bottom", or FALSE to
suppress the guide. Multiple scales combine into one guide region:
plot(
g,
vertex.color = scale_vertex_color(V(g)$gender, name = "Gender"),
vertex.size = scale_vertex_size(degree(g), range = c(12, 34), name = "Degree"),
legend = "bottom"
)
The guide takes its space from the current figure, so plots with
legends can be arranged with par(mfrow = ) or
layout() like any other plot.
Decluttering with label_top()
On large graphs, labelling every vertex is unreadable.
label_top() keeps only the highest-ranking labels by some
metric and blanks the rest with NA (which
plot() omits):
big <- sample_gnp(40, 0.08)
plot(
big,
vertex.size = 6,
vertex.label = label_top(degree(big), n = 5),
vertex.label.dist = 1,
vertex.label.color = "black"
)
Use prop to keep a fraction instead of a count, and
decreasing = FALSE to keep the lowest:
plot(
big,
vertex.size = 6,
vertex.label = label_top(degree(big), prop = 0.1, decreasing = FALSE),
vertex.label.dist = 1,
vertex.label.color = "black"
)
To label everything above a fixed cutoff you don’t need the helper:
ifelse(metric > cutoff, labels, NA) works directly.
Highlighting groups
mark.groups draws a smoothed, filled polygon “under” a
set of vertices. The fill, border, smoothness, padding and border width
are set by mark.col, mark.border,
mark.shape, mark.expand and
mark.lwd:
plot(
g,
vertex.size = 25,
mark.groups = list(c("Alice", "Himari", "Moshe"), c("Nang", "Samira")),
mark.col = c("#ffd9d9", "#d9ecff"),
mark.border = c("tomato", "steelblue"),
mark.shape = 1 / 2,
mark.expand = 20,
mark.lwd = 2
)
Annotations and frame
Plot-level titles and axes follow base graphics conventions:
main, sub, xlab,
ylab, axes and frame.plot.
plot(
g,
vertex.size = 25,
main = "Friendship network",
sub = "an igraph example",
xlab = "x",
ylab = "y",
axes = TRUE,
frame.plot = TRUE
)
Custom vertex shapes
You can register your own shape with add_shape(). A
shape is defined by a clip function (where edges stop) and a
plot function (how the vertex is drawn);
shape_noclip and shape_noplot are no-op
building blocks, and shapes("circle")$clip reuses an
existing clipper. The plot function receives the coordinates and
params, a function to look up plotting parameters; it may
also take v, the vertex being drawn when vertices are drawn
one at a time.
mytriangle <- function(coords, v = NULL, params) {
vertex.color <- params("vertex", "color")
if (length(vertex.color) != 1 && !is.null(v)) {
vertex.color <- vertex.color[v]
}
vertex.size <- params("vertex", "size")
if (length(vertex.size) != 1 && !is.null(v)) {
vertex.size <- vertex.size[v]
}
# When all vertices share a shape, the plot function is called once for the
# whole layout (with v = NULL), so recycle scalars to one value per row.
vertex.size <- rep(vertex.size, length.out = nrow(coords))
symbols(
x = coords[, 1], y = coords[, 2], bg = vertex.color,
stars = cbind(vertex.size, vertex.size, vertex.size),
add = TRUE, inches = FALSE
)
}
add_shape("triangle", clip = shapes("circle")$clip, plot = mytriangle)
plot(
g,
vertex.shape = "triangle",
vertex.color = "seagreen",
vertex.size = 40
)
shape_noclip (edges run all the way to the centre) and
shape_noplot (draw nothing) are the no-op building blocks;
registering a shape from them gives an “invisible” vertex that still
carries a label:
add_shape("blank", clip = shape_noclip, plot = shape_noplot)
plot(g, vertex.shape = "blank", vertex.label.dist = 0)
Setting defaults
igraph_options() sets defaults for every subsequent
plot, and igraph_opt() reads one back. Plotting options use
the same vertex. / edge. prefixes:
old <- igraph_options(
vertex.color = "orange",
vertex.size = 30,
edge.color = "grey70"
)
plot(g)
igraph_opt("vertex.color") # read one option back
#> [1] "orange"
igraph_options(old) # restoreThe full precedence order, from highest to lowest, is:
- an explicit argument to
plot(), - a vertex/edge/graph attribute,
- an
igraph_options()setting, - the built-in default.
Setting igraph_options(annotate.plot = TRUE) makes
plot() annotate the figure with the graph’s name and its
vertex/edge counts by default.
SVG export with tooltips
as_svg() renders a graph to a standalone SVG. Beyond
crisp vector output, it tags each vertex and edge with element IDs and a
<title>, so the SVG has hover tooltips with
no JavaScript dependency. It takes the same plotting
parameters as plot(), scale legends, line types and label
fonts included. The tooltips argument picks which vertex
attribute to use for the titles (defaulting to the vertex name), and
file writes the SVG to a file.
tmp <- tempfile(fileext = ".svg")
svg <- as_svg(g, file = tmp, width = 6, height = 6, tooltips = "gender")
substr(svg, 1, 60)
#> [1] "<svg xmlns='http://www.w3.org/2000/svg' width='432' height='"Each vertex becomes
<g id="vertex-N"><title>...</title>...</g>
and each edge a matching group, so downstream tools (or a browser) can
offer hover and click interactions. Embedded directly into this page,
hovering a vertex shows its tooltip:
cat(as_svg(
g,
vertex.size = 30,
vertex.color = scale_vertex_color(V(g)$gender, name = "Gender"),
width = 6,
height = 6,
tooltips = "gender"
))as_svg() records what igraph draws itself. Axes and
titles are left out, and so is anything a custom shape draws by calling
base graphics directly (like the triangle above).
Where to go next
- The per-function reference: https://r.igraph.org/reference/, in particular
?plot.igraphand?igraph.plottingfor the full list of parameters. - The main igraph introduction for graph construction and analysis.

