Update: In Mathematica 12.0, Subgraph
preserved edge weights.
IGraph/M has a function to do this since version 0.3.97. Unlike the method using adjacency matrices, this function will also handle weighted multigraphs.
Thus, use IGWeightedSubgraph
instead of Subgraph
. Note that the second argument can only be a list of vertices. Unlike in Subgraph
, edges and patterns are not currently supported.
This function is fast (partly implemented in C), but it preserves edge weights only. All other properties are discarded.
If you need to preserve all properties, use IGTake
. IGTake[graph, subgraph]
takes the vertices and edges of graph
that are also present in subgraph
and preserves all graph properties.
Examples
<< IGraphM`
IGraph/M 0.3.97.1 (February 4, 2018)
Evaluate IGDocumentation[] to get started.
g = ExampleData[{"NetworkGraph", "EastAfricaEmbassyAttacks"}]
vs = {"Osama", "Salim", "Abdullah", "Hage", "Abouhlaima", "Owhali"};
sg1 = Subgraph[g, vs]
The graph returned by Subgraph
is not weighted:
IGEdgeWeightedQ[sg1]
(* False *)
IGWeightedSubgraph
returns a weighted result, but all the original styling is lost.
sg2 = IGWeightedSubgraph[g, vs]
IGEdgeWeightedQ[sg2]
(* True *)
IGTakeIGTakeSubgraph
preserves all properties (and styling), but it is much slower than IGWeightedSubgraph
.
sg3 = IGTake[g, Subgraph[g, vs]]
IGEdgeWeightedQ[sg3]
(* True *)
Verify that the edge weights in the subgraphs are correct.
Function[graph,
PropertyValue[{graph, #}, EdgeWeight] & /@ EdgeList[sg1]
] /@ {g, sg2, sg3}
(* {{0.52, 0.48, 0.48, 0.36, 0.36, 0.36, 0.48, 0.16},
{0.52, 0.48, 0.48, 0.36, 0.36, 0.36, 0.48, 0.16},
{0.52, 0.48, 0.48, 0.36, 0.36, 0.36, 0.48, 0.16}} *)
Equal @@ %
(* True *)