8
$\begingroup$

Suppose I have generated the two graphs g1 and g2 below in a separate Mathematica notebook with the node colors as shown.

I then would like to copy the two graphs into a new Mathematica notebook and take their graph union; that is GraphUnion[g1,g2,VertexLabels->Automatic]; however, the graph union loses the original node colors and only produces the default grey nodes. Any recommendations?

edges1 = {NS <-> N1, NS <-> N2, N2 <-> N3, N3 <-> N1};
edges2 = {NS <-> S1, S1 <-> S3, S2 <-> N2, N2 <-> NS};
g1 = Graph[edges1, VertexLabels -> "Name", VertexLabels -> Automatic, 
  VertexSize -> 0.2, VertexStyle -> {NS | N1 | N2 -> Red, N3 -> Blue}]
g2 = Graph[edges2, VertexLabels -> "Name", VertexLabels -> Automatic, 
  VertexSize -> 0.2, 
  VertexStyle -> {S1 | S2 | S3 -> Yellow}]
$\endgroup$
6
$\begingroup$

I do not use Graph much at all. But playing with it, it looks like styling is lost when making union.

A workaround meanwhile is to do this

edges1 = {NS <-> N1, NS <-> N2, N2 <-> N3, N3 <-> N1};
edges2 = {NS <-> S1, S1 <-> S3, S2 <-> N2, N2 <-> NS};
vs1 = {NS | N1 | N2 -> Red, N3 -> Blue};
vs2 = {S1 | S2 | S3 -> Yellow};
g1 = Graph[edges1, VertexLabels -> "Name", VertexLabels -> Automatic, 
  VertexSize -> 0.2, VertexStyle -> vs1]
g2 = Graph[edges2, VertexLabels -> "Name", VertexLabels -> Automatic, 
  VertexSize -> 0.2, VertexStyle -> vs2]

Mathematica graphics

Now

GraphUnion[g1, g2, VertexLabels -> "Name", VertexSize -> 0.2, VertexStyle -> Join[vs1, vs2]]

Mathematica graphics

i.e need to apply styles manually again. This seems like a feature limitation. May be submit feature request to WRI on this by emailing support@wolfram.com

|improve this answer|||||
$\endgroup$
2
$\begingroup$
ClearAll[grUnion]
grUnion = GraphUnion[##, 
    Normal@GroupBy[Join @@ (Options /@ {##}), First -> Last, Apply[Union]]] &;

grUnion[g1, g2]

enter image description here

You can add new options and/or replace existing one using Graph[grUnion[g1,g2], options]:

Graph[grUnion[g1, g2],
 VertexLabels -> Placed["Name", Center], 
 VertexLabelStyle -> {Alternatives @@ VertexList[g1] -> White},
 ImageSize -> Large]

enter image description here

|improve this answer|||||
$\endgroup$
  • $\begingroup$ very clever kglr ... I like the node labels inside; many thanks again! $\endgroup$ – PRG Feb 29 at 17:55

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.