# TikZ: Draw the smallest rectangle containing given points with sides parallel to coordinate axes

I need a TikZ macro to draw the smallest rectangle around a list of points, with sides parallel to the coordinate axes. In a perfect world it would work with any number of points greater than 1, but I would be happy if it just worked with 3. The points will usually be of the form

([yshift=10pt] A.north)


That is, they will generally be anchors of shapes, possibly shifted manually.

-
Should the rectangle be parallel to axes or general? Because for the general one, the problem is really not easy (from the teoretical-geometrical point of view). – yo' Sep 24 '12 at 13:30
If the rectangle is in the standard orientation, the fit library would seem to be a good ... fit. – Loop Space Sep 24 '12 at 13:31
Thanks for pointing this out, question updated. – Jamie Vicary Sep 24 '12 at 13:32
Sorry to be pedantic, but are the coordinate axes transformed in any way, or do you mean them to be "What TeX thinks are left-right and up-down"? If not transformed, then I really think that the fit library is what you're looking for. – Loop Space Sep 24 '12 at 13:44
My axes are not transformed. The fit library sounds good... – Jamie Vicary Sep 24 '12 at 13:57

## Code

\documentclass[tikz,border=5mm]{standalone}
\usetikzlibrary{calc,fit,positioning}

\begin{document}

\begin{tikzpicture}
% some nodes
\node[fill=red,circle,inner sep=2mm] (A) at (0,0) {};
\node[fill=blue,circle,inner sep=4mm] (B) at (4,-1) {};
\node[fill=violet,circle,inner sep=3mm] (C) at (1,3) {};

% a node, relatively shifted
\node[fill=orange,circle] (D) at ([yshift=5mm,xshift=15mm] A.north) {};

% outer fit
\node[thick,draw=red,fit=(A)(B)(C)] {};
\node[thick,draw=blue,fit=(A)(B)(C),inner sep=0] {};

% inner fit
\node[thick,draw=red,fit=(A.east)(B.north west)(C.south),densely dotted] {};
\node[thick,draw=blue,fit=(A.east)(B.north west)(C.south),inner sep=0,densely dotted] {};
\node[thick,draw=violet,fit=(A.east)(B.north west)(C.south),inner sep=-3pt,densely dotted] {};

% center fit with shifted node, as ([options] node) does not work
\node[thick,draw=orange,fit=(A.center)(B.center)(D.center),densely dashed,inner sep=0] {};

% same as above with calc's ($()+()$); note that you can't use coordinates as (x,y), you have
%   to enclose the coordinates in braces: ({x,y})
\node[thick,draw=orange,fit=(A.center)(B.center)($(A.north)+({1.5,0.5})$),densely dashed] {};
\end{tikzpicture}

\end{document}


## Output

-
+1: Nice. Wondering if there is a way to automate the inner fit -- I thought simply figuring out the size of the node would be enough, but then realized that knowing that would not be sufficient easy, as you don't know which way to tweak the point. – Peter Grill Oct 11 '12 at 16:41