How to externalize TikZ pictures
There are two questions hidden in your post, they have two answers that are basically orthogonal:
#Speeding up compilation by using tikzexternalize
:
You don't actually have to write them into separate files to save compilation time. You can leave your code almost unchanged, that's the beauty of it. This is the simplest possible setup with externalization
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{external}
\tikzexternalize[prefix=figures/] % activate and define figures/ as cache folder
\begin{document}
\begin{tikzpicture}
\node {real complex figure};
\end{tikzpicture}
\end{document}
This will only run if your LaTeX is set up to run with shell escape (pdflatex -synctex=1 -interaction=nonstopmode --shell-escape %.tex
, see here for example)
#Having tidy code, by writing TikZ code into separte files:
Of course you can also store the \begin{tikzpicture}...\end{tikzpicture}
code in an external .tex
or .tikz
file and use \input
to include it. But that is a matter of taste and does not effect compilation performance.
You could write
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{external}
\tikzexternalize[prefix=figures/]
\begin{document}
\input{tikzfigure1.tikz}
\end{document}
and
into tikzfigure1.tikz
:
\begin{tikzpicture}
\node {real complex figure};
\end{tikzpicture}
I tend to define my own command to include tikz
files, instead of using \input
in order to take care of one more thing:
\newcommand{\inputtikz}[1]{%
\tikzsetnextfilename{#1}%
\input{#1.tikz}%
}
This will make sure that the externalization is based on the file name (instead of the order) so that it doesn't get confused if you change the orders of TikZ pictures in your document.
I prefer a manual way to externalize TikZ pictures. This gives you full control and does not require any shell escape huzzle.
Put every TikZ image in a file of its own (good for keeping track of your code anyways). Use this template (e.g. ext-img1.tex):
\documentclass[tikz]{standalone} \usepackage{tikz} \begin{document} % \begin{tikzpicture} <your tikz code here> \end{tikzpicture} % \end{document}
Include the external image in your main document:
\begin{figure} \includegraphics{ext-img1.pdf} \caption{external image} \end{figure}
Compile the external image
pdflatex ext-img1.tex
Compile the main document
Whenever you want to modify the image, you have to rebuild the file defined in the first step.