Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add legend in igraph to annotate difference vertices size

Tags:

r

legend

igraph

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?

like image 368
itamar kanter Avatar asked Dec 18 '22 15:12

itamar kanter


1 Answers

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.

like image 195
digEmAll Avatar answered Mar 09 '23 00:03

digEmAll