hmnoidk
hmnoidk

Reputation: 565

How to make a legend for vertex color attributes when colours are defined within the plot argument? (R)

I don't know how to make a reproducible example out of this. The only important thing is that I would like to make make a legend of the vertex.color argument such that the colours I am using to represent "motherinst" are shown in the legend.

plot(g, vertex.size = (V(g)$poly_area*1.25), arrow.size = 0.5, arrow.width = 0.1, vertex.label = V(g)$poly_area, vertex.color = color[as.numeric(as.factor(vertex_attr(g, "motherinst")))], curved = TRUE)

I tried adding colours to the graph object directly but that won't seem to work for me either.

Upvotes: 1

Views: 1203

Answers (1)

Vincent Guillemot
Vincent Guillemot

Reputation: 3429

I would use the function legend.

First make a reproducible graph:

require(igraph)
g <- graph_from_atlas(523)

I need to know the number of vertices, let's call it n

n <- length(V(g))

Then I create an arbitrary factor that describes a certain property of each node, and assign a color to each node according to this factor. I did not really know what the poly_area property was, so I just got creative...

f <- factor(rep(LETTERS[1:2], length = n))
V(g)$poly_area <- V(g) ** 2
vcols <- c("#F8766D", "#00BFC4")[f]

The call to the plottting function is the same (only simplified a little bit for clarity)...

plot(g, vertex.size = (V(g)$poly_area + 10), vertex.label = V(g)$poly_area, vertex.color = vcols)

... and a legend can be added with legend

legend("topleft", legend = levels(f), pch = 16, col = vcols, bty = "n")

And here is the result !

Graph with legend

Upvotes: 4

Related Questions