5
$\begingroup$

I was trying to set (change) a vertex coordinate this way:

g = Graph@{1 -> 2, 2 -> 3, 3 -> 1, 1 -> 4}
SetProperty[{g, 1}, VertexCoordinates -> {0.25, 1}]

But failed. At the same time this works nicely

SetProperty[{g, 1}, VertexLabels -> 1]

Both propeties are in this list

PropertyList[{g, 1}]

Could you explain what my mistake is? And how to change vertex coordinate using SetProperty?

$\endgroup$
5
$\begingroup$

By default, the graph is laid out automatically. No explicit vertex coordinates are stored.

If you decide to store vertex coordinates, you must do so for all vertices. Currently, the built-in layout algorithms do not support fixing the position of only a subset of vertices. Once explicit coordinates are set for all vertices, SetProperty works for changing only one at a time.

g = Graph@{1 -> 2, 2 -> 3, 3 -> 1, 1 -> 4};

These work:

g2 = SetProperty[g, 
  VertexCoordinates -> {{0, 0}, {0, 1}, {1, 0}, {1, 1}}]

g3 = SetProperty[g, 
  VertexCoordinates -> {1 -> {0, 0}, 2 -> {0, 1}, 3 -> {1, 0}, 4 -> {1, 1}}]

g4 = Graph[g, 
  VertexCoordinates -> {1 -> {0, 0}, 2 -> {0, 1}, 3 -> {1, 0}, 4 -> {1, 1}}]

This does not:

SetProperty[{g, 1}, VertexCoordinates -> {2, 2}]

This one does:

SetProperty[{g2, 1}, VertexCoordinates -> {2, 2}]

Update

If you want to keep the positions you currently see, and move a single vertex, I recommend

g = Graph@{1 -> 2, 2 -> 3, 3 -> 1, 1 -> 4}

enter image description here

g = Graph[g, VertexCoordinates -> GraphEmbedding[g]];
PropertyValue[{g, 1}, VertexCoordinates] = {0.25, 1}

g

enter image description here

This will modify the graph in-place.

$\endgroup$
2
  • $\begingroup$ Thank you. So, to change coordinates of a subset of vertices I have to do something like this coords = PropertyValue[{g, #}, VertexCoordinates] & /@ VertexList[g] and then SetProperty[g, VertexCoordinates -> ReplacePart[coords, 2 -> {1, 1}]] $\endgroup$ – Gregory Fridman Jan 7 '18 at 15:22
  • $\begingroup$ @GregoryFridman You can do that, but I would do the following. First, g = Graph[g, VertexCoordinates -> GraphEmbedding[g]] to set explicit (not automatic) coordinates for all vertices. Then you can use SetProperty to modify just one vertex in the same way as you tried in the question. $\endgroup$ – Szabolcs Jan 7 '18 at 16:10

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.