# Why does fitting fail in TikZ in the second image?

I have a document with two tikz pictures, both use the fit library. As long as I only have one picture everything works fine:

\documentclass[a4paper]{article}
\usepackage[english]{babel}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
\usetikzlibrary{fit}
\node(n){x};
\node [fit=(n),draw]{};
\end{tikzpicture}
\end{document}


As soon as I add a second picture:

\documentclass[a4paper]{article}
\usepackage[english]{babel}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
\usetikzlibrary{fit}
\node(n){x};
\node [fit=(n),draw]{};
\end{tikzpicture}
\begin{tikzpicture}
\usetikzlibrary{fit}
\node(n){x};
\node [fit=(n),draw]{};
\end{tikzpicture}
\end{document}


I get the following error

Package pgfkeys Error: I do not know the key '/tikz/fit' and I am going to ignore it. Perhaps you misspelled it.

Why is the pgfkey suddenly missing in the second picture and what can I do to fix it?

-

You have to include \usetikzlibrary{fit} only once, outside the \begin{tikzpicture}

\documentclass[a4paper]{article}
\usepackage[english]{babel}
\usepackage{tikz}
\usetikzlibrary{fit}

\begin{document}

\begin{tikzpicture}
\node(n){x};
\node [fit=(n),draw]{};
\end{tikzpicture}

\begin{tikzpicture}
\node(n){x};
\node [fit=(n),draw]{};
\end{tikzpicture}

\end{document}


-
Of course. It is kind of embarrassing that I did not think of that. Thank you! –  Maeher Jun 15 '12 at 10:58

To add to the already-existing answers, the reason why your original code doesn't work is for the combination of the following two factors:

1. TikZ has some code that ensures that it only loads a given library once. This means that packages and so forth can freely put \usetikzlibrary{something} without fear of loading the library more than once. The test is global in scope.
2. When the fit library is loaded, it sets a whole slew of code and keys. These are local in scope. Normally, this is not a problem as it is usual to load TikZ libraries in the preamble (it doesn't actually matter with the fit library, but others might need this so it's a good habit to get into).

So when you first load the fit library, it loads in the definitions and keys but these are local to the first tikzpicture. When that ends, all the definitions and keys are forgotten. So when you try to load it again in the second definition, it knows that it has already loaded it because the test is global. But it has forgotten what it loaded. So the definitions and keys are not set up and consequently the library is unusable.

-

\usetikzlibrary{fit} belongs into the preamble, not into the tikzpicture environment. Loading it there seems to work anyway, but loading it twice causes issues. Simply place it into the preamble.

-