GraphPlot and GraphPlot3D calculate and plot a visually appealing 2D/3D layout of a graph. The functions are designed to work with very large graphs and handle both connected and disconnected graphs.
generate a 3D plot of the graph represented by the adjacency matrix m
Graph drawing functions.
This plots a graph specified by a rule list:
For disconnected graphs, individual components are laid out in a visually appealing way and assembled:
This is a larger graph defined by a sparse adjacency matrix from a structural engineering application. The matrix comes from the Harwell–Boeing Collection:
GraphPlot may produce slightly different output on different platforms, due to floating-point differences.
The option DirectedEdges specifies whether to draw edges as arrows. Possible values for this option are True or False. The default value for this option is False.
This shows a graph with edges represented by arrows:
This makes the arrowheads larger:
EdgeLabeling
The option EdgeLabeling specifies whether and how to display labels given for the edges. Possible values for this option are True, False, or Automatic. The default value for this option is True, which displays the supplied edge labels on the graph. With EdgeLabeling->Automatic, the labels are shown as tooltips.
By default, GraphPlot displays the supplied label for the edge between vertices 3 and 6:
This displays the edge label as a tooltip. Place the cursor over the edge between vertices 3 and 6 to see the tooltip:
Alternatively, use Tooltip[v_{i}->v_{j},lbl] to specify a tooltip for an edge. Place the cursor over the edge between vertices 3 and 6, as well as over the edge label on the edge between vertices 3 and 5, to see the tooltips:
The option EdgeRenderingFunction specifies graphical representation of the graph edges. Possible values for this option are Automatic, None, or a function that gives a proper combination of graphics primitives and directives. With the default setting of Automatic, a dark red line is drawn for each edge. With EdgeRenderingFunction->None, edges are not drawn.
This draws vertices only:
With EdgeRenderingFunction->g, each edge is rendered with the graphics primitives and directives given by the function g that can take three or more arguments, in the form g[{r_{i},…,r_{j}},{v_{i},v_{j}},lbl_{ij},…], where r_{i}, r_{j} are the coordinates of the beginning and ending points of the edge, v_{i}, v_{j} are the beginning and ending vertices, and lbl_{ij} is any label specified for the edge or None. Explicit settings for EdgeRenderingFunction->g override settings for EdgeLabeling and DirectedEdges.
This plots the edges as gray arrows with ends set back from vertices by a distance 0.1 (in the graph's coordinate system):
This generates edge labels or displays the ones supplied in the description of the graph:
This draws straight edges in black and other edges (two multiedges and a self-loop) in red. The function LineScaledCoordinate from the package GraphUtilities is used to place labels at 70% of the length of the edge:
This plots a 3D graph using spheres for vertices and cylinders for edges:
This plots a graph with edges displayed as springs and vertices as spheres:
This plots the benzene molecule:
Draw text along the edges:
Draw graphics on each edge:
Method
Algorithms to be used in GraphPlot and GraphPlot3D can be specified using the Method option, either as Method->"name" or Method->{"name",opt_{1}->val_{1},…}, where opt_{i}-> val_{i} are method-specific options, described in separate sections. Method->Automatic uses the "RadialDrawing" method for trees and "SpringElectricalEmbedding" otherwise.
a method suitable for the problem is chosen automatically
"CircularEmbedding"
lay out the vertices in a circle
"HighDimensionalEmbedding"
invoke the high-dimensional embedding method, in which the graph is first laid out in a high-dimensional space based on the graph distances of the vertices to k centers; this layout is then projected to 2D or 3D space by linear combination of the high-dimensional coordinates using principal component analysis
"RadialDrawing"
invoke the radial drawing method, which is most suitable for tree or tree-like graphs; if the graph is not a tree, a spanning tree is first constructed, and a radial drawing of the spanning tree is used to derive the drawing for the graph
"RandomEmbedding"
lay out vertices randomly
"SpiralEmbedding"
lay out the vertices in a spiral; in 3D, this distributes vertices uniformly on a sphere
"SpringElectricalEmbedding"
invoke the spring-electrical embedding method, in which neighboring vertices are subject to an attractive spring force that is proportional to their physical distance, and all vertices are subject to a repulsive electrical force that is inversely proportional to their distance; the overall energy is minimized
"SpringEmbedding"
invoke the spring embedding method, in which a vertex is subject to either attractive or repulsive force from another vertex, as though they are connected by a spring; the spring has an ideal length equal to the graph distance betweenthe vertices; the total spring energy is minimized
This draws the Petersen graph using the default method:
This draws the graph using the "SpringEmbedding" algorithm:
This draws the graph using the "HighDimensionalEmbedding" algorithm:
This draws the complete graph of 30 vertices using the "CircularEmbedding" method:
This draws the complete graph of 30 vertices using the "SpiralEmbedding" method in 3D:
This draws the complete graph using the "RandomEmbedding" method:
This draws a graph specified in the Combinatorica Package format using coordinates that come with it:
MultiedgeStyle
The option MultiedgeStyle specifies whether to draw multiple edges between two vertices. Possible values for MultiedgeStyle are Automatic (the default), True, False, or a positive real number. With the default setting MultiedgeStyle->Automatic, multiple edges are shown for a graph specified by a list of rules, but not shown if specified by an adjacency matrix. With MultiedgeStyle->δ, the multiedges are spread out to a scaled distance of δ.
By default, multiple edges are shown if a graph is given as a list of rules:
But multiple edges are not shown for graphs specified by an adjacency matrix:
This spreads multiple edges by the specified amount:
PackingMethod
The option PackingMethod specifies the method used for packing disconnected components. Possible values for the option are Automatic (the default), "ClosestPacking", "ClosestPackingCenter", "Layered", "LayeredLeft", "LayeredTop", and "NestedGrid". With PackingMethod->"ClosestPacking", components are packed as close together as possible using a polyomino method [6], starting from the top left. With PackingMethod->"ClosestPackingCenter", components are packed starting from the center. With PackingMethod->"Layered", components are packed in layers starting from top left. With PackingMethod->"LayeredLeft" or PackingMethod->"LayeredTop", components are packed in layers starting from the top/left respectively. With PackingMethod->"NestedGrid", components are arranged in a nested grid. The typical effective default setting is PackingMethod->"Layered", and the packing starts with the components of the largest bounding box area.
This shows the packing of disconnected components by the default method:
This shows the packing of disconnected components using the "ClosestPackingCenter" method:
Users can adjust the packing by suboptions of PackingMethod. The suboption "Padding" specifies the amount of space to allow between components; possible values are Automatic (the default), or a non-negative number. The suboption "PaddingFunction", which overrides "Padding", also specifies the amount of space to allow between components. It takes a list of the form {{w_{1},h_{1}},…}, which are the width and height of the bounding box of the components, and returns a non-negative number. Options PackingMethod->"ClosestPacking" and PackingMethod->"ClosestPackingCenter" also accept a "PolyominoNumber" suboption, which specifies the average number of polyominoes used to approximate each disconnected component. Possible values for the "PolyominoNumber" suboption are Automatic (the default, which usually sets "PolyominoNumber" to 100), or a positive integer. A smaller "PolyominoNumber" typically has the effect of not allowing smaller components to embed in between large components.
This specifies a space of one polyomino between components:
This specifies that an average of five polyominoes be used to approximate each component:
PlotStyle is a common option for graphics functions inherited by GraphPlot and GraphPlot3D. The option PlotStyle specifies the style in which objects are drawn.
Draw edges with thicker lines, and both edges and vertex labels in red:
SelfLoopStyle
The option SelfLoopStyle specifies whether and how to draw loops for vertices that are linked to themselves. Possible values of the option are Automatic (the default), True, False, or a positive real number. With SelfLoopStyle->Automatic, self-loops are shown if the graph is specified by a list of rules, but not by an adjacency matrix. With SelfLoopStyle->δ, the self-loops are drawn with a diameter of δ (relative to the average edge length).
By default, self-loops are displayed for a graph specified by a list of rules:
Self-loops are not shown if the graph is specified by an adjacency matrix:
This shows self-loops with the diameter as big as the average length of the edges:
VertexCoordinateRules
The option VertexCoordinateRules specifies the coordinates of the vertices. Possible values are None, a list of coordinates, or a list of rules specifying the coordinates of selected or all vertices.
This draws the Petersen graph using known coordinates:
This computes vertex coordinates of the same graph using the "SpringEmbedding" algorithm:
This specifies coordinates for two vertices:
This specifies only coordinates:
This draws a bipartite graph by fixing coordinates. "Anchors" are added to connect disconnected components:
When the bipartite graph is connected, it works even better without augmenting it with "Left" and "Right" anchors:
VertexLabeling
The option VertexLabeling specifies whether to show vertex names as labels. Possible values for this option are True, False, Automatic (the default), and Tooltip. VertexLabeling->True shows the labels. For graphs specified by an adjacency matrix, vertex labels are taken to be successive integers , , …, , where is the size of the matrix. For graphs specified by a list of rules, labels are the expressions used in the rules. VertexLabeling->False displays each vertex as a point. VertexLabeling->Tooltip displays each vertex as a point, but gives its name in a tooltip. VertexLabeling->Automatic displays each vertex as a point, giving its name in a tooltip if the number of vertices is not too large. You can also use Tooltip[v_{k},v_{lbl}] anywhere in the list of rules to specify an alternative tooltip for a vertex v_{k}.
This draws the graph with labels given as indices of the adjacency matrix:
This uses the labels specified in the list of rules:
This specifies alternative labels for vertices 3 and 5. Place the cursor above the vertices to see the labels:
This plots vertices as points, and displays vertex names in tooltips. Place the cursor above the vertices to see the labels:
VertexRenderingFunction
The option VertexRenderingFunction specifies graphical representation of the graph edges. Possible values for this option are Automatic, None, or a function that gives a proper combination of graphics primitives and directives. With the default setting of Automatic, vertices are displayed as points, with their names given in tooltips.
By default, vertices are displayed as points and, for small graphs, labeled in tooltips. Point the cursor at a vertex to see the tooltip:
This draws no vertices at all:
With VertexRenderingFunction->g, each vertex is rendered with the graphics primitives given by g[r_{i},v_{i},…], where r_{i} is the coordinate of the vertex and v_{i} is the label of the vertex. Explicit settings for VertexRenderingFunction->g override settings for VertexLabeling.
This shows vertices as yellow disks:
This renders vertices using a predefined graphic:
A Common Suboption of All Methods
All graph drawing methods accept the method suboption "Rotation", which specifies the desired amount of clockwise rotation in radians from the default orientation. The option takes any numeric values, or False. The default is 0.
For GraphPlot and GraphPlot3D, the default orientation is derived by an alignment step where the principal axis is found and the graph drawing is aligned with the coordinate. However if "Rotation"->False is specified, this step is skipped.
option name
default value
"Rotation"
0
amount of clockwise rotation to apply to the drawing
A common suboption for all methods.
This rotates a plot of a graph by , , and clockwise:
This shows the evolution of a graph layout process:
Common Suboptions of the "SpringEmbedding" and "SpringElectricalEmbedding" Methods
Both the SpringEmbedding and SpringElectricalEmbedding methods belong to the family of so-called force-directed methods. These methods work by calculating the force on each vertex, and iteratively moving the vertex along the force in an effort to minimize the overall system's energy. See [8] for algorithmic details. These two methods have the following common options.
tolerance used in terminating the energy minimization process
Common suboptions for "SpringEmbedding" and "SpringElectricalEmbedding" methods.
"EnergyControl"
The suboption "EnergyControl" specifies limitations on the total energy of the system during minimization. Possible values are Automatic (the default), "Monotonic", or "NonMonotonic". When the value is "Monotonic", a step along the force will only be accepted if the energy is lowered. When the value is "NonMonotonic", a step along the force will be accepted even if the energy is not lowered.
"InferentialDistance"
The suboption "InferentialDistance" specifies a cutoff distance beyond which the interaction between vertices is assumed to be nonexistent. Possible values are Automatic (the default) or a positive numeric value. For the "SpringEmbedding" method, if the graph distance between a vertex i and a vertex j is greater than the option value of "InferentialDistance", the repulsive and attractive spring force between i and j is ignored. For the "SpringElectricalEmbedding" method, if the Euclidean distance between a vertex i and a vertex j is greater than the option value of "InferentialDistance", the repulsive force between i and j is ignored.
This draws a random tree using the "SpringElectricalEmbedding" method:
Using a smaller (more negative) "RepulsiveForcePower" option value (see the next section), the graph now fills more space:
A similar effect can be achieved using a small "InferentialDistance" option value:
MaxIterations
The option MaxIterations specifies the maximum number of iterations to be used in attempting to minimize the energy. Possible values are Automatic (the default) or a positive integer.
"RandomSeed"
The option "RandomSeed" specifies a seed for the random number generator that computes the initial vertex placement. Changing this option usually affects the orientation of the drawing of the graph, but it can also change the layout. Possible values are Automatic or an integer.
This shows the effect of different random seed values on drawing the Petersen graph:
"RecursionMethod"
The option "RecursionMethod" specifies whether the graph layout should be produced by a recursive procedure. Possible values are Automatic (the default), "Multilevel", or None. In a "Multilevel" algorithm, the graph is successively coarsened into graphs with a smaller and smaller number of vertices. The coarser graphs are laid out first, and those layouts are interpolated into the finer graphs and then further refined.
For the option "Randomize", possible values are Automatic, True, and False. For "MinSize", possible values are Automatic or a positive number. For "CoarseningScheme", the implemented algorithms are based on either a maximal independent vertex set, which forms the coarse vertices, or a maximal independent edge set, also called a matching. In a matching, two vertices that form an edge are merged to form a coarse graph vertex. The following are possible values for "CoarseningScheme".
"MaximalIndependentVertexSet"
link vertices in the maximal independent set if their graph distance is 3 or less
"MaximalIndependentVertexSetInjection"
link vertices in the maximal independent set if their graph distance is 1 or 2
"MaximalIndependentVertexSetRugeStuben"
generate the maximal independent vertex set, giving priority to vertices with more neighbors not in the set, then link vertices in the set if their graph distance is 3 or less
"MaximalIndependentVertexSetRugeStubenInjection"
link vertices if their graph distance is 1 or 2, giving priority to vertices with more neighbors
"MaximalIndependentEdgeSet"
consider edges in their natural order when matching
"MaximalIndependentEdgeSetHeavyEdge"
give priority to edges with higher edge weight (i.e., edges that represent a larger number of edges in the original graph) when matching
"MaximalIndependentEdgeSetSmallestVertexWeight"
give priority to matchings of vertices with neighbors that have the smallest vertex weight
"StepControl"
The option "StepControl" defines how step length is modified during energy minimization. It can be Automatic (the default), "Monotonic" (where step length can only be decreased), "NonMonotonic" (where step length can be made larger or smaller), or "StrictlyMonotonic" (where step length is strictly reduced between iterations).
"StepLength"
The option "StepLength" gives the initial step length used in moving the vertices around. Possible values are Automatic (the default) or a positive real number.
Tolerance
The option Tolerance specifies the tolerance used in terminating the energy minimization process. If the average change of coordinates of each vertex is less than the tolerance, the energy minimization process is terminated and the current coordinates are given as output. Possible values are Automatic or a positive real number.
Method Suboptions of the "SpringElectricalEmbedding" Method
whether to use an octree data structure (in three dimensions) or a quadtree data structure (in two dimensions) in the calculation of repulsive force
"RepulsiveForcePower"
-1
how fast the repulsive force decays over distance
Method options for "SpringElectricalEmbedding".
"Octree"
The "Octree" option specifies whether to use an octree data structure (in three dimensions) or a quadtree data structure (in two dimensions) in the calculation of repulsive force. Possible values are Automatic (the default), True, or False. Use of an octree/quadtree data structure minimizes the complexity of computation by approximating the long-range repulsive force. However, it introduces an approximation to the force calculation. Therefore, in a few cases the result may not be as good.
"RepulsiveForcePower"
Possible values are negative real numbers, with -1 as the default. In the spring-electrical embedding, the repulsive force between two vertices and is by default. If the value of RepulsiveForcePower is (with ), then the repulsive force is defined as , where is the distance between the vertices and is a constant coefficient.
A strong long-range repulsive force over long distance often has the boundary effect that vertices in the periphery are closer to each other than those in the center are. Specifying a weaker long-range repulsive force can sometimes alleviate this effect. This option can also be useful in drawing a graph so that it fills up more space. (See the "InferentialDistance" method option for details.)
With a repulsive force power of , the boundary vertices are not as close to each other as they are with the default value of :
whether the result should be further refined, and which method should be used for refinement
Method option for "HighDimensionalEmbedding".
"RefinementMethod"
The option "RefinementMethod" specifies whether the result should be further refined, and which method should be used to refine it. Possible values are None (the default), "SpringEmbedding", or "SpringElectricalEmbedding".
This shows a case where the "HighDimensionalEmbedding" method placed vertices 5 and 6 at the same position. Specifying a "RefinementMethod" option helps to draw the graph better:
Advanced Topics
Drawing a Graph to Fill Up More Space
While the default setting for GraphPlot works well in general, for graphs that have a wide range of values for the vertex degree, it is often necessary to use a setting that helps the vertices to occupy less space.
The default method usually works well:
However, sometimes "SpringEmbedding" produces a drawing that occupies more space:
A similar effect can be achieved with a repulsive force power smaller than the default (-1), so that the repulsive force decays more quickly over distance:
Alternatively, specify a cutoff distance:
For such tree-like graphs, a tree-drawing algorithm may be preferable. See "Tree Drawing" for greater control over tree layout:
This draws a graph from power network modeling:
Improving Performance for Drawing Very Large Graphs
Although the default option set usually ensures a very good performance, it is often possible to further increase drawing speed and reduce memory usage by selecting specific option combinations for a particular task. For example, speed and/or memory usage can be improved using a smaller number of iterations, a smaller inferential distance, or a lower tolerance. These settings tend to reduce quality, but still frequently offer an acceptable compromise.
This is a drawing with default option settings:
A coarsening scheme based on the maximal independent vertex set is often faster and uses less memory, and yet offers a comparable layout quality:
By reducing the number of iterations to 30, you can get a result still faster:
Setting the inferential distance to 2 and the number of iterations to 40 is also faster than the default:
By further reducing the number of iterations to 20, you get a result much faster:
A combination of the previous options is still faster:
"HighDimensionalEmbedding" tends to be the fastest method, but the quality of the drawing often suffers:
For comparison, "SpringEmbedding" is the slowest method, but it is the only one that draws the mesh using orthogonal lines:
Extracting Vertex Coordinates from Output
In most cases, you will deal with the output of GraphPlot and GraphPlot3D just as with a usual Graphics expression. However, you may sometimes want to take advantage of the additional information encapsulated in the output expression, which has the form Graphics[Annotation[data,VertexCoordinateRules->rules]]. Particularly, it is sometimes useful to extract coordinates of graph vertices.
Here is a simple graph:
This extracts the coordinates of vertices:
Example Gallery
E. coli Transcription Networks
In a graph representation of a transcriptional regulation network that controls gene expression in cells, nodes (vertices) are operons, which are one or more genes transcribed on the same messenger ribonucleic acid (mRNA). Edges of the graph are directed from an operon that encodes a transcription factor to an operon that it directly regulates [1].
Data
This is the network [2] described as rules.
Drawing the Network
The network consists of many components. Mouse over vertices to see the labels:
Use a different component packing method:
This spreads out the vertices:
An alternative way of spreading out the vertices:
Protein: An Oxidoreductase
This plots an oxidoreductase protein [3] using the data from [4]:
Square Dielectric Waveguide
A square sparse matrix can be viewed as an adjacency matrix of a graph; therefore it is often instructive to "draw" the sparse matrix using GraphPlot. An example is given below, and the graph drawing of over one thousand matrices can be found at [7].
This graph represents a sparse matrix used in electrical engineering [5]:
Social Network
Graph drawing is a powerful tool in visualizing social structures.
This plots a social network:
Graphs from Words and Texts
This plots a network of words all starting with "din". Here, two nearest words are found for each word and linked to it with an edge:
This generates a graph by linking each letter in a word to all the letters that follow it in the word:
This generates a graph by linking words in a text with subsequent words:
Torus
This defines a torus and plots it in 3D:
References
[1] Milo, R., S. Shen-Orr, S. Itzkovitz, N. Kashtan, D. Chklovskii, and U. Alon. "Network Motifs: Simple Building Blocks of Complex Networks." Science 298, no. 5594 (2002): 824–827.
[2] Alon, U. "Collection of Complex Networks." Uri Alon Homepage 2007.
[3] Milo, R., S. Itzkovitz, N. Kashtan, et al. "Superfamilies of Designed and Evolved Networks." Science 303, no. 5663 (2004): 1538–1542.
[6] Freivalds, K., U. Dogrusoz, and P. Kikusts, "Disconnected Graph Layout and the Polyomino Packing Approach." Lecture Notes in Computer Science: Revised Papers from the 9th International Symposium on Graph Drawing 2265 (2001): 378–391.
[7] Hu, Y. F. "Graph Drawing of Square Matrices from University of Florida Sparse Matrix Collection." (2007).
[8] Hu, Y. F. "Efficient, High-Quality Force-Directed Graph Drawing." The Mathematica Journal 10, no. 1 (2006): 37–71.