TikZ Directed Graph Example
Sometimes you’re in LaTeX and you need to draw a directed graph. You can do this in another piece of software and include the resulting image in your document, but why not do it directly in LaTeX?
For this post, I’ve pulled a graph from one of my assignments to show a simple example of using TikZ. TikZ is a very complex and powerful package, so I won’t be explaining much. This example is intended to be used by copying and pasting it into your own document and modifying it to create the graph you want.
The code is as follows:
\documentclass[12pt,letterpaper]{report}
\usepackage{pgf, tikz}
\usetikzlibrary{arrows, automata}
\begin{document}
\begin{tikzpicture}[
> = stealth, % arrow head style
shorten > = 1pt, % don't touch arrow head to node
auto,
node distance = 3cm, % distance between nodes
semithick % line style
]
\tikzstyle{every state}=[
draw = black,
thick,
fill = white,
minimum size = 4mm
]
\node[state] (s) {$s$};
\node[state] (v1) [above right of=s] {$v_1$};
\node[state] (v2) [right of=s] {$v_2$};
\node[state] (v3) [below right of=s] {$v_2$};
\node[state] (t) [right of=v2] {$t$};
\path[->] (s) edge node {18} (v1);
\path[->] (s) edge node {1} (v2);
\path[->] (s) edge node {1} (v3);
\path[->] (v2) edge node {2} (v1);
\path[->] (v3) edge node {1} (v2);
\path[->] (v1) edge node {20} (t);
\draw[red, dashed] (1, 2) -- (1, -2);
\end{tikzpicture}
\end{document}
And it produces the following result:
There are more examples available for graphs in TikZ on TeXample.net. Hope this helps!