Dale Pin
Dale Pin

Reputation: 61

Synchronise colors between plot and legend

I have this command to produce a network graph from igraph:

plot(ig, layout=layout.fruchterman.reingold(ig),vertex.label=NA,vertex.label.color="black",vertex.frame.color="black",edge.color="black", vertex.color=rainbow(9)[data2$Group], main="MB Network")

The data2 is another object containing information on groupings of the vertices in the igraph object ig. I wanted to color the vertices by their groupings and then put a legend for group color guidelines so I used the command:

legend("topleft",legend=unique(data2$Group),col=rainbow(9)[data2$Group])

However, the colors used in the legend does not match with the colors of the plot. How should I correct this?

Upvotes: 2

Views: 4305

Answers (3)

Dale Pin
Dale Pin

Reputation: 61

Thank you, everyone for your inputs!

I somehow corrected the problem by using fill=rainbow(9)[unique(data2$Group)] for the legend.

Upvotes: 1

Vincent Guillemot
Vincent Guillemot

Reputation: 3429

I agree with @Resh that RColorBrewer provides excellent color palettes !

Here is an example on a famous cubical graph

require(igraph)
require(RColorBrewer)

I would externally define the palette first, I chose four colors in the palette called "Accent". Each one of the color is then associated to the eight vertices according to a factor called Group. The levels of the factor are set on purpose to G, P, O and Y because the colors are green, purple, orange and yellow. This will help us know if the colors are right in both the graph and the legend.

pal <- brewer.pal(4,"Accent")
g <- make_graph("Cubical")
Group <- gl(4, 2, labels = c("G","P","O","Y"))
vertex.col <- pal[Group]

plot(g, 
     layout=layout.fruchterman.reingold(g),
     vertex.label.color="black",
     vertex.frame.color="black",
     edge.color="black", 
     vertex.color=vertex.col, 
     main="Cubical")

legend("topleft",bty = "n",
       legend=levels(Group),
       fill=pal, border=NA)

And the result...

Cubical example with legend

Upvotes: 1

Resh
Resh

Reputation: 153

There is a package I have used in past called RColorBrewer which creates color pallets for you. Have you taken a look at it?

Once the colors are matched or same then the legend will also be of the same color.

Hope this helps.

Upvotes: 0

Related Questions