Creating hexagonal grid (hexagonal grid graph)
With IGraph/M:
IGMeshGraph@IGLatticeMesh["Hexagonal", {6, 4}]
We can also crop it to a hexagon:
IGMeshGraph@IGLatticeMesh["Hexagonal", Polygon@CirclePoints[10, 6]]
It can also generate many other kinds of lattices, not just hexagonal.
Here is my generalization of the code from link provided by @LouisB:
HexagonalGridGraph2[{wide1_Integer?Positive, wide2_Integer?Positive,
wide3_Integer?Positive}, opts : OptionsPattern[Graph]] :=
Module[{cells, edges, vertices},
cells =
Flatten[Table[
CirclePoints[{Sqrt[3] (1 j + k - 2 ) + Sqrt[3] (1 j + l - 2 ),
3 k - 2 - 3 l}, {2, \[Pi]/2}, 6], {j, wide1}, {k, wide2}, {l,
wide3}], 2];
edges = Union[Sort /@ Flatten[Partition[#, 2, 1, 1] & /@ cells, 1]];
vertices = Union[Flatten[edges, 1]];
IndexGraph[
Graph[UndirectedEdge @@@ edges, opts,
VertexCoordinates -> Thread[vertices -> vertices]]]]
And here are some examples:
Sort /@ Tuples[Range[4], {3}] // Union;
Partition[
Rasterize /@ (HexagonalGridGraph2[#, PlotLabel -> #,
ImageSize -> {100, 100}] & /@ %), 5];
ImageAssemble[%]
We can generate the vertex coordinates using a slightly modified version of azerbajdan's cells
and use them with NearestNeighborGraph
:
ClearAll[vCoords]
vCoords = DeleteDuplicates @ Flatten[
Table[CirclePoints[{(2 j + k + l - 4) Sqrt[3] , 3 k - 2 - 3 l}, {2, π/2}, 6],
{j, #}, {k, #2}, {l, #3}], 3] &;
ClearAll[hexGridGraph]
hexGridGraph = Module[{v = vCoords @@ #},
NearestNeighborGraph[v, ##2, VertexCoordinates -> v]] &;
Examples:
hexGridGraph[{3, 5, 7},
VertexLabels -> Placed["Index", Center],
VertexSize -> .7,
VertexStyle -> White,
VertexLabelStyle -> 8,
ImageSize -> 400]
args = Sort /@ Tuples[Range[4], {3}] // Union;
hexGridGraph[#, PlotLabel -> #, ImageSize -> {100, 100}] & /@ args //
Multicolumn[#, 5] &