itamar kanter
itamar kanter

Reputation: 1360

Add legend in igraph to annotate difference vertices size

I have a graph in igraph with a vertex size that is coded for a value.
I wish to add a legend with symbols (points in my case) with different sizes. I tried the following code

require(igraph)
er_graph <- erdos.renyi.game(100, 5/100)
value<-runif(100)
n<-6
size_vec<-seq_len(n)
sizeCut<-cut(value,n)
vertex.size<-size_vec[sizeCut]
plot(er_graph, vertex.label=NA, vertex.size=vertex.size)
legend('topleft',legend=levels(sizeCut),pt.cex=size_vec,col='black')

but end with legend without symbols see example

Any sugestions how I go about this?

Upvotes: 5

Views: 14557

Answers (2)

unknown
unknown

Reputation: 883

Anyone looking at this who wants a continuous scale for node sizes instead of a discrete scale then this is the code you need to do it:

require(igraph)
er_graph <- erdos.renyi.game(100, 5/100)
value<-runif(100)
sizeCut<- c(0.2,0.4,0.6,0.8,1.0)
sizeCutScale <- sizeCut*10
vertex.size<-value*10
plot(er_graph, vertex.label=NA, vertex.size=vertex.size)
legend('topleft',legend=unique(sizeCut),pt.cex= sizeCutScale,col='black')
a <- legend('topleft',legend=unique(sizeCut),pt.cex=sizeCutScale/200,col='white',
            pch=21, pt.bg='white')
x <- (a$text$x + a$rect$left) / 2
y <- a$text$y
symbols(x,y,circles=sizeCutScale/200,inches=FALSE,add=TRUE,bg='orange')

enter image description here

Upvotes: 1

digEmAll
digEmAll

Reputation: 57210

You should set pch to some value to indicate which character you want to use for the bullets (see ?points to check the possible values).
Also, you should scale the pt.cex values in order to make the bullets not too big for the legend, and use pt.bg to set the background color of the bullets, e.g.

# scaled between 1 and 2
scaled <- 1 + ((2-1) * (size_vec - min(size_vec) ) / (  max(size_vec) - min(size_vec) ) )
legend('topleft',legend=levels(sizeCut),pt.cex=scaled,col='black',pch=21, pt.bg='orange')

enter image description here

EDIT :

Unfortunately, calculating the right sizes of the bullets is not easy; a possible workaround is plotting white bullets then manually add the vertices to the legend in the same way they are plotted inside the plot.igraph function :

# N.B. /200 is taken from plot.igraph source code
a <- legend('topleft',legend=levels(sizeCut),pt.cex=size_vec/200,col='white',
            pch=21, pt.bg='white')
x <- (a$text$x + a$rect$left) / 2
y <- a$text$y
symbols(x,y,circles=size_vec/200,inches=FALSE,add=TRUE,bg='orange')

enter image description here

Disclaimer: this code heavily relies on the source code of plot.igraph function that might be changed in a future version of igraph. Probably you should search for another plot function for igraph which natively allows to add a legend.

Upvotes: 10

Related Questions