# Vertex relabeling. Ordering from top left in GridGraph

I have a grid graph

GridGraph[{15,15},VertexLabels->"Name"]


which gives the following but I want the vertex number starts from top left going to right all the way down.

Is there any way or specific rule to order the vertex number from Left to Right? ## VertexCoordinates

You can define arbitrary VertexCoordinates

GridGraph[
{15, 15}
, VertexLabels -> "Name"
, VertexCoordinates -> Flatten[Table[{j, 15 - i}, {i, 15}, {j, 15}], 1]
] ## Untidy with RandomReal

GridGraph[
{15, 15}
, VertexLabels -> "Name"
, VertexCoordinates ->
Flatten[Table[{j + RandomReal[{-0.1, 0.1}], 15 - i + RandomReal[{-0.1, 0.1}]}, {i, 15}, {j, 15}], 1]
] Code and plots done in Mathemathica 11.1.1 on Win7

@rhermans already gave a good answer. I just want to show how to easily transform existing vertex coordinates using the IGraph/M package:

<< IGraphM

g = GridGraph[{15, 15}, VertexLabels -> "Name"];


Reverse the x and y coordinates:

IGVertexMap[Reverse, VertexCoordinates, g] Rotate clockwise by 90 degrees:

IGVertexMap[RotationTransform[-90 Degree], VertexCoordinates, g] With IGraph/M, you can apply any function you like to the vertex coordinates (or other graph property) using a one-liner.

Without IGraph/M a general property transformation is usually messier, but the VertexCoordinates can be retrieved or set in a single go on some graphs, which makes this easier here:

SetProperty[
g,
VertexCoordinates -> RotationTransform[-Pi/2]@GraphEmbedding[g]
]


There are some good answers already. However, those answer rely a bit on the structure of the graph to produce the ordering you want. Suppose you had an arbitrary graph, and you wanted to change the vertex number (or node values) so that vertices are sorted so that a vertex with coordinate $(x_1, y_1)$ comes before a vertex with $(x_2, y_2)$ if:

1. $y_2 > y_1$
2. Or, if $y_2 = y_1$, then $x_1 < x_2$

(recall that larger $y$ values correspond to vertices that are higher up the page). To do this, I will use the following ranking function:

ranking[coords_] := Ordering @ Ordering[ coords . {{0, 1}, {-1, 0}} ]


Here is a test case:

ranking[{{2,1}, {3,1}, {1, 2}, {2, 2}}]


{3, 4, 1, 2}

Now, all we need to do is to get the coordinates of the vertices (GraphEmbedding), and replace the vertices based on the above ranking function. The function to use for this is VertexReplace, but VertexReplace does not do what we want when the initial vertex list and the final vertex list share common values. Hence, we need to use VertexReplace in two steps:

reorderVertices[g_] := With[{e = GraphEmbedding[g]},
VertexReplace[

reorderVertices @ GridGraph[{15, 15}, VertexLabels->"Name"]
` 