I need to add either a vertex or an edge to a graph, and also sometimes, vertices or edges, or a mixture of the two. How to write a function for this?
1 Answer
$\begingroup$
$\endgroup$
9
Update: Can I add a mixture list of vertices and edges to an existing graph?
ClearAll[addToGraph]
addToGraph[g_Graph, stuffToAdd_] := Fold[
If[Head[#2] === UndirectedEdge || Head[#2] === DirectedEdge, EdgeAdd, VertexAdd]@ ## &,
g, stuffToAdd]
Example:
g = Graph[{a, b, c}, {a <-> b, b <-> c, c <-> a},
VertexLabels -> Placed["Name", Center], VertexSize -> Scaled[.1],
VertexLabelStyle -> 18, AspectRatio -> 1];
addToGraph[g, {d, d <-> a, e, h <-> a}]
Original answer:
The functions you need are VertexAdd
, EdgeAdd
, and their relatives VertexDelete
and EdgeDelete
.
For the graph
g = Graph[{a, b, c}, {a <-> b, b <-> c, c <-> a},
VertexLabels -> Placed["Name", Center], VertexSize -> Scaled[.1],
VertexLabelStyle -> 18, AspectRatio -> 1]
Adding a vertex
VertexAdd[g, d]
Adding an edge
EdgeAdd[g, d <-> a]
Deleting an edge
EdgeDelete[g, c <-> a]
-
$\begingroup$ Can I add a mixture list of vertices and edges to an existing graph? How to write such a function
addToGraph[g, {4, 1 \[UndirectedEdge] 2}]
which will add another vertex4
and an edge between1
and2
? Thank you. $\endgroup$– Qiang LiCommented Feb 17, 2012 at 23:16 -
2$\begingroup$ I don't know of a built-in function that does that. But, it seems straightforward to do define a composite function that does both:
addToGraph[g_, newvertices_List, newedges_List]:= (VertexAdd[g,newvertices];EdgeAdd[g,newedges];)
. Use it ash=addToGraph[g,{d,e},{a->d,a->e}]
to add two new vertices and two new edges to graphg
to get a new graphh
. $\endgroup$– kglrCommented Feb 17, 2012 at 23:35 -
$\begingroup$ I guess I wanted to know what if I mixed the
newvertices_List
andnewedges_List
in a single list? $\endgroup$– Qiang LiCommented Feb 18, 2012 at 0:20 -
1$\begingroup$ @QiangLi, you need modify slightly to parse the new stuff into vertex and edge parts. For example, let
newstuff = {a, a \[UndirectedEdge] b, b \[UndirectedEdge] e, d, b}
. Then, you can usenewedges=Cases[newstuff, _ \[UndirectedEdge] _]; newvertices = Complement[newstuff, newedges]
as the first two steps of the composite function on the right hand side. That is, the function becomes `addToGraph2[g_, newstuff_]:=(newedges=Cases[newstuff, _ \ [UndirectedEdge] _]; newvertices = Complement[newstuff, newedges]; VertexAdd[g,newvertices];EdgeAdd[g,newedges];). $\endgroup$– kglrCommented Feb 18, 2012 at 0:52 -
2$\begingroup$ @Shamina, replace
{d, d <-> a, e, h <-> a}
with{d, d \[UndirectedEdge] a, e, h \[UndirectedEdge] a}
$\endgroup$– kglrCommented Jul 2, 2021 at 10:10