3
$\begingroup$

I'm using AdjacencyGraph to plot a graph corresponding to an undirected, unweighted 5-node network. Each node is assigned a different color. Here's what I have so far:

A = {{0, 1, 1, 0, 0}, {1, 0, 1, 0, 0}, {1, 1, 0, 1, 1}, {0, 0, 1, 0, 
1}, {0, 0, 1, 1, 0}};
Labels = {1, 2, 3, 4, 5};
VertexNames = Table[i -> Labels[[i]], {i, 5}];
col = Range[5] /. {1 -> Red, 2 -> Green, 3 -> Blue, 4 -> Purple, 
5 -> Orange};
G = AdjacencyGraph[A, VertexLabels -> VertexNames, 
VertexStyle -> Thread[Range[5] -> col], VertexSize -> Medium, 
VertexLabelStyle -> Large]

Mathematica graphics

This does exactly as I would expect. However, now I want to assign colors based upon a partition of the vertices. For example, suppose I have {{1,3,4},{2,5}} and I would like for the nodes in each of the two lists to be colored identically.

I'm not doing this for purposes of plotting a community partition as one would be using the CommunityGraphPlot command.

I do have IGraph/M installed if there's any easy way to accomplish this using it.

$\endgroup$
3
$\begingroup$

HighlightGraph?:

HighlightGraph[G, {{1, 3, 4}, {2, 5}}]

HighlightGraph[G, {Style[{1, 3, 4}, Blue], Style[{2, 5}, Orange]}]
$\endgroup$
3
$\begingroup$

Use HighlightGraph.

g = AdjacencyGraph[A, VertexSize -> Medium]

HighlightGraph[g, {{1, 3, 4}, {2, 5}}]

enter image description here

HighlightGraph[g, {Style[{1, 3, 4}, Blue], Style[{2, 5}, Red]}]

enter image description here

HighlightGraph[g, {Labeled[{1, 3, 4}, "A", Center], 
  Labeled[{2, 5}, "B", Center]}, VertexLabelStyle -> White]

enter image description here


There are alternative ways to do this with IGraph/M, but in this case I recommend using the built-in HighlightGraph (unless you have a good reason not to).

IGVertexMap[
 ColorData[97],
 VertexStyle -> (IGPartitionsToMembership[VertexList[#], {{1, 3, 4}, {2, 5}}] &),
 g
]

enter image description here

$\endgroup$
1
$\begingroup$

First, I would like to change the labels to emphasize that they are not the same as vertex nodes in what follows:

labels = {11, 12, 13, 14, 15};
vertexNames = MapIndexed[First[#2] -> # &, labels];

Color specification for nodes is given in this format:

{1 -> Red, 2 -> Red, 3 -> Red, 4 -> Blue, 5 -> Blue}

We can create this list in the following way:

groups = {{1, 2, 3}, {4, 5}};
colors = Flatten@MapThread[Thread@*Rule, {groups, {Red, Blue}}];

where Thread@*Rule is the same as Thread[# -> #2] &.

We can now display the graph with this coloring:

AdjacencyGraph[
 A,
 VertexLabels -> vertexNames,
 VertexSize -> Medium,
 VertexLabelStyle -> Large,
 VertexStyle -> colors
 ]

Mathematica graphics

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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