> For the complete documentation index, see [llms.txt](https://overleaf-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://overleaf-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` 更改为 `输出`，这会影响外部化（生成）的 TikZ 图形的名称：默认情况下，生成的图形文件命名为 `output-figureN.EXT` 其中
  * `N` 是根据图形出现的顺序/次序得出的整数（`N`=0, 1, 2, ...);
  * `EXT` 是 TikZ 使用的文件扩展名之一，包括 `pdf`, `md5` 和 `dpth` （也包括 `log`).
* **一个注意事项**：如果你在上传图形文件后，随后又修改了项目中的 TikZ 代码，可能需要删除 `tikz` 文件夹中对应的图形文件，这样 Overleaf 才能生成并使用新版本。或者，你也可以在本地机器上重新生成这些文件并再次上传到 Overleaf。请记住，你需要替换该特定 TikZ 绘图的所有 `.pdf`, `.md5` 和 `.dpth` 文件。

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

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

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

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

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

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

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

使用 `standalone` 或 `预览` 宏包来创建一个包含 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}
```

&#x20;[在 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 宏包**

下面是一些使用 `预览` 宏包的示例代码：

```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}
```

&#x20;[在 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://overleaf-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.
