# Coloring edges of a graph according to their weight?

What's the simplest way to plot a graph with weighted edges, such that the color of the edge corresponds to the weight of the edge?

-
Why the downvote? Please leave a comment – becko Sep 2 '14 at 19:04
The evildoer was me, because I felt that an estimated contributor like yourself should have shown some own efforts. – eldo Sep 2 '14 at 19:32
@eldo I really did not know how to get started, so I had nothing to show. – becko Sep 2 '14 at 20:01
Accepted @ becko – eldo Sep 2 '14 at 20:06

Update: If the graph g1 is already created, I think SetOptions is the most convenient way to make changes in g1:

g1 = Graph[{1 <-> 2, 2 <-> 3, 3 <-> 1}, EdgeWeight -> {2, 3, 4}];
ew = PropertyValue[g1, EdgeWeight];
el = EdgeList[g1];
edgestylea = Thread[el -> (Directive[CapForm["Round"],
Thickness[Rescale[# , Through@{Min, Max}@ew, {0.02, .06}]],
ColorData[1, #]] & /@ ew)];
edgestyleb = Thread[el -> (Directive[CapForm["Round"],
Thickness[.02 + .04 #], (* or Thickness[Rescale[#, {0,1}, {.02,.06}]] *)
ColorData["SolarColors"][#]] & /@ Rescale[ew])];

g1a = SetProperty[g1, EdgeStyle -> edgestylea];
g1b = SetProperty[g1, EdgeStyle -> edgestyleb];
Row[{g1a, g1b}]


If not, you can directly use the edge-weight information for styling edges:

el = {1 <-> 2, 2 <-> 3, 3 <-> 1};
ew = {2, 3, 4};
edgestylea = Thread[el -> (Directive[CapForm["Round"],
Thickness[Rescale[# , Through@{Min, Max}@ew, {0.02, .06}]],
ColorData[1, #]] & /@ ew)];
edgestyleb = Thread[el -> (Directive[CapForm["Round"],
Thickness[.02 + .04 #],
ColorData["SolarColors"][#]] & /@ Rescale[ew])];

g2a = Graph[el, EdgeWeight -> ew, EdgeStyle -> edgestylea];
g2b = Graph[el, EdgeWeight -> ew, EdgeStyle -> edgestyleb];
Row[{g2a, g2b}]
(* same picture *)


Original Post

One possible approach: use the EdgeWeight PropertyValue of an edge with EdgeStyle

g = Graph[{1 <-> 2, 2 <-> 3, 3 <-> 1}, EdgeWeight -> {2, 3, 4},
EdgeStyle -> {e_ :>
Directive[Thick, ColorData[1, PropertyValue[{g, e}, EdgeWeight]]]}]


Or

h = Graph[{1 <-> 2, 2 <-> 3, 3 <-> 1}, EdgeWeight -> {2, 3, 4}];
SetProperty[h, EdgeStyle -> Thread[EdgeList[h] ->
(Directive[Thick, ColorData[1, #]] & /@  PropertyValue[h, EdgeWeight])]]
(* same picture *)

-
Nice. I didn't realise you could use patterns in EdgeStyle. FYI you can use <-> for a slightly more readable UndirectedEdge. – Simon Woods Sep 2 '14 at 19:16
Thank you @Simon. I cannot find this usage pattern in the docs; I must have learned it somewhere on this site. – kglr Sep 2 '14 at 19:33