How to use TikZ externalize with PGFgantt

I recently switched on tikzexternalize on a document with several figures created by TikZ in it. Activating this Tikz library has the advantage of compiling the figures only once (if unchanged), speeding up the creation of the completed document. As a nice side benefit, one gets the images as separate PDF files, which in my case was the main motivation. One simple call to ImageMagick later, one has all images in a format of choice. However, I could not get it to work at first due to my using the PGFgantt package to create a gantt time chart. Here is the (not compiling) start point:

\documentclass{article}
\usepackage{tikz}
\usepackage{pgfgantt}

\usetikzlibrary{external}
\tikzexternalize

\begin{document}
  
\begin{figure}
  \begin{ganttchart}[
      time slot format=isodate,
      compress calendar]
        {2018-01-01}{2018-12-31}
    \gantttitle{Col 1}{6}
    \gantttitle{Col 2}{6}\\
    \gantttitlecalendar{month} \\
    \ganttbar{Panic}{2018-02-01}{2018-04-21} \\
    \ganttbar{Sorrow}{2018-06-01}{2018-10-12}
  \end{ganttchart}
\end{figure}

\end{document}

Compiling this leads to the following error:

! File ended while scanning use of 
\tikzexternal@laTeX@collect@until@end@tikzpicture.

Solution

Simply wrap the ganttchart environment in an additional tikzpicture one like this:

\begin{figure}
  \begin{tikzpicture}
  \begin{ganttchart}
    [...]
  \end{ganttchart}
  \end{tikzpicture}
\end{figure}

Explanation

Why does this work? To understand this, it is helpful to review how TikZexternalize works: In order to identify the code of figure environments to externalize, the document is searched through for occurrences of a \begin{tikzpicture}. This search also finds these commands if they are “hidden” behind macro definitions. PGFgantt’s \begin{ganttchart} is such a case. To determine the endpoint for the figure to be compiled, externalize now only searches for occurrences of \end{tikzpicture} that are in the code verbatim. (I did not look up the reason for this, but I guess there is a very good reason why the endpoint search cannot expand macro definitions. Probably limiting complexity of the parser has a huge part in this.) As you can see in the start point code box, there is no \end{tikzpicture} in sight, leading to the above error message. By providing the wrapper tikzpicture environment around ganttchart, TikZexternalize can do its job properly.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.