Coloring edges of a graph according to their weight?
Update: If the graph g1
is already created, I think SetProperty
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 *)
What's the simplest way...
I think the simplest way is with the IGraph/M package.
ExampleData[{"NetworkGraph", "EastAfricaEmbassyAttacks"}] //
Graph[#, EdgeStyle -> AbsoluteThickness[5]] & // (* thicken edges *)
IGEdgeMap[ColorData["Rainbow"], EdgeStyle -> Rescale@*IGEdgeProp[EdgeWeight]] (* colour edges *)
Notice how setting EdgeStyle
individually for each edge (to colour them) did not remove the global EdgeStyle
setting that adjusts thickness. I am pointing this out because this behaviour is far from obvious (in fact to me it is counterintuitive), but it can be very useful.
The setting stored inside the graph looks like this: