> For the complete documentation index, see [llms.txt](https://ayakaleaf-pro.ayaka.space/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ayakaleaf-pro.ayaka.space/latex/zh-cn/wen-da/60-i-have-a-lot-of-tikz-matlab2tikz-or-pgfplots-figures-so-i-m-getting-a-compilation-timeout.-can-i.md).

# 我有很多 tikz、matlab2tikz 或 pgfplots 图形，因此会遇到编译超时。我可以 e

## 如何外部化 TikZ 图形

使用 TikZ [名为 `external`](https://tikz.dev/library-external) 用于创建并将 TikZ 图形存储（缓存）为 PDF 文件——这一过程通常称为“*外部化*”。

通过以下方式加载该库： `\usetikzlibrary{external}`，然后使用命令启用外部化 `\tikzexternalize`:

```latex
\usetikzlibrary{external}
\tikzexternalize[<options>]
```

其中 `<options>` 是一个可选的参数列表（键值对），用于配置该 `external` 库。

* **注意**：要使 TikZ 外部化在 Overleaf 上正常工作， `\tikzexternalize` 命令 ***必须*** 放在项目的主 `.tex` 文件中。

让我们来看一个基础示例，其中使用了来自 [TikZ 文档](https://tikz.dev/library-external):

```latex
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{external}
\tikzexternalize[prefix=tikz/]

\begin{document}
% 这个 TikZ 图形将被写入
% 一个名为 'output-figure0.pdf' 的文件中
% 位于 'tikz' 文件夹内
\begin{tikzpicture}

  \node {root}
    child {node {left}}
    child {node {right}
      child {node {child}}
      child {node {child}}
    };

\end{tikzpicture}

\end{document}
```

若要探索此示例，你可以 [在 Overleaf 上打开它。](https://www.overleaf.com/project/new/template/27519?id=1174669946\&templateName=Example+to+externalize+a+TikZ+graphic\&latexEngine=pdflatex\&texImage=texlive-full%3A2022.1\&mainFile=)

我们示例中的代码使用了选项 `prefix=tikz/` 配合 `\tikzexternalize`:

```latex
\tikzexternalize[prefix=tikz/]
```

该选项 `prefix=tikz/` 提供一个文件夹的名称（此处为 `tikz`）用于缓存生成的（外部化的）图形——你需要在项目中手动创建该文件夹。不过，在 LaTeX（TikZ 代码）可以向该文件夹写入之前，它必须包含一个文件——任何（占位）文件都可以；例如，你可以添加一个空文本文件 `foo.txt` 在 `tikz` 文件夹中。

Overleaf 将外部化的 TikZ PDF 图形视作生成的输出文件，因此它们不会出现在项目可见的文件列表中——它们实际上存在于项目中，只是对视图隐藏了——你可以查看 [生成文件](/latex/zh-cn/zhi-shi-ku/150-view-generated-files.md) 来查看它们。

下面这段（简短的）视频概述了上述示例的编译过程，并演示如何访问由 TikZ 生成的文件列表：

{% embed url="<https://videos.ctfassets.net/nrgyaltdicpt/6VZVoHzhpNzOWSTvsWYm08/80d178255345da83bcd82b5fc64e5c6b/TikZExternalize.mp4>" %}

## 一些说明

将 TikZ 图形外部化可能会给底层 TeX 引擎（pdfTeX、XeTeX、LuaTeX 等）带来较高的计算负担，因此该 `external` 库提供了一个用于“优化”该过程的选项。如果启用优化，TikZ 会尝试通过“忽略”某些复杂（耗时）但对 TikZ 并非必需的命令来减少工作量——方法是在运行时重新定义它们。此外，来自其他宏包的一些命令在外部化模式下可能会引发错误；例如， `\includepdf` 来自 `pdfpages` 宏包。为了解决这个问题，你需要“优化掉”这类命令：

```latex
\tikzexternalize[prefix=tikz/,optimize command away=\includepdf]
```

## 需要外部化的复杂图形太多了！

如果你的图形很复杂和/或数量很多，你很可能会在 Overleaf 中遇到 [编译超时](/latex/zh-cn/zhi-shi-ku/038-fixing-and-preventing-compile-timeouts.md#compiletimeout) 在初次编译期间——因为外部化文件正在生成。本节将列出一些避免编译超时的可能解决方法。

### 逐步构建

通过以下方式逐步构建你的项目： [注释掉](https://ctan.org/pkg/comment?lang=en) 项目的不同部分可能会有帮助，但请记住，所有生成文件都会在服务器上按固定间隔被垃圾回收。这样，当你下次登录时，项目可能会无法编译，你就得再次逐步重新生成它们。

### 在本地生成图形

* **注意**：本节假设你的项目使用 `\tikzexternalize[prefix=tikz/]` 将生成的图形缓存到一个名为 `tikz`.

作为一种解决方法， [下载你的 Overleaf 项目](/latex/zh-cn/zhi-shi-ku/036-exporting-your-work-from-overleaf.md) 并在本地机器上编译它，以外部化（生成）图形文件。编译完成后， `tikz` 文件夹中应包含每个生成图形的若干文件类型，包括 `*somegraphic*.pdf`, `*somegraphic*.md5` 和 `*somegraphic*.dpth`。如果你将这些文件上传到 Overleaf 项目的 `tikz` 文件夹中，它们将在编译时被使用——这样编译速度应该会相当快。因为这些文件是上传的而非生成的，所以不会被服务器删除：上传的文件永远不会被垃圾回收。

* **注意（图形文件名）**：Overleaf 将 `\jobname` 设为 `output`，这会影响外部化（生成）的 TikZ 图形的命名：默认情况下，生成的图形文件命名为 `output-figureN.EXT` 其中
  * `N` 是一个由图形出现的顺序/次序推导出的整数（`N`=0, 1, 2, ...);
  * `EXT` 是 TikZ 使用的文件扩展名之一，包括 `pdf`, `md5` 和 `dpth` （也包括 `log`).
* **注意事项**：如果在上传图形文件之后，你随后又修改了项目中的 TikZ 代码，那么可能需要删除 `tikz` 文件夹中的相应图形文件，以便 Overleaf 可以生成并使用新版本。或者，你也可以在本地机器上重新生成这些文件并重新上传到 Overleaf。请记住，你需要替换所有 `.pdf`, `.md5` 和 `.dpth` 文件，针对该特定 TikZ 图形。

### 在单独的项目中生成图形

另一种选择是创建一个仅包含 TikZ 图形的单独图形项目。一旦这些图形完成，你可以按如下方式将该单独项目中的 PDF 上传到你的主项目：

* 点击“上传文件”图标（![Overleaf file upload icon](/files/b873bc48a4c147f9f71d6245052c189d4842df06)）位于文件列表面板上方；
* 选择 **来自另一个项目**;
* ，在下拉列表中选择包含 TikZ 图形的项目；
* 选择 **从输出文件中**;
* 选择 **output.pdf** 并（可选地）为上传的文件命名。

上传后，你可以通过选择已上传 PDF 的相应页面来访问单个图形；例如，可通过如下命令：

```latex
\includegraphics[page=1]{tikzpics.pdf}
```

该 [本文末尾的视频](#videodemo) 演示了如何从单独项目上传 PDF。

#### 如何创建一个单独的图形项目

使用 `standalone` 或 `preview` 宏包来创建一个包含 TikZ 图形的单独项目——输出的 PDF 将包含与图形大小相匹配的紧密裁切页面。

**示例：standalone 宏包**

以下是使用该 `standalone` 宏包的一些示例代码：

```latex
\documentclass[tikz]{standalone}
\begin{document}
\begin{tikzpicture}
\node[fill=yellow]{Hello!};
\end{tikzpicture}

\begin{tikzpicture}
\node[fill=pink]{World!};
\end{tikzpicture}
\end{document}
```

[在 Overleaf 中打开此示例](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Example+of+standalone+package+and+TikZ\&snip=%5Cdocumentclass%5Btikz%5D%7Bstandalone%7D%0A%5Cbegin%7Bdocument%7D%0A%5Cbegin%7Btikzpicture%7D%0A%5Cnode%5Bfill%3Dyellow%5D%7BHello%21%7D%3B%0A%5Cend%7Btikzpicture%7D%0A%0A%5Cbegin%7Btikzpicture%7D%0A%5Cnode%5Bfill%3Dpink%5D%7BWorld%21%7D%3B%0A%5Cend%7Btikzpicture%7D%0A%5Cend%7Bdocument%7D)

此示例生成如下输出：

![standalone LaTeX 宏包示例](/files/a74e3c6fcd928a1bf0c9a2daa0f0b9dc9d7a3475)

**示例：preview 宏包**

以下是使用该 `preview` 宏包的一些示例代码：

```latex
\documentclass{article}
\usepackage[active,tightpage]{preview}
\setlength{\PreviewBorder}{0pt}
\usepackage{tikz}
\PreviewEnvironment[{[]}]{tikzpicture}
\begin{document}
\begin{tikzpicture}
\node[fill=yellow]{Hello!};
\end{tikzpicture}

\begin{tikzpicture}
\node[fill=pink]{World!};
\end{tikzpicture}
\end{document}
```

[在 Overleaf 中打开此示例](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Example+of+the+preview+package+and+TikZ\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%5Bactive%2Ctightpage%5D%7Bpreview%7D%0A%5Csetlength%7B%5CPreviewBorder%7D%7B0pt%7D%0A%5Cusepackage%7Btikz%7D%0A%5CPreviewEnvironment%5B%7B%5B%5D%7D%5D%7Btikzpicture%7D%0A%5Cbegin%7Bdocument%7D%0A%5Cbegin%7Btikzpicture%7D%0A%5Cnode%5Bfill%3Dyellow%5D%7BHello%21%7D%3B%0A%5Cend%7Btikzpicture%7D%0A%0A%5Cbegin%7Btikzpicture%7D%0A%5Cnode%5Bfill%3Dpink%5D%7BWorld%21%7D%3B%0A%5Cend%7Btikzpicture%7D%0A%5Cend%7Bdocument%7D)

此示例生成如下输出：

![preview LaTeX 宏包示例](/files/6240223bf9e7c20f4c618f3a0692db5cef4f40a7)

### 视频演示：从另一个 Overleaf 项目上传文件

以下视频演示如何上传一个仅包含图形的 PDF 文件（来自另一个 Overleaf 项目）——这里我们使用 `standalone` 宏包来创建包含基于 TikZ 的插图的 PDF。

{% embed url="<https://videos.ctfassets.net/nrgyaltdicpt/6l4dDatlnqzIymJLofSnQP/61f8ad4b872f5a82f3cd45c487e2f101/TikzSeparateProjects.mp4>" %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://ayakaleaf-pro.ayaka.space/latex/zh-cn/wen-da/60-i-have-a-lot-of-tikz-matlab2tikz-or-pgfplots-figures-so-i-m-getting-a-compilation-timeout.-can-i.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
