问题
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?
回答1:
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...
回答2:
There is a package I have used in past called RColorBrewer which creates color pallets for you. Have you taken a look at it?
- http://earlglynn.github.io/RNotes/package/RColorBrewer/index.html
- https://moderndata.plot.ly/create-colorful-graphs-in-r-with-rcolorbrewer-and-plotly/
Once the colors are matched or same then the legend will also be of the same color.
Hope this helps.
回答3:
Thank you, everyone for your inputs!
I somehow corrected the problem by using fill=rainbow(9)[unique(data2$Group)] for the legend.
来源:https://stackoverflow.com/questions/46197910/synchronise-colors-between-plot-and-legend