4
$\begingroup$

The following code produces a graph with vertices N1, N2, and Nw colored yellow, and vertices Fx, Fz, F3, F4 and F5 colored red. For this, I used VertexStyle. However, separately listing each vertex in VertexStyle is not efficient for a graph with thousands of N and F vertices.

Is there an automated way to color vertices by the first letter in their name, i.e. the "N" and the "F"?

edges = {N1 -> N2, N2 -> Nw, Fx -> N3, Fx -> F4, N1 -> F4, N1 -> Fz, 
   N2 -> F3, N2 -> F4, F3 -> F4, F4 -> F5};
Graph[
 edges, 
 GraphLayout -> {"LayeredDigraphEmbedding", "Orientation" -> Left}, 
 VertexLabels -> Placed["Name", Center], VertexSize -> 0.35, 
 VertexStyle -> 
  {Fx | Fz | F3 | F4 | F5 -> Red, 
   N1 | N2 | Nw -> Yellow}
]
$\endgroup$

1 Answer 1

6
$\begingroup$

You can use patterns in VertexStyle:

VertexStyle ->
 {
   _?(StringPart[SymbolName[#], 1] === "N" &) -> Yellow,
   _?(StringPart[SymbolName[#], 1] === "F" &) -> Red
 }

So your code would become:

edges = {N1 -> N2, N2 -> Nw, Fx -> N3, Fx -> F4, N1 -> F4, 
         N1 -> Fz, N2 -> F3, N2 -> F4, F3 -> F4, F4 -> F5};

Graph[edges, 
  GraphLayout -> {"LayeredDigraphEmbedding", "Orientation" -> Left}, 
  VertexLabels -> Placed["Name", Center], VertexSize -> 0.35, 
  VertexStyle ->
  {
    _?(StringPart[SymbolName[#], 1] === "N" &) -> Yellow,
    _?(StringPart[SymbolName[#], 1] === "F" &) -> Red
  }
]

colored vertices by pattern

$\endgroup$
2
  • $\begingroup$ MarcoB: I tried it from looking at it as a String but could not get there as you did ... very helpful and many thanks for sharing your skills!! $\endgroup$
    – user42700
    Commented Sep 14, 2022 at 16:27
  • $\begingroup$ @PRG I'm glad it helped! The only snag the fact that N1 is not yet a string, but a symbol, so you have to convert it to a string first. Or you could change your vertex names to strings in the definition of the graph (e.g. {"N1" -> "N2", ...}, but that may well be far more work. $\endgroup$
    – MarcoB
    Commented Sep 14, 2022 at 16:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.