TikZ PGF – How to Draw a Convex Hull with TikZ in LaTeX

tikz-pgf

I want to draw a convex hull with tikz.

\documentclass{article}

\usepackage{tikz}

\begin{document}

\begin{center}
\begin{tikzpicture}

\def\us{(0,2),(1,4),(2,0),(3,2),(4,1),(6,2),(6,4)}

\foreach \u [count=\i from 1] in \us {\node (u\i) at \u [right] {$u_\i$};}

\fill[fill=blue] (u1) -- (u2) -- (u3);
% \fill[red] (0,2) -- (2,0) -- (3,2);

\end{tikzpicture}
\end{center}

\end{document}

If I'm right, this should draw a filled blue triangle.
But it doesn't! Why? If instead, I comment out the \fill[red] line, I do see a result.

Thank you, Adrian.

Best Answer

This is because TikZ automatically uses the most appropriate anchor to connect two nodes, so you do not actually have a triangle, you have two edges.

Try

\fill[fill=blue] (u1.center) -- (u2.center) -- (u3.center) ;

instead, it will show the difference.

Other ways are to use

\def\us{0/2,1/4,2/0,3/2,4/1,6/2,6/4}
\foreach \x/\y [count=\i from 1] in \us {
   \coordinate[label=right:$u_\i$] (u\i) at (\x,\y);
} 

instead, as coordinates are automatically connected using their "center" anchor.

Finally, a more sophisticated way might be this one:

\def\us{(0,2)/left,(1,4)/right,(2,0)/right,
   (3,2)/above,(4,1)/above,(6,2)/below,(6,4)/below}

\foreach \u/\pos [count=\i from 1] in \us {
   \node[shape=coordinate,label=\pos:$u_\i$] (u\i) at \u {};
}

This gives you the possibility to set the label position individually for each coordinate so that they are not interfering with connecting lines etc.