Mohammad
Mohammad

Reputation: 35

igraph : Add Shape to Edges between Communities

I used community detection in igraph to cluster a graph. what I want is to add a shape like a triangle or square in the middle of edges between communities. the edges between communities already have different color but I want to print in b/w, that's why I want to do this. thanks

Upvotes: 1

Views: 375

Answers (1)

G5W
G5W

Reputation: 37641

There are two parts to solving this:

  1. Finding which edges to label and
  2. adding a symbol to those edges.

This answer fully addresses part 1, but the answer to part 2 is not perfect.

Setup Basic graph and clustering

library(igraph)
g <- graph_from_literal(1-2-3-4-1, 2-5-4, 1-5,3-5,
    2-6, 1-9, 6-7-10-8-6, 6-9-10)
CL = cluster_louvain(g) 
set.seed(1234)
plot(CL, g)

Unlabeled graph

I set the random seed so that we can get the same plot later for comparison.

Part 1. Find the edges between communities

This is pretty simple. Just check whether or not the endpoints of each edge are in the same or different communities. In order to make this comparison, it is convenient to assign the cluster number of each vertex as an attribute.

## create a cluster label for each vertex
V(g)$cluster = 0
for(i in 1:length(CL)) {
    V(g)[CL[[i]]]$cluster = i }

## identify the cross-cluster edges and check
XCE = which(V(g)[ends(g, E(g))[,1]]$cluster !=
    V(g)[ends(g, E(g))[,2]]$cluster)
E(g)[XCE]
+ 2/16 edges (vertex names):
[1] 1--9 2--6

We see that this has correctly identified the edge between vertices 1 and 9 and the edge between vertices 2 and 6 as the edges that connect different communities.

Part 2 Annotate the cross-community edges

The idea here is to use the edge labels to indicate the edges between communities. The edge labels are text. If you wanted a text label, this is a full solution. But if you want a symbol, you are limited to those symbols you can make in text. I tried to use the many Unicode symbol characters with no success. A previous SO question Is there an argument to force UTF8 in igraph functions? asked how to use Unicode, but got no answer. I was successful at using extended ASCII characters. I use ¤ below, but some others to try are: ‡ ¤ • º §

## Create edge labels
EdgeLabel = rep("", ecount(g))
## Potential symbol characters:  ‡ ¤ • º §
EdgeLabel[XCE] = "¤"
set.seed(1234)
plot(CL, g, edge.label=EdgeLabel, edge.label.cex=1.5)

Labeled Graph

Upvotes: 1

Related Questions