NearestNeighborGraph [{elem1,elem2,…}]
gives a graph with vertices elem1,elem2,… and edges connecting each elemi to its nearest neighbors.
NearestNeighborGraph [{elem1,elem2,…},k]
gives a graph connecting each elemi to its k nearest neighbors.
NearestNeighborGraph [{elem1,elem2,…},{k,r}]
gives a graph connecting each elemi to at most k nearest vertices within radius r of elemi.
NearestNeighborGraph [{elem1,elem2,…},{All ,r}]
gives a graph connecting each elemi to all vertices within radius r of elemi.
NearestNeighborGraph
NearestNeighborGraph [{elem1,elem2,…}]
gives a graph with vertices elem1,elem2,… and edges connecting each elemi to its nearest neighbors.
NearestNeighborGraph [{elem1,elem2,…},k]
gives a graph connecting each elemi to its k nearest neighbors.
NearestNeighborGraph [{elem1,elem2,…},{k,r}]
gives a graph connecting each elemi to at most k nearest vertices within radius r of elemi.
NearestNeighborGraph [{elem1,elem2,…},{All ,r}]
gives a graph connecting each elemi to all vertices within radius r of elemi.
Details and Options
- The nearest neighbor graph is also known as k-nearest neighbor graph (k-NNG).
- An element elemj is a nearest neighbor of an element elemi whenever the distance from elemi to elemj is no larger than the distance from elemi to any other element.
- An element elemj is a k-nearest neighbor of an element elemi whenever the distance from elemi to elemj is among the k^(th) smallest distances from elemi to any other element.
- NearestNeighborGraph works for a variety of data, including numerical, geospatial, textual, and visual.
- NearestNeighborGraph has the same options as Graph , with the following additions and changes: [List of all options]
-
- NearestNeighborGraph takes the same DistanceFunction as Nearest .
-
ImageMargins 0. the margins to leave around the graphicPreserveImageOptions Automatic whether to preserve image options when displaying new versions of the same graphic
List of all options
Examples
open all close allBasic Examples (2)
A nearest neighbor graph:
Generate the k-nearest neighbor graph for integers in the range 1 to 10:
Scope (10)
Basic Uses (4)
A nearest neighbor graph for integers in the range 1 to 10:
Generate the 2-nearest neighbor graph:
Generate the at most 3-nearest neighbor graph within radius 2:
Generate the nearest neighbor graph within radius 3:
Numerical Data (1)
A nearest neighbor graph for two-dimensional numerical data:
Three-dimensional dataset:
Boolean Data (1)
A nearest neighbor graph for a set of Boolean data:
Geo Positions (1)
Generate the nearest geodesic distance neighbor graph:
Strings (1)
Generate the 2-nearest strings neighbor graph:
Images (1)
Generate the 2-nearest images neighbor graph:
Colors (1)
Generate the 2-nearest colors neighbor graph:
Options (89)
DistanceFunction (7)
By default, EuclideanDistance is used for numerical data:
EditDistance is used for strings:
GeoDistance is used for geo positions:
JaccardDissimilarity is used for Boolean data:
ColorDistance is used for colors:
ImageDistance is used for images:
The DistanceFunction can be given as a symbol:
Or as a pure function:
Method (1)
Compare different methods for machine-precision data:
In three dimensions, the "KDtree" method is faster:
In 20 dimensions, a simple scan is faster:
WorkingPrecision (1)
Using WorkingPrecision->MachinePrecision ensures the fastest evaluation method is used:
AnnotationRules (2)
Specify an annotation for vertices:
Edges:
DirectedEdges (1)
By default, an undirected graph is generated:
Use DirectedEdges->True to generate a directed graph:
EdgeLabels (7)
Label the edge 12:
Label all edges individually:
Use any expression as a label:
Use Placed with symbolic locations to control label placement along an edge:
Use explicit coordinates to place labels:
Vary positions within the label:
Place multiple labels:
Use automatic labeling by values through Tooltip and StatusArea :
EdgeShapeFunction (6)
Get a list of built-in settings for EdgeShapeFunction :
Undirected edges including the basic line:
Lines with different glyphs on the edges:
Directed edges including solid arrows:
Line arrows:
Open arrows:
Specify an edge function for an individual edge:
Combine with a different default edge function:
Draw edges by running a program:
EdgeShapeFunction can be combined with EdgeStyle :
EdgeShapeFunction has higher priority than EdgeStyle :
EdgeStyle (2)
Style all edges:
Style individual edges:
EdgeWeight (2)
Specify a weight for all edges:
Use any numeric expression as a weight:
GraphHighlight (3)
Highlight the vertex 1:
Highlight the edge 23:
Highlight vertices and edges:
GraphHighlightStyle (2)
Get a list of built-in settings for GraphHighlightStyle :
Use built-in settings for GraphHighlightStyle :
GraphLayout (5)
By default, the layout is chosen automatically:
Specify layouts on special curves:
Specify layouts that satisfy optimality criteria:
VertexCoordinates overrides GraphLayout coordinates:
Use AbsoluteOptions to extract VertexCoordinates computed using a layout algorithm:
PlotTheme (4)
Base Themes (2)
Use a common base theme:
Use a monochrome theme:
Feature Themes (2)
Use a large graph theme:
Use a classic diagram theme:
VertexCoordinates (3)
By default, any vertex coordinates are computed automatically:
Extract the resulting vertex coordinates using AbsoluteOptions :
Specify a layout function along an ellipse:
Use it to generate vertex coordinates for a graph:
VertexCoordinates has higher priority than GraphLayout :
VertexLabels (13)
Use vertex names as labels:
Label individual vertices:
Label all vertices:
Use any expression as a label:
Use Placed with symbolic locations to control label placement, including outside positions:
Symbolic outside corner positions:
Symbolic inside positions:
Symbolic inside corner positions:
Use explicit coordinates to place the center of labels:
Place all labels at the upper-right corner of the vertex and vary the coordinates within the label:
Place multiple labels:
Any number of labels can be used:
Use the argument Placed to control formatting including Tooltip :
Or StatusArea :
Use more elaborate formatting functions:
VertexShape (5)
Use any Graphics , Image , or Graphics3D as a vertex shape:
Specify vertex shapes for individual vertices:
VertexShape can be combined with VertexSize :
VertexShape is not affected by VertexStyle :
VertexShapeFunction has higher priority than VertexShape :
VertexShapeFunction (10)
Get a list of built-in collections for VertexShapeFunction :
Use built-in settings for VertexShapeFunction in the "Basic" collection:
Simple basic shapes:
Common basic shapes:
Use built-in settings for VertexShapeFunction in the "Rounded" collection:
Use built-in settings for VertexShapeFunction in the "Concave" collection:
Draw individual vertices:
Combine with a default vertex function:
Draw vertices using a predefined graphic:
Draw vertices by running a program:
VertexShapeFunction can be combined with VertexStyle :
VertexShapeFunction has higher priority than VertexStyle :
VertexShapeFunction has higher priority than VertexSize :
VertexShapeFunction has higher priority than VertexShape :
VertexSize (8)
By default, the size of vertices is computed automatically:
Specify the size of all vertices using symbolic vertex size:
Use a fraction of the minimum distance between vertex coordinates:
Use a fraction of the overall diagonal for all vertex coordinates:
Specify size in both the and directions:
Specify the size for individual vertices:
VertexSize can be combined with VertexShapeFunction :
VertexSize can be combined with VertexShape :
VertexStyle (5)
Style all vertices:
Style individual vertices:
VertexShapeFunction can be combined with VertexStyle :
VertexShapeFunction has higher priority than VertexStyle :
VertexStyle can be combined with BaseStyle :
VertexStyle has higher priority than BaseStyle :
VertexShape is not affected by VertexStyle :
VertexWeight (2)
Set the weight for all vertices:
Use any numeric expression as a weight:
Applications (7)
Basic Uses (2)
Fixed-radius near neighbors:
-approximate nearest neighbor search:
Graphs & Networks (2)
Farthest neighbor graphs:
Generate a spatial random graph within radius 0.2:
Geometry (1)
Simplification of point-sample surfaces:
Proximity Searching (2)
Search nearest image neighbors:
Search the dictionary neighbors:
Properties & Relations (7)
Use VertexCount and EdgeCount to count vertices and edges:
Use VertexList and EdgeList to enumerate vertices and edges in standard order:
Compute the AdjacencyMatrix from a graph:
Distance metric generates undirected graphs:
Dissimilarity generates directed graphs:
Generate a nearest neighbor graph within radius 0.2 by using SpatialGraphDistribution :
Use Nearest and NearestFunction get the nearest neighbor graph:
This is equivalent to:
See Also
RandomPointConfiguration DistanceMatrix Nearest ClusteringTree SpatialGraphDistribution RelationGraph NestGraph GeoNearest DimensionReduce
Function Repository: PersistentHomology
Related Guides
History
Text
Wolfram Research (2015), NearestNeighborGraph, Wolfram Language function, https://reference.wolfram.com/language/ref/NearestNeighborGraph.html.
CMS
Wolfram Language. 2015. "NearestNeighborGraph." Wolfram Language & System Documentation Center. Wolfram Research. https://reference.wolfram.com/language/ref/NearestNeighborGraph.html.
APA
Wolfram Language. (2015). NearestNeighborGraph. Wolfram Language & System Documentation Center. Retrieved from https://reference.wolfram.com/language/ref/NearestNeighborGraph.html
BibTeX
@misc{reference.wolfram_2025_nearestneighborgraph, author="Wolfram Research", title="{NearestNeighborGraph}", year="2015", howpublished="\url{https://reference.wolfram.com/language/ref/NearestNeighborGraph.html}", note=[Accessed: 05-December-2025]}
BibLaTeX
@online{reference.wolfram_2025_nearestneighborgraph, organization={Wolfram Research}, title={NearestNeighborGraph}, year={2015}, url={https://reference.wolfram.com/language/ref/NearestNeighborGraph.html}, note=[Accessed: 05-December-2025]}