Graphviz
12 min read

Graph Visualization Software — describes graphs declaratively in the DOT language; renders them as images (PNG, SVG, PDF, PostScript, etc.), diagrams, and maps.

Widely used for dependency graphs, state machines, network diagrams, flowcharts, UML diagrams, ER models, and more.

Overview

Graphviz works by taking a DOT file (a text description of nodes, edges, and attributes) and running it through a layout engine that computes positions and then renders the result to an output format.

.dot file → layout engine → rendered output

The typical workflow:

bash
# Write graph.dot, then render it
dot graph.dot -Tpng -o graph.png
neato graph.dot -Tsvg -o graph.svg

Key Components

• DOT Language — Declarative language for defining graphs
• Layout Engines — Algorithms that compute node/edge positions
• Output Formats — PNG, SVG, PDF, PostScript, JSON (xdot), image maps, etc.
• Libraries — C library for embedding Graphviz in applications



The DOT Language

Grammar

graph : [ strict ] (graph | digraph) [ ID ] '{' stmt_list '}'
stmt_list : [ stmt [ ';' ] stmt_list ]
stmt : node_stmt | edge_stmt | attr_stmt | ID '=' ID | subgraph
attr_stmt : (graph | node | edge) attr_list
attr_list : '[' [ a_list ] ']' [ attr_list ]
a_list : ID '=' ID [ (';' | ',') ] [ a_list ]
edge_stmt : (node_id | subgraph) edgeRHS [ attr_list ]
edgeRHS : edgeop (node_id | subgraph) [ edgeRHS ]
node_stmt : node_id [ attr_list ]
node_id : ID [ port ]
port : ':' ID [ ':' compass_pt ] | ':' compass_pt
subgraph : [ subgraph [ ID ] ] '{' stmt_list '}'
compass_pt : n | ne | e | se | s | sw | w | nw | c | _

Basic Syntax

dot
// Undirected graph (uses --)
graph MyGraph {
A -- B -- C;
A -- C;
}

// Directed graph (uses ->)
digraph MyGraph {
A -> B -> C;
A -> D;
D -> C [label="optional" style=dashed];
}

IDs

An ID is one of:

• Unquoted: Alphanumeric + underscore, not starting with a digit: node1, my_node, ABC
• Quoted: Double-quoted string: "node 1", "Hello World"
• Numeric: Any number: 123, -3.14, .5
• HTML-like: <...> containing legal XML

dot
digraph {
node1; // Unquoted
"node 1"; // Quoted (allows spaces)
123; // Numeric
<p>Hello</p>; // HTML-like
}

Keywords

KeywordPurpose
graphStart undirected graph
digraphStart directed graph
strictNo multi-edges allowed
subgraphDefine a subgraph
clusterPrefix for cluster subgraphs (layout convention)
nodeDefault node attributes
edgeDefault edge attributes
graph (as attr)Default graph attributes

Comments

dot
digraph {
// Single-line comment

/* Multi-line
comment */
}

Default Attributes

dot
digraph {
// Set defaults for all nodes
node [shape=box fontname=Helvetica fontsize=12];

// Set defaults for all edges
edge [color=blue style=dashed];

// Now these inherit the defaults
A;
B;
C;
A -> B;
B -> C;

// Override for specific node
D [shape=diamond color=red];
}

Subgraphs and Clusters

dot
digraph {
// Ordinary subgraph (groups structure)
subgraph cluster_group {
label="Group A";
style=filled;
color=lightgrey;
A -> B;
}

// Anonymous subgraph for rank constraints
subgraph {
rank=same;
C; D; E;
}
}

Cluster subgraphs must have names starting with cluster to be rendered as grouped boxes.

Ports (Edge Attachment Points)

dot
digraph {
A [shape=record label="{left|middle|right}"];
B [shape=record label="{top|bottom}"];

// Attach to specific ports
A:m -> B:t;
A:l -> B:b;
}

Compass points for ports: n, ne, e, se, s, sw, w, nw, c, _ (center).



Layout Engines

Graphviz ships with 12 layout engines, each using a different algorithm:

Directed Graph Layouts

EngineAlgorithmBest For
dotHierarchical (Sugiyama)Directed graphs, flowcharts, trees
twopiRadial (Spring)Rooted graphs, hub-and-spoke
circoCircular (Springs)Cycles, ring topologies

dot — Hierarchical Layout

dot
digraph {
rankdir=TB; // or LR, RL, BT
node [shape=box];

A -> B -> D;
A -> C -> D;
}

Key attributes: rankdir, ranksep, nodesep, rank=same/min/max/source/sink, ordering=in/out, minlen, constraint, group

twopi — Radial Layout

dot
graph {
layout=twopi;
root=Center;
Center -> A -> B;
Center -> C -> D;
}

Nodes are placed in concentric circles by distance from root.

circo — Circular Layout

dot
graph {
layout=circo;
mindist=1.0;
oneblock=false; // one block per connected component

A -> B -> C -> D -> E -> F -> A;
}

Nodes placed on one or more circles to minimize edge crossings.



Undirected Graph Layouts

EngineAlgorithmBest For
neatoSpring model (stress majorization)Undirected graphs, small-to-medium
fdpForce-directed (Fruchterman-Reingold)Undirected, general purpose
sfdpMulti-level force-directedLarge undirected graphs

neato — Spring Model

dot
graph {
layout=neato;
mode=KK; // KK, major, sgd, hier, ipsep
model=shortpath; // shortpath, circuit, subset, mds
overlap=false; // overlap removal strategy
sep="+3"; // separation margin
}

fdp — Force-Directed Placement

dot
graph {
layout=fdp;
K=0.5; // spring constant
maxiter=200; // iterations
overlap=prism; // overlap removal
}

sfdp — Scalable Force-Directed Placement

dot
graph {
layout=sfdp;
K=0.8;
levels=4;
label_scheme=3; // edge label placement
beautify=true; // arrange leaf nodes uniformly
}



Cluster Layouts

EnginePurpose
osageCluster/array layout (for component diagrams)
patchworkSquarified treemap for clustered graphs

osage — Cluster Grid

dot
graph {
layout=osage;
A -> B;
C -> D;
A -> C;
B -> D;
}

patchwork — Squarified Treemap

dot
graph {
layout=patchwork;
node [style=filled];
A [area=5 fillcolor=blue];
B [area=10 fillcolor=green];
C [area=20 fillcolor=red];
}



Utility Engines

EnginePurpose
nopPretty-print DOT input
nop2Pretty-print assuming known positions

bash
dot -Txdot input.dot | dot -Tcanon > output.dot



Node Shapes

ShapeDescription
boxRectangle
ellipseEllipse/circle
circleCircle (alias for ellipse with equal width/height)
pointPoint (invisible, used as anchor)
diamondDiamond/rhombus
triangleTriangle
plaintextPlain text, no border
recordRecord-style table
fixedshapeFixed shape
polygonPolygon (use sides to set sides)
sectorSector/wedge
MrecordMarkdown record
fileFolder/file shape
folderFolder shape
noteNote/tape shape
tabTab shape
box3d3D box
cdsClass diagram shape

Record Nodes (Tables)

dot
digraph {
node [shape=record fontname=Helvetica fontsize=10];

A [label="{<f0> left | <f1> middle | <f2> right}"];
B [label="{ top | {<c0> left | <c1> right} | bottom }"];
C [label="simple node"];

A:f1 -> B:top;
A:f2 -> B:c0;
B:bottom -> C;
}

Record syntax: { field0 | field1 | field2 } or { <portname> label | ... }



Complete Attribute Reference

All attributes are case-sensitive. Specified as name=value in brackets.

Graph-Level Attributes

AttributeTypeDefaultDescription
bgcolorcolortransparentCanvas background
centerboolfalseCenter drawing in output
charsetstringUTF-8Character encoding
labelstring""Graph title
labellocstring"t"/"b"Label position (top/bottom)
labeljuststring"c"Label justification (l/c/r)
rankdirrankdir"TB"Layout direction (TB/RL/LR/BT)
ranksepdouble0.5Separation between ranks
nodesepdouble0.25Min space between adjacent nodes
margindoubledevice-depCanvas margin in inches
paddouble0.0555 (4pt)Padding around graph
sizedoubleautoMax width/height in inches
ratiodouble/stringautoAspect ratio (fill/compress/expand/auto)
overlapstringtrueOverlap removal method
scaledouble1.0Scale factor after layout
rotateint0Rotation angle
landscapeboolfalseSame as rotate=90
orientationdouble0Node shape rotation angle
layerslayerList""Named layers for overlays
layerselectlayerRange""Layers to emit
packbool/intfalsePack connected components
packmodepackModenodePacking method
defaultdistdoubleautoDistance between components (neato/fdp)
clusterrankclusterModelocalCluster handling (dot only)
newrankboolfalseGlobal ranking (dot only)
mclimitdouble1.0Edge crossing minimizer scale
nslimit / nslimit1doubleautoNetwork simplex iterations
searchsizeint30Edge search limit
TBbalancestring""Move floating nodes to min/max rank
orderingstring""Edge ordering (in/out)
remincrossbooltrueSecond edge crossing pass
showboxesint0Debug guide boxes
quantumdouble0.0Round label dims to quantum
linelengthint128Line overflow length
pagedoubleautoPage size in inches
pagedirpagedirBLPage emission order
viewportviewPort""Clipping window
outputorderoutputModebreadthfirstDrawing order
fontpathstringsystem-depFont search path
fontnamesstring""SVG font mapping
stylesheetstring""CSS stylesheet URL (SVG)
classstring""CSS class (SVG)
idstring""Element identifier
href / URLescString""Hyperlink
targetescString""Browser target
tooltipescString""Hover tooltip
commentstring""Output comment

Node-Level Attributes

AttributeTypeDefaultDescription
labelstring\N (node name)Node text label
shapeshapeellipseNode shape
widthdouble0.75Width in inches
heightdouble0.5Height in inches
fixedsizebool/stringfalseUse fixed dimensions
stylestyle""Drawing style (filled/diagonal...)
colorcolorblackOutline color
fillcolorcolorlightgreyFill color
penwidthdouble1.0Line width in points
peripheriesintshape-depNumber of borders
orientationdouble0Polygon rotation
sidesint4Polygon sides
regularboolfalseForce regular polygon
distortiondouble0Polygon distortion
skewdouble0Polygon skew
fontnamestringTimes-RomanText font
fontsizedouble14.0Font size in points
fontcolorcolorblackText color
margindouble0.11,0.055Label margin
labellocstring"c"Label position (t/c/b)
nojustifyboolfalseNo line justification
imagestring""Image file path
imagepathstring""Image search paths
imageposstring"mc"Image position (tl/tc/tr/ml/mc/mr/bl/bc/br)
imagescalebool/stringfalseImage scaling (false/width/height/both)
pospointautoPosition (x,y) in points
pinboolfalsePin to position
zdouble0.0Z coordinate (3D)
groupstring""Node group for bundling
class / href / URLescString""SVG/Map attributes
tooltipescString""Hover tooltip
xlabelstring""External label

Edge-Level Attributes

AttributeTypeDefaultDescription
labelstring""Edge text label
dirdirTypeforwardArrow direction (forward/back/both/none)
arrowheadarrowTypenormalHead arrow style
arrowtailarrowTypenormalTail arrow style
arrowsizedouble1.0Arrow scale factor
headlabelstring""Label near head
taillabelstring""Label near tail
headportportPoscenterAttachment point on head
tailportportPoscenterAttachment point on tail
headclip / tailclipbooltrueClip edge to node boundary
headhref / headURLescString""Head hyperlink
tailhref / tailURLescString""Tail hyperlink
labelhref / labelURLescString""Label hyperlink
headtarget / tailtargetescString""Browser target
headtooltip / tailtooltipescString""Edge tooltip
color / fillcolorcolorblackEdge color
penwidthdouble1.0Line width in points
fontname / fontsize / fontcolorvariousdefaultsLabel font
labelfloatboolfalseFree label positioning
labelangledouble-25Label angle in degrees
labeldistancedouble1.0Label distance from node
decorateboolfalseConnect label to edge
stylestyle""Drawing style
minlenint1Minimum rank difference
weightint/double1Edge weight
constraintbooltrueUse for ranking
samehead / sametailstring""Co-align edges
lhead / ltailstring""Logical head/tail for clusters
xlabelstring""External label

Style Values

StyleDescription
"filled"Fill with fillcolor
"diagonalFill"Diagonal fill
"rounded"Rounded corners
"dashed"Dashed line
"dotted"Dotted line
"bold"Bold line
"invis"Invisible
"striped"Striped
"filled" + gradientGradient fill

Arrowhead/Tail Styles

ValueDescription
"normal"Standard arrow
"box"Box arrow
"obox"Open box
"crow"Crow's foot
"ocrow"Open crow's foot
"doublecrow"Double crow's foot
"odoublecrow"Open double crow's foot
"diamond"Diamond
"odiamond"Open diamond
"dot"Small dot
"odot"Open dot
"inv"Inverted triangle
"oinv"Open inverted triangle
"none"No arrow

Rank Direction

ValueDescription
"TB"Top to bottom (default)
"BT"Bottom to top
"LR"Left to right
"RL"Right to left

Color Names

Standard X11 colors: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgreen, darkgrey, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, green, greenyellow, grey, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgreen, lightgrey, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, navyblue, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, rebeccapurple, red, rosybrown, royalblue, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen

Also supports CSS colors, hex (#RRGGBB), and Brewer color schemes (colorscheme=oranges9, colorscheme=greens9, etc.).



CLI Commands and Options

Main Commands

CommandLayout EngineDescription
dotdotHierarchical layout
neatoneatoSpring model
fdpfdpForce-directed
sfdpsfdpScalable force-directed
twopitwopiRadial layout
circocircoCircular layout
osageosageCluster/array layout
patchworkpatchworkTreemap layout
nopnopPretty-print
dot2texdotConvert to TikZ

Common Options

bash
# Basic usage
dot [options] <input.dot>

# Specify output format
dot -Tpng -o output.png input.dot
dot -Tsvg -o output.svg input.dot
dot -Tpdf -o output.pdf input.dot

# Auto-detect output from filename extension
dot -O -Tpng input.dot # creates input.dot.png
dot -O -Tsvg input.dot # creates input.dot.svg

# Pipe input
echo 'digraph{A->B}' | dot -Tsvg > graph.svg

# Specify layout engine explicitly
dot -Kneato -Tpng input.dot
dot -Kfdp -Tpng input.dot

# Set engine-specific attributes
dot -Kdot -O graph.dot # uses DOT attribute: layout=dot

Option Summary Table

OptionDescription
-TfmtOutput format (png, svg, pdf, ps, json, xdot, cmap, map, plain, dot, canon, gif, jpg, jpeg, tif, tiff, webp, svgz, ps2)
-o fileOutput file name
-KengineForce layout engine (dot, neato, fdp, sfdp, twopi, circo, osage, patchwork, nop)
-nRead existing positions (no layout), for -n2 use points as input
-n2Like -n, coordinates are in points
-s scaleScale input coordinates (e.g., -s72 for points-to-inches)
-Gattr=valGlobal attribute
-Nattr=valDefault node attribute
-Eattr=valDefault edge attribute
-vVersion information
-VVersion and license info
-cEnable plugin loading
-g levelDebug level
-l fileLoad library
-q levelMinimum query level for symbol lookup (default: 3)
-e fileError file
-i fileImage path
-f fontpathFont path
-OGenerate output files with format appended to input filename
-SUse the size attribute to determine output dimensions

Output Formats

FormatExtensionDescription
png.pngPNG bitmap
svg.svgScalable Vector Graphics
pdf.pdfPDF document
ps.psPostScript Level 2
ps2.psPostScript Level 3
xdot.xdotX11 Graphics Exchange Format
dot.dotCanonical DOT format
canon.canonCanonical text output
plain.plainPlain node positions
json.jsonJSON output
json0.jsonJSON (no layout)
cmap.cmapImage map for HTML
cmapx.cmapxNamed map for HTML
imap.imapClient-side image map
cmapx_np.cmapxClient map, no URLs
svgz.svgzCompressed SVG
gif.gifGIF bitmap
jpg / jpeg.jpgJPEG bitmap
tif / tiff.tifTIFF bitmap
webp.webpWebP bitmap
vrml.vrmlVRML 3D
fig.figXFIG format

Engine-Specific Options

neato

OptionDescription
-mUse Kamada-Kawai mode
-s scaleScale input coordinates
-e epsilonTermination condition
-i modeOptimization mode (KK/major/sgd/hier/ipsep)
-M modelDistance model (shortpath/circuit/subset/mds)
-k maxiterMax iterations
-D dampingDamping factor (0.0-1.0)
-d dimLayout dimensions (2-10)
-d2 dimenRendering dimensions
-p normalizeNormalize layout
-PDon't translate to origin
-r ratioAspect ratio
-S sizeMax size
-c configConfiguration file

fdp

OptionDescription
-k KSpring constant
-m maxiterMax iterations
-e epsilonTermination condition
-d dimDimensions
-D dampingDamping
-p normalizeNormalize
-PDon't translate
-S sizeMax size



Examples

Flowchart

dot
digraph Workflow {
rankdir=LR;
node [shape=box, fontname=Helvetica fontsize=12];
edge [fontname=Helvetica fontsize=10];

Start [shape=ellipse, style=filled, fillcolor=lightgreen];
Process [shape=box, style=filled, fillcolor=lightblue];
Decision [shape=diamond, style=filled, fillcolor=yellow];
End [shape=ellipse, style=filled, fillcolor=salmon];

Start -> Process;
Process -> Decision;
Decision -> Yes [label="Yes"] -> End;
Decision -> No [label="No"] -> Process;
}

Class Diagram

dot
digraph Classes {
rankdir=TB;
node [shape=record fontname=Helvetica fontsize=10];

Animal [label="<name> name | <age> age | <sound> sound"];
Dog [label="<name> name | <breed> breed | <fetch> fetch"];
Cat [label="<name> name | <lives> lives | <meow> meow"];

Dog -> Animal [label="extends" arrowhead=obox dir=both];
Cat -> Animal [label="extends" arrowhead=obox dir=both];
}

State Machine

dot
digraph States {
rankdir=LR;
node [shape=circle, width=0.5];

init [shape=doublecircle, label=""];
active [label="Active"];
pending [label="Pending"];

init -> active [label="start"];
active -> pending [label="pause"];
pending -> active [label="resume"];
active -> active [label="tick", loop=true, labelabove=true];
}

Family Tree

dot
digraph Family {
rankdir=TB;
node [shape=box, style=filled];

{ rank=same; F1; M1; }
{ rank=same; C1; C2; C3; }

F1 [label="Father", fillcolor=lightblue];
M1 [label="Mother", fillcolor=lightpink];
C1 [label="Child 1"];
C2 [label="Child 2"];
C3 [label="Child 3"];

F1 -> C1; F1 -> C2; F1 -> C3;
M1 -> C1; M1 -> C2; M1 -> C3;
}

Color Wheel

dot
graph {
layout=neato;
node [style=filled];

"Red" [fillcolor=red];
"Orange" [fillcolor=orange];
"Yellow" [fillcolor=yellow];
"Green" [fillcolor=green];
"Blue" [fillcolor=blue];
"Indigo" [fillcolor=indigo];
"Violet" [fillcolor=violet];

"Red" -- "Orange" -- "Yellow" -- "Green" -- "Blue" -- "Indigo" -- "Violet" -- "Red";
}

Network Diagram

dot
digraph Network {
rankdir=TB;
node [shape=cylinder, style=filled, fillcolor=lightblue];

Internet [shape=cloud, label="Internet", fillcolor=lightgray];
Firewall [label="Firewall", fillcolor=yellow];
Router [label="Core Router"];
Switch [label="Switch"];
Servers [shape=cylinder, label="Servers", fillcolor=lightgreen];

Internet -> Firewall -> Router -> Switch -> Servers;
}



Useful Tools & Libraries

Online Tools

ToolURLDescription
Graphviz OnlineBrowser-based DOT playground
SVG Outputdot graph.dot -TsvgScalable vector output

CLI Tools

ToolPurpose
dotHierarchical layout
neatoSpring model layout
fdpForce-directed layout
sfdpLarge-scale force-directed
twopiRadial layout
circoCircular layout
osageCluster grid layout
patchworkTreemap layout
dotty / gvGraphviz GUI viewer
xdotX11 display
dot2texConvert DOT to TikZ/LaTeX
gvprGraphviz pattern processing language

Programming Libraries

LibraryLanguageDescription
libgraphvizCCore library for embedding
pygraphvizPythonPython bindings
pydotPythonPure Python DOT parser/renderer
gvHaskellHaskell bindings
graphvizRubyRuby gem
graphvizPHPPHP extension
graphvizRustRust bindings
graphvizJavaJava bindings (via JNI)

Alternative Diagramming Tools

ToolDescription
D2Modern alternative with nicer syntax
PlantUMLUML-focused with ASCII art
MermaidDiagrams-as-code, renders inline in Markdown
TikZLaTeX vector graphics
Draw.ioWeb-based diagramming
yEdDesktop diagram tool

Integrations

IntegrationDescription
Vim/Neovim:Graphviz plugins for inline rendering
VS CodeGraphviz syntax extensions
RMarkdowndot code chunks
JupyterIPython graphviz magic
LaTeXdot2tex for TikZ output
MakeAuto-generate graphs from dependencies



Installation

macOS

bash
brew install graphviz

Debian/Ubuntu

bash
sudo apt install graphviz

Fedora/RHEL

bash
sudo dnf install graphviz

Windows (Chocolatey)

bash
choco install graphviz

Windows (Winget)

bash
winget install Graphviz

Arch Linux

bash
pacman -S graphviz

From Source

bash
git clone https://gitlab.com/graphviz/graphviz.git
cd graphviz
./autogen.sh
./configure
make
sudo make install

Python Bindings

bash
pip install pygraphviz # Requires graphviz C library
pip install pydot # Pure Python, no C dependency



Common Patterns

Automatic File Extension Output

bash
# Output to same filename with format extension
dot -O graph.dot # creates graph.dot.png
dot -Tsvg graph.dot -o graph.svg

Force Layout from Attributes

dot
digraph {
// Override layout engine via attribute
graph [layout=neato];
A -> B;
B -> C;
}

Invisible/Hidden Elements

dot
digraph {
// Invisible nodes/edges
Hidden [shape=point width=0];
A -> Hidden [style=invis];
Hidden -> B;
}

Rank Constraints

dot
digraph {
// Force nodes on same rank
subgraph { rank=same; A; B; C; }

// Force minimum rank
subgraph { rank=min; Start; }

// Force maximum rank
subgraph { rank=max; End; }
}



Resources

• Official Website: https://graphviz.org
• Documentation: https://graphviz.org/docs/
• GitLab: https://gitlab.com/graphviz/graphviz
• Gallery: https://graphviz.org/gallery/
• Forum: https://forum.graphviz.org/
• Attribute Reference: https://graphviz.org/doc/info/attrs.html
• DOT Language Reference: https://graphviz.org/doc/info/lang.html