Piotr Wilczek
Piotr Wilczek

Reputation: 197

How to label connected components in a disconnected graph?

I have some disconnected graph composed of three connected components. This graph is produced by the following commands in the igraph R:

library(igraph)
x1 <- c(1:7, 2, 8:14, 10, 15:21, 18)
x2 <- c(rep(0, 7), 1, rep(0, 7), 1, rep(0, 7), 1)
m <- cbind(x1, x2)
g <- graph.formula(1-2, 2-3, 3-4, 4-5, 5-6, 6-7, 2-8,
                   9-10, 10-11, 11-12, 12-13, 13-14, 14-15, 11-16,
                   17-18, 18-19, 19-20, 20-21, 21-22, 22-23, 20-24)
plot(g, layout = m, rescale = F, xlim = c(0.5, 21.5), vertex.size = 20,
     vertex.label = NA, edge.color = "black", vertex.color = "black")

The resulting disconnected graph is plotted below: enter image description here

I want to label every disconnected components by a letter, for instance "A", "B" and "C". Alternatively, I want to make some subtitles for every connected components in the igraph R ?

Upvotes: 1

Views: 238

Answers (1)

Henrik
Henrik

Reputation: 67828

Use components to get the cluster id. To center labels horizontally within each id, use tapply to calculate the midpoint of x values in 'm'. For the vertical position, use min of the y values and a suitable offset. Use text to add labels.

m <- cbind(m, id = components(g)$membership)
xs <- tapply(m[ , "x1"], m[ , "id"], function(x) mean(range(x)))
ys <- tapply(m[ , "x2"], m[ , "id"], min)
plot(g, layout = m, rescale = F, xlim = c(0.5, 21.5), vertex.size = 20,
     vertex.label = NA, edge.color = "black", vertex.color = "black")
text(xs, ys - 0.6, LETTERS[1:3])

enter image description here

Upvotes: 2

Related Questions