Draw a graph with nodes and edges in LaTeX (TikZ)

Draw every vertex as a named TikZ node with \node[circle, draw] (a) at (0,0) {A}; and every edge as a line between two names with \draw (a) -- (b);.

Preamble

The snippets on this page need these lines before \begin{document}:

\usepackage{tikz}

Draw vertices and edges

The style vertex in the options of tikzpicture saves you from repeating circle, draw for every node; minimum size gives all circles the same diameter. Several -- in one \draw form a chain of edges.

\begin{tikzpicture}[vertex/.style={circle, draw, minimum size=7mm}]
\node[vertex] (a) at (0,0) {A};
\node[vertex] (b) at (2,1) {B};
\node[vertex] (c) at (2,-1) {C};
\node[vertex] (d) at (4,0) {D};
\draw (a) -- (b) -- (d) -- (c) -- (a);
\draw (b) -- (c);
\end{tikzpicture}
Result
The compiled example

Open in the editor

Add directions and weights

-> turns an edge into an arrow, and >=stealth selects a pointed arrow tip. A node after -- puts the weight at the middle of the edge; above, below left and so on move it off the line.

\begin{tikzpicture}[vertex/.style={circle, draw, minimum size=7mm}, >=stealth]
\node[vertex] (a) at (0,0) {A};
\node[vertex] (b) at (2,1) {B};
\node[vertex] (c) at (2,-1) {C};
\node[vertex] (d) at (4,0) {D};
\draw[->] (a) -- node[above left] {4} (b);
\draw[->] (a) -- node[below left] {2} (c);
\draw[->] (c) -- node[right] {1} (b);
\draw[->] (b) -- node[above right] {5} (d);
\draw[->] (c) -- node[below right] {8} (d);
\end{tikzpicture}
Result
The compiled example

Open in the editor

Bend edges and draw loops

With \path[->], each edge draws one connection from the node before it. bend left curves the edge to the left as seen in its direction, so two opposite edges do not overlap. loop above draws an edge from a node back to itself.

\begin{tikzpicture}[vertex/.style={circle, draw, minimum size=7mm}, >=stealth]
\node[vertex] (p) at (0,0) {$q_0$};
\node[vertex] (q) at (3,0) {$q_1$};
\path[->] (p) edge[bend left] node[above] {a} (q)
          (q) edge[bend left] node[below] {b} (p)
          (q) edge[loop above] node[above] {a} (q);
\end{tikzpicture}
Result
The compiled example

Open in the editor

Place vertices on a circle

A polar coordinate (angle:radius) places a vertex on a circle around the origin. Two nested \foreach loops then connect every pair of vertices, which gives the complete graph with five vertices here.

\begin{tikzpicture}[vertex/.style={circle, draw, inner sep=2pt}]
\foreach \i in {1,...,5} {
  \node[vertex] (v\i) at ({90 + 72*(\i-1)}:1.5) {\i};
}
\foreach \i in {1,...,5} {
  \foreach \j in {1,...,5} {
    \ifnum\i<\j \draw (v\i) -- (v\j); \fi
  }
}
\end{tikzpicture}
Result
The compiled example

Open in the editor

Pitfalls

Compiled with pdfLaTeX from TeX Live 2023.

Related pages