# Color the nodes according to certain values

I have a simple graph, consisting 6 nodes and the connection is:

node = {{1, 2}, {2, 3}, {2, 4}, {4, 5}, {5, 6}, {3, 6}};


Each node corresponds to a weight, assuming it is

weight={1,2,3,4,5,6}


Now I want to plot this graph, showing the actual number on each node and assign the node color based on the weight. (If possible, I also would like to assign the color of the connection line with colors, changing smoothly from one node to another).

Here is a quick example of coloring both vertices and edges with specified colors, along with the additional stipulation that an edge's color should transition between the colors of its associated vertices:

edges = {{1, 2}, {2, 3}, {2, 4}, {4, 5}, {5, 6}, {3, 6}};
weight = Range[6];
cols = ColorData[61] /@ weight;

Graph[UndirectedEdge @@@ edges,
EdgeShapeFunction -> ({AbsoluteThickness[4],
Line[#1, VertexColors -> cols[[List @@ #2]]]} &),
VertexSize -> Medium, VertexStyle -> Thread[Range[6] -> cols]]


• This is great. One more question, is it possible to label the circle with their number and also add a color bar on the right side of the figure? Commented Aug 28, 2017 at 4:40
• ...shouldn't you have included those in the question in the first place? :| Anyway, look up VertexLabels and PointLegend[]. Commented Aug 28, 2017 at 4:44
• :-) thanks. This is really helpful! Commented Aug 28, 2017 at 4:45
• Sorry to bother you again but I cannot figure out how to use PoingLegrnd[]😂 Commented Aug 28, 2017 at 6:29
• Try Legended[(* stuff *), PointLegend[cols, weight]]. Commented Aug 28, 2017 at 6:32

You can use rules to specify colors and VertexStyle to color the nodes, e.g.

col = Range[6] /. {1 -> Red, 2 -> Green, 3 -> Blue, 4 -> Purple,
5 -> Orange, 6 -> White};
Legended[Graph[UndirectedEdge @@@ node,
VertexStyle -> Thread[Range[6] -> col], VertexSize -> 0.2],
PointLegend[col, Range[6],
LegendMarkers -> Graphics[{EdgeForm[Black], Disk[]}],
LegendMarkerSize -> 20]]


There is a package to make your life easer

<< IGraphM
node = {{1, 2}, {2, 3}, {2, 4}, {4, 5}, {5, 6}, {3, 6}};
weight = {1, 2, 3, 4, 5, 6};
IGVertexMap[ColorData[97], VertexStyle -> IGVertexProp[VertexWeight],
Graph[UndirectedEdge @@@ node, VertexWeight -> weight]]


If the weight which are used for colouring are not integers, it is useful to Rescale them:

IGVertexMap[ColorData["MintColors"], VertexStyle -> Rescale@*IGVertexProp[VertexWeight],
Graph[UndirectedEdge @@@ node, VertexWeight -> weight]]
`