> 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-tw/te-ding-ling-yu/08-pgfplots-package.md).

# Pgfplots 套件

## 簡介

該 `pgfplots` 基於 [`TikZ`](/latex/zh-tw/tu-biao-yu-biao-ge/05-tikz-package.md)的套件，是一個強大的視覺化工具，非常適合用來建立科學／技術圖形。基本概念是你提供輸入資料／公式，而 `pgfplots` 則負責其餘部分。

### 文件前言區

若要使用 `pgfplots` 套件加入你的文件中，請在前言區加入以下這一行：

`\usepackage{pgfplots}`

你也可以在文件前言區設定 `pgfplots` 的行為。例如，要變更每個圖的大小並確保向後相容性（建議）請加入下一行：

`\pgfplotsset{width=10cm,compat=1.9}`

這會變更每個 `pgfplot` 圖的大小為 10 公分，這已經很大；你也可以使用不同單位（pt、mm、in）。 *compat* 參數是為了讓程式碼可在套件版本 1.9 或更新版本上運作。

### 編譯時間（簡短背景）

當原始的 TeX 引擎在 40 多年前被構想／撰寫時，它並不是為了 *直接* 產生圖形而設計的——那些圖形應該是由外部程式（例如 MetaPost）建立的檔案，再匯入排版文件中。pdfTeX 的出現——它與原始 TeX 軟體有密切關聯——帶來了建立圖形的能力 *直接* ，方法是使用 pdfTeX 新增的內建 TeX 語言命令（稱為 *原始命令*）其可輸出產生圖形所需的 PDF 運算子／資料。pdfTeX 的誕生促成了更進階的 LaTeX 圖形套件的發展，例如 `TikZ`, `pgfplots` 等等，這些套件能夠產生以高階 LaTeX 命令編寫的圖形。

不過在幕後，在 pdfTeX 引擎（以及其他引擎）深處，這些高階 LaTeX 圖形命令需要先被處理，方法是將它們「轉換」回低階的 pdfTeX 引擎（原始）命令，而這些命令才真正產生（輸出）所需的 PDF 運算子，以生成最終的圖形。這種對圖形化 LaTeX 命令的處理——展開與原始命令執行——可能需要相當可觀的時間。即使只有一個高階 LaTeX 圖形命令，加上其對應資料，也可能需要重複執行 *許多* 低階 TeX 引擎（原始）命令。就終端使用者而言，包含多個 `pgfplots` 圖形，和／或非常複雜圖形的文件，可能需要相當長的時間才能顯示（編譯）。

### 縮短編譯時間

若要提高文件編譯速度，你可以設定 `pgfplots` 套件將圖形輸出為獨立的 PDF 檔案，然後再將它們匯入文件中：編譯一次，接著重複使用這些圖形。要這麼做，請將下方顯示的程式碼加入前言區：

```
\usepgfplotslibrary{external}
\tikzexternalize
```

請參閱 [這篇說明文章](/latex/zh-tw/wen-yu-da/60-i-have-a-lot-of-tikz-matlab2tikz-or-pgfplots-figures-so-i-m-getting-a-compilation-timeout.-can-i.md) 以進一步了解如何在你的 Overleaf 專案中設定 tikz 外部化。

## 基本範例（也將圖形外部化）

```latex
\documentclass{article}
\usepackage[margin=0.25in]{geometry}
\usepackage{pgfplots}
\pgfplotsset{width=10cm,compat=1.9}

% 我們將把圖形外部化
\usepgfplotslibrary{external}
\tikzexternalize

\begin{document}

第一個範例是並排繪製 2D 與 3D 數學式。

% 這裡開始 2D 圖
\begin{tikzpicture}
\begin{axis}
\addplot[color=red]{exp(x)};
\end{axis}
\end{tikzpicture}
% 這裡結束 2D 圖
\hskip 5pt
% 這裡開始 3D 圖
\begin{tikzpicture}
\begin{axis}
\addplot3[
    surf,
]
{exp(-x^2-y^2)*x};
\end{axis}
\end{tikzpicture}
% 這裡結束 3D 圖

\end{document}
```

[在 Overleaf 中開啟這個 `pgfplots` Overleaf 中的範例。](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=pgfplots+example+1\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%5Bmargin%3D0.25in%5D%7Bgeometry%7D%0A%5Cusepackage%7Bpgfplots%7D%0A%5Cpgfplotsset%7Bwidth%3D10cm%2Ccompat%3D1.9%7D%0A%0A%25+We+will+externalize+the+figures%0A%5Cusepgfplotslibrary%7Bexternal%7D%0A%5Ctikzexternalize%0A%0A%5Cbegin%7Bdocument%7D%0A%0AFirst+example+is+2D+and+3D+math+expressions+plotted+side-by-side.%0A%0A%25Here+begins+the+2D+plot%0A%5Cbegin%7Btikzpicture%7D%0A%5Cbegin%7Baxis%7D%0A%5Caddplot%5Bcolor%3Dred%5D%7Bexp%28x%29%7D%3B%0A%5Cend%7Baxis%7D%0A%5Cend%7Btikzpicture%7D%0A%25Here+ends+the+2D+plot%0A%5Chskip+5pt%0A%25Here+begins+the+3D+plot%0A%5Cbegin%7Btikzpicture%7D%0A%5Cbegin%7Baxis%7D%0A%5Caddplot3%5B%0A++++surf%2C%0A%5D%0A%7Bexp%28-x%5E2-y%5E2%29%2Ax%7D%3B%0A%5Cend%7Baxis%7D%0A%5Cend%7Btikzpicture%7D%0A%25Here+ends+the+3D+plot%0A%0A%5Cend%7Bdocument%7D)

下圖顯示了以上程式碼產生的結果：

![Plgplotsex1OLV2.png](/files/980aa1194755621107394aebc7703ce2497cf5f6)

### 程式碼說明

因為 `pgfplots` 是以 `tikz` 為基礎，圖形必須放在一個 `tikzpicture` 環境中。接著，環境宣告 `\begin{axis}`, `\end{axis}` 會為圖形設定正確的縮放比例——請查看 [參考指南](#reference-guide) 以了解其他座標軸環境。

要加入實際圖形，請使用命令 `\addplot[color=red]{log(x)};` 。在方括號內 `[...]`，可以傳入一些選項；在這裡，我們把圖形的 `color` 設為 `red`。方括號是必須的；如果沒有傳入任何選項，請在其中留白。大括號內放入要繪製的函數。請記得此命令必須以分號（;）結尾。

若要在第一個圖旁邊放第二個圖，請宣告一個新的 `tikzpicture` 環境。不要換行，而是留一小段空白，在此情況下 `\hskip 10pt` 會插入一個寬度為 10pt 的空白。

其餘語法相同，除了 `\addplot3 [surf,]{exp(-x^2-y^2)*x};`。這會新增一個 3D 圖，而選項 `surf` 在方括號內表示這是一個曲面圖。要繪製的函數必須放在大括號內。同樣地，別忘了在命令結尾加上分號（;）。

**注意**：建議養成良好習慣，將程式碼縮排——請參考上方範例中的第二個圖——並在傳入 `\addplot`的每個選項後面加上逗號（,）。如此一來程式碼會更易讀，也更方便在需要時加入更多選項。

## 2D 圖形

`pgfplots`的 2D 繪圖功能非常豐富——而且你可以依需求客製化圖形。不過，預設選項通常已經能產生很好的結果，所以你只需要提供資料，LaTeX 就會負責其餘部分。

### 繪製數學式

範例如下：

```latex
\begin{tikzpicture}
\begin{axis}[
    axis lines = left,
    xlabel = \(x\),
    ylabel = {\(f(x)\)},
]
% 下方定義紅色拋物線
\addplot [
    domain=-10:10,
    samples=100,
    color=red,
]
{x^2 - 2*x - 1};
\addlegendentry{\(x^2 - 2x - 1\)}
% 這裡定義藍色拋物線
\addplot [
    domain=-10:10,
    samples=100,
    color=blue,
    ]
    {x^2 + 2*x + 1};
\addlegendentry{\(x^2 + 2x + 1\)}

\end{axis}
\end{tikzpicture}
```

[在 Overleaf 中開啟這個 `pgfplots` Overleaf 中的範例。](https://www.overleaf.com/docs?engine=\&snip_name=pgfplots+example+2\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%5Bmargin%3D0.25in%5D%7Bgeometry%7D%0A%5Cusepackage%7Bpgfplots%7D%0A%5Cpgfplotsset%7Bwidth%3D10cm%2Ccompat%3D1.9%7D%0A%5Cbegin%7Bdocument%7D%0A%5Cbegin%7Btikzpicture%7D%0A%5Cbegin%7Baxis%7D%5B%0A++++axis+lines+%3D+left%2C%0A++++xlabel+%3D+%5C%28x%5C%29%2C%0A++++ylabel+%3D+%7B%5C%28f%28x%29%5C%29%7D%2C%0A%5D%0A%25Below+the+red+parabola+is+defined%0A%5Caddplot+%5B%0A++++domain%3D-10%3A10%2C+%0A++++samples%3D100%2C+%0A++++color%3Dred%2C%0A%5D%0A%7Bx%5E2+-+2%2Ax+-+1%7D%3B%0A%5Caddlegendentry%7B%5C%28x%5E2+-+2x+-+1%5C%29%7D%0A%25Here+the+blue+parabola+is+defined%0A%5Caddplot+%5B%0A++++domain%3D-10%3A10%2C+%0A++++samples%3D100%2C+%0A++++color%3Dblue%2C%0A++++%5D%0A++++%7Bx%5E2+%2B+2%2Ax+%2B+1%7D%3B%0A%5Caddlegendentry%7B%5C%28x%5E2+%2B+2x+%2B+1%5C%29%7D%0A%0A%5Cend%7Baxis%7D%0A%5Cend%7Btikzpicture%7D%0A%5Cend%7Bdocument%7D)

這段程式碼的輸出如下圖所示——當你開啟連結時，LaTeX 文件前言區會自動加入：

![Plgplotsex2.png](/files/be9870b1e5c6254b13d5b607ecf488979e48699e)

#### 程式碼說明

讓我們逐行分析這些新命令：

**axis lines = left。**

這會將座標軸設定為只顯示在圖的左側與下方，而不是預設的方框。更多自訂選項請參考說明指南。

**xlabel = (x) 和 ylabel = {(f(x))}。**

這些參數名稱顧名思義，會讓你在水平與垂直座標軸上加入標籤。請注意 ylabel 的值被大括號包住，這些括號會告訴 pgfplots 如何分組文字。xlabel 也可以加上括號。這對於較複雜、可能讓 pgfplots 混淆的標籤很有用。

**\addplot。**

這會把一條圖形加到座標軸上，基本用法已在前言中說明。在這個範例中有兩個新參數。

**domain=-10:10。**

這會設定 x 值的範圍。

**samples=100。**

決定由 domain 定義區間中的點數。samples 的值越大，圖形越細緻，但渲染所需時間也會越長。

**\addlegendentry{(x^2 - 2x - 1)}。**

這會加入圖例，以識別函數 x^2 - 2x - 1。

若要再新增另一個圖形，只要寫一個新的 `\addplot` 項目。

### 根據資料繪圖

科學研究常常會產生需要分析的資料。下一個範例將示範如何使用 *pgfplots*:

```latex
根據資料繪圖：

\begin{tikzpicture}
\begin{axis}[
    title={CuSO\(_4\cdot\)5H\(_2\)O 溶解度的溫度依賴性},
    xlabel={溫度 [\textcelsius]},
    ylabel={溶解度 [每 100 g 水中的 g 數]},
    xmin=0, xmax=100,
    ymin=0, ymax=120,
    xtick={0,20,40,60,80,100},
    ytick={0,20,40,60,80,100,120},
    legend pos=north west,
    ymajorgrids=true,
    grid style=dashed,
]

\addplot[
    color=blue,
    mark=square,
    ]
    coordinates {
    (0,23.1)(10,27.5)(20,32)(30,37.8)(40,44.6)(60,61.8)(80,83.8)(100,114)
    };
    \legend{CuSO\(_4\cdot\)5H\(_2\)O}

\end{axis}
\end{tikzpicture}
```

[在 Overleaf 中開啟這個 `pgfplots` Overleaf 中的範例。](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=pgfplots+example+3\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%5Bmargin%3D0.5in%5D%7Bgeometry%7D%0A%5Cusepackage%7Btextcomp%7D%0A%5Cusepackage%7Bpgfplots%7D%0A%5Cpgfplotsset%7Bwidth%3D10cm%2Ccompat%3D1.9%7D%0A%25%5Cusepgfplotslibrary%7Bexternal%7D%0A%25%5Ctikzexternalize%0A%5Cbegin%7Bdocument%7D%0APlotting+from+data%3A%0A%0A%5Cbegin%7Btikzpicture%7D%0A%5Cbegin%7Baxis%7D%5B%0A++++title%3D%7BTemperature+dependence+of+CuSO%5C%28_4%5Ccdot%5C%295H%5C%28_2%5C%29O+solubility%7D%2C%0A++++xlabel%3D%7BTemperature+%5B%5Ctextcelsius%5D%7D%2C%0A++++ylabel%3D%7BSolubility+%5Bg+per+100+g+water%5D%7D%2C%0A++++xmin%3D0%2C+xmax%3D100%2C%0A++++ymin%3D0%2C+ymax%3D120%2C%0A++++xtick%3D%7B0%2C20%2C40%2C60%2C80%2C100%7D%2C%0A++++ytick%3D%7B0%2C20%2C40%2C60%2C80%2C100%2C120%7D%2C%0A++++legend+pos%3Dnorth+west%2C%0A++++ymajorgrids%3Dtrue%2C%0A++++grid+style%3Ddashed%2C%0A%5D%0A%0A%5Caddplot%5B%0A++++color%3Dblue%2C%0A++++mark%3Dsquare%2C%0A++++%5D%0A++++coordinates+%7B%0A++++%280%2C23.1%29%2810%2C27.5%29%2820%2C32%29%2830%2C37.8%29%2840%2C44.6%29%2860%2C61.8%29%2880%2C83.8%29%28100%2C114%29%0A++++%7D%3B%0A++++%5Clegend%7BCuSO%5C%28_4%5Ccdot%5C%295H%5C%28_2%5C%29O%7D%0A++++%0A%5Cend%7Baxis%7D%0A%5Cend%7Btikzpicture%7D%0A%5Cend%7Bdocument%7D)

這段程式碼的輸出如下圖所示——當你開啟連結時，LaTeX 文件前言區會自動加入：

![Plgplotsex3.png](/files/20da74842d5ed991b6b945fd85fed8375ba4fc28)

#### 程式碼說明

這裡有一些新的命令與參數：

**title={CuSO(\_4\cdot)5H(\_2)O 溶解度的溫度依賴性}。**

如你所料，這會為圖形指定標題。標題會顯示在圖上方。

**xmin=0, xmax=100, ymin=0, ymax=120。**

x 與 y 座標軸的最小與最大界限。

**xtick={0,20,40,60,80,100}, ytick={0,20,40,60,80,100,120}。**

放置標記的位置。如果留空，刻度會自動設定。

**legend pos=north west。**

圖例框的位置。請查看說明指南以取得更多選項。

**ymajorgrids=true。**

這會啟用／停用 y 軸刻度位置上的網格線。若要在 x 軸上啟用網格線，請使用 xmajorgrids。

**grid style=dashed。**

顧名思義。用來顯示虛線網格。

**mark=square。**

這會在 coordinates 陣列中的每個點畫出方形標記。每個標記都會用直線連到下一個。

**coordinates {(0,23.1)(10,27.5)(20,32)...}**

要繪製的點的座標。這就是你想以圖形方式分析的資料。

如果資料在檔案中，而這通常是情況；那麼不要使用命令 `\addplot` 和 `coordinates` ，而應該使用 `\addplot table {file_with_the_data.dat}`，其餘選項在這個環境中都適用。

### 散佈圖

散佈圖用來透過某種標記來表示資訊，通常用於計算統計迴歸時。在這個範例中，我們將使用名為 `scattered_example.dat`的檔案中所包含的資料來建立散佈圖，其中的資料如下：

```
GPA  ma  ve  co   un
3.45 643 589 3.76 3.52
2.78 558 512 2.87 2.91
2.52 583 503 2.54 2.4
3.67 685 602 3.83 3.47
3.24 592 538 3.29 3.47
2.1 562 486 2.64 2.37
...
```

我們的散佈圖使用資料的前兩欄：

```latex
\begin{tikzpicture}
\begin{axis}[
    enlargelimits=false,
]
\addplot+[
    only marks,
    scatter,
    mark=halfcircle*,
    mark size=2.9pt]
table[meta=ma]
{scattered_example.dat};
\end{axis}
\end{tikzpicture}
```

![Scattered.png](/files/2875473356e24e537b28f1105aee7541202402b5)

[在 Overleaf 中開啟一個散佈圖專案範例（包含資料檔 `scattered_example.dat`).](https://www.overleaf.com/project/new/template/20099?id=68399290\&templateName=Scatter+plot+example\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=)

#### 程式碼說明

傳入 `axis` 和 `addplot` 環境的參數也可以用在資料圖中，除了 `scatter`之外。以下是程式碼說明：

**enlarge limits=false**

這會縮小座標軸，讓最大與最小值的點位於圖的邊緣。

**only marks**

顧名思義，會在每個點上放置標記。

**scatter**

使用 scatter 時，點的顏色會依某個值而定，而顏色由下方解釋的 meta 參數給出。

**mark=halfcircle**\*

每個點要使用的標記類型，請參考說明指南中的可用值列表。

**mark size=2.9pt**

每個標記的大小，可使用不同單位。

**table\[meta=ma]{scattered\_example.dat};**

這裡 table 命令告訴 latex 要繪製的資料位於檔案中。傳入 meta=ma 參數以選擇決定每個點顏色的欄位。大括號內是資料檔名稱。

### 長條圖

長條圖（也稱為 bar chart 和 bar plot）用來顯示已蒐集的資料，主要是某類族群的統計資料。 `pgfplots` 中的長條圖具有高度可設定性，但在這裡我們將展示一個簡單範例：

```latex
\begin{tikzpicture}
\begin{axis}[
	x tick label style={
		/pgf/number format/1000 sep=},
	ylabel=Year,
	enlargelimits=0.05,
	legend style={at={(0.5,-0.1)},
	anchor=north,legend columns=-1},
	ybar interval=0.7,
]
\addplot
	coordinates {(2012,408184) (2011,408348)
		 (2010,414870) (2009,412156)};
\addplot
	coordinates {(2012,388950) (2011,393007)
		(2010,398449) (2009,395972)};
\legend{Men,Women}
\end{axis}
\end{tikzpicture}
```

[在 Overleaf 中開啟這個 `pgfplots` Overleaf 中的長條圖程式碼範例。](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=pgfplots+bar+chart+example\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%5Bmargin%3D0.5in%5D%7Bgeometry%7D%0A%5Cusepackage%7Btextcomp%7D%0A%5Cusepackage%7Bpgfplots%7D%0A%5Cpgfplotsset%7Bwidth%3D10cm%2Ccompat%3D1.9%7D%0A%25%5Cusepgfplotslibrary%7Bexternal%7D%0A%25%5Ctikzexternalize%0A%5Cbegin%7Bdocument%7D%0A%5Cbegin%7Btikzpicture%7D%0A%5Cbegin%7Baxis%7D%5B%0A%09x+tick+label+style%3D%7B%0A%09%09%2Fpgf%2Fnumber+format%2F1000+sep%3D%7D%2C%0A%09ylabel%3DYear%2C%0A%09enlargelimits%3D0.05%2C%0A%09legend+style%3D%7Bat%3D%7B%280.5%2C-0.1%29%7D%2C%0A%09anchor%3Dnorth%2Clegend+columns%3D-1%7D%2C%0A%09ybar+interval%3D0.7%2C%0A%5D%0A%5Caddplot+%0A%09coordinates+%7B%282012%2C408184%29+%282011%2C408348%29%0A%09%09+%282010%2C414870%29+%282009%2C412156%29%7D%3B%0A%5Caddplot+%0A%09coordinates+%7B%282012%2C388950%29+%282011%2C393007%29+%0A%09%09%282010%2C398449%29+%282009%2C395972%29%7D%3B%0A%5Clegend%7BMen%2CWomen%7D%0A%5Cend%7Baxis%7D%0A%5Cend%7Btikzpicture%7D%0A%5Cend%7Bdocument%7D)

這段程式碼的輸出如下圖所示——當你開啟連結時，LaTeX 文件前言區會自動加入：

![Barchartsexample.png](/files/99d6d87afbf6a4f90f4104cb84140ca40236281d)

#### 程式碼說明

這個圖從（[前面已說明的](#introduction)）的 `tikzpicture` 和 `axis` 環境宣告開始，但 `axis` 宣告中有一些新的參數：

**x tick label style={/pgf/number format/1000 sep=}**

這段程式碼定義了一個完整的圖形樣式。使用這種樣式時，你可以在這個 axis 環境中加入多個 \addplot 命令，它們會自然地配合在一起，而不需要額外調整（下面描述的 ybar 參數是使這一切運作所必需的）。

**enlargelimits=0.05。**

在長條圖中擴大範圍是必要的，因為這類圖通常需要在長條上方留一些額外空間，讓圖看起來更好，和／或加入標籤。數值 0.05 是相對於整個圖的總高度。

**legend style={at={(0.5,-0.2)}, anchor=north,legend columns=-1}**

同樣地，在大多數情況下這都能正常運作。如果需要，將 -0.2 的值改掉，就可以讓圖例更靠近／遠離 x 軸。

**ybar interval=0.7,**

每個長條的粗細。1 表示長條彼此相鄰且沒有間隙；0 表示沒有長條，只有垂直線。

該 `coordinates` 在這類圖中，決定長條的基準點以及其高度。

y 軸上的標籤最多會顯示 4 位數字。如果你使用的數字大於 9999 `pgfplots` 將使用與範例相同的表示法。

## 3D 圖形

`pgfplots` 具有你在繪圖軟體中可能預期的 3D 繪圖功能。

### 繪製數學式

有一個簡單的範例在 [引言](#introduction)，現在讓我們做一些稍微複雜一點的東西：

```latex
\begin{tikzpicture}
\begin{axis}[
    title=使用 mesh 參數的範例,
    hide axis,
    colormap/cool,
]
\addplot3[
    mesh,
    samples=50,
    domain=-8:8,
]
{sin(deg(sqrt(x^2+y^2)))/sqrt(x^2+y^2)};
\addlegendentry{\(\frac{sin(r)}{r}\)}
\end{axis}
\end{tikzpicture}
```

[在 Overleaf 中開啟這個 `pgfplots` Overleaf 中的 3D 範例。](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=pgfplots+3D+example\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%5Bmargin%3D0.5in%5D%7Bgeometry%7D%0A%5Cusepackage%7Bpgfplots%7D%0A%5Cpgfplotsset%7Bwidth%3D10cm%2Ccompat%3D1.9%7D%0A%25%5Cusepgfplotslibrary%7Bexternal%7D%0A%25%5Ctikzexternalize%0A%5Cbegin%7Bdocument%7D%0A%5Cbegin%7Btikzpicture%7D%0A%5Cbegin%7Baxis%7D%5B%0A++++title%3DExample+using+the+mesh+parameter%2C%0A++++hide+axis%2C%0A++++colormap%2Fcool%2C%0A%5D%0A%5Caddplot3%5B%0A++++mesh%2C%0A++++samples%3D50%2C%0A++++domain%3D-8%3A8%2C%0A%5D%0A%7Bsin%28deg%28sqrt%28x%5E2%2By%5E2%29%29%29%2Fsqrt%28x%5E2%2By%5E2%29%7D%3B%0A%5Caddlegendentry%7B%5C%28%5Cfrac%7Bsin%28r%29%7D%7Br%7D%5C%29%7D%0A%5Cend%7Baxis%7D%0A%5Cend%7Btikzpicture%7D%0A%5Cend%7Bdocument%7D)

這段程式碼的輸出如下圖所示——當你開啟連結時，LaTeX 文件前言區會自動加入：

![Pgfplots3dexample.png](/files/7e99ad60fcbc44b4b1f9ac477cdb4428912f3674)

#### 程式碼說明

這裡大多數命令都已經說明過了，但還有 3 個新東西：

**hide axis**

axis 環境中的這個選項名稱就很直觀，座標軸將不會顯示。

**colormap/cool**

是圖中要使用的配色方案。更多配色方案請查看說明指南。

**mesh**

這個選項也很直觀，另請參考前言範例中的 surf 參數。

**注意**：當使用三角函數時 `pgfplots` 預設使用角度作為單位；如果角度是以弧度表示（如本例），你必須使用 `deg` 函數將其轉換為角度。

### 等高線圖

在 `pgfplots` 中可以繪製等高線圖，但資料必須先由外部程式預先計算。讓我們看一個範例：

```latex
\begin{tikzpicture}
\begin{axis}
[
    title={等高線圖，俯視圖},
    view={0}{90}
]
\addplot3[
    contour gnuplot={levels={0.8, 0.4, 0.2, -0.2}}
]
{sin(deg(sqrt(x^2+y^2)))/sqrt(x^2+y^2)};
\end{axis}
\end{tikzpicture}
```

[在 Overleaf 中開啟這個 `pgfplots` Overleaf 中的等高線圖範例。](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=pgfplots+contour+plot+example\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%5Bmargin%3D0.5in%5D%7Bgeometry%7D%0A%5Cusepackage%7Bpgfplots%7D%0A%5Cpgfplotsset%7Bwidth%3D10cm%2Ccompat%3D1.9%7D%0A%25%5Cusepgfplotslibrary%7Bexternal%7D%0A%25%5Ctikzexternalize%0A%5Cbegin%7Bdocument%7D%0A%5Cbegin%7Btikzpicture%7D%0A%5Cbegin%7Baxis%7D%0A%5B%0A++++title%3D%7BContour+plot%2C+view+from+top%7D%2C%0A++++view%3D%7B0%7D%7B90%7D%0A%5D%0A%5Caddplot3%5B%0A++++contour+gnuplot%3D%7Blevels%3D%7B0.8%2C+0.4%2C+0.2%2C+-0.2%7D%7D%0A%5D%0A%7Bsin%28deg%28sqrt%28x%5E2%2By%5E2%29%29%29%2Fsqrt%28x%5E2%2By%5E2%29%7D%3B%0A%5Cend%7Baxis%7D%0A%5Cend%7Btikzpicture%7D%0A%0A%5Cend%7Bdocument%7D)

這段程式碼的輸出如下圖所示——當你開啟連結時，LaTeX 文件前言區會自動加入：

![Contourplotexample.png](/files/85e759fb1a9117723752e49dbf0e67797e125d9d)

#### 程式碼說明

這是一個與前一節使用相同方程式的某些等高線圖。 `title` 參數的值是放在大括號內，因為它包含逗號，所以我們使用分組括號來避免與傳給 `\begin{axis}` 宣告的其他參數混淆。有兩個新命令：

**view={0}{90}**

這會改變圖的視角。此參數是傳給 axis 環境的，這表示它也可用於其他類型的 3D 圖。第一個值是在 z 軸周圍的旋轉角度，單位為度；第二個值是繞 x 軸旋轉視角。在這個範例中，當我們將繞 z 軸 0° 的旋轉與繞 x 軸 90° 的旋轉結合時，得到的是從上方觀看圖形的視角。

**contour gnuplot={levels={0.8, 0.4, 0.2, -0.2}}**

這行程式碼做了兩件事：首先，它告訴 LaTeX 使用外部軟體 gnuplot 來計算等高線；這在 Overleaf 中運作良好，但如果你想在本機 LaTeX 安裝中使用此命令，必須先安裝 gnuplot（matlab 也可以，在這種情況下，請在命令中以 matlab 取代 gnuplot）。其次，子參數 levels 是一個高度層級值的列表，將用來計算等高線。

### 根據資料繪製曲面

若要將一組資料繪製成 3D 曲面，我們只需要每個點的座標。這些座標可以是不排序的集合，或者在此情況下，是一個矩陣：

```latex
\begin{tikzpicture}
\begin{axis}
\addplot3[
    surf,
]
coordinates {
(0,0,0) (0,1,0) (0,2,0)

(1,0,0) (1,1,0.6) (1,2,0.7)

(2,0,0) (2,1,0.7) (2,2,1.8)
};
\end{axis}
\end{tikzpicture}
```

[在 Overleaf 中開啟這個 `pgfplots` Overleaf 中的 3D 曲面範例。](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=plotting+a+surface+from+data+with+pgfplots\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%5Bmargin%3D0.5in%5D%7Bgeometry%7D%0A%5Cusepackage%7Bpgfplots%7D%0A%5Cpgfplotsset%7Bwidth%3D10cm%2Ccompat%3D1.9%7D%0A%25%5Cusepgfplotslibrary%7Bexternal%7D%0A%25%5Ctikzexternalize%0A%5Cbegin%7Bdocument%7D%0A%5Cbegin%7Btikzpicture%7D%0A%5Cbegin%7Baxis%7D%0A%5Caddplot3%5B%0A++++surf%2C%0A%5D+%0Acoordinates+%7B%0A%280%2C0%2C0%29+%280%2C1%2C0%29+%280%2C2%2C0%29%0A%0A%281%2C0%2C0%29+%281%2C1%2C0.6%29+%281%2C2%2C0.7%29%0A%0A%282%2C0%2C0%29+%282%2C1%2C0.7%29+%282%2C2%2C1.8%29%0A%7D%3B%0A%5Cend%7Baxis%7D%0A%5Cend%7Btikzpicture%7D%0A%0A%5Cend%7Bdocument%7D)

這段程式碼的輸出如下圖所示——當你開啟連結時，LaTeX 文件前言區會自動加入：

![3dsurfacedata.png](/files/b730e4e1f5d22103cf76a33a11c954a1c6f97e20)

#### 資料說明

傳入 `coordinates` 參數的點會被視為包含在一個 3 × 3 矩陣中，每一列矩陣之間以空白行作為分隔。

本文中所有適用於 3D 圖的選項也都適用於資料曲面。

### 參數式圖形

參數式圖形的語法稍有不同。讓我們看一個範例：

```latex
\begin{tikzpicture}
\begin{axis}
    [
    view={60}{30},
    ]
\addplot3[
    domain=0:5*pi,
    samples = 60,
    samples y=0,
]
({sin(deg(x))},
{cos(deg(x))},
{x});
\end{axis}
\end{tikzpicture}
```

[在 Overleaf 中開啟這個 `pgfplots` Overleaf 中的參數式圖形範例。](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=pgfplots+parametric+plot+example\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%5Bmargin%3D0.5in%5D%7Bgeometry%7D%0A%5Cusepackage%7Bpgfplots%7D%0A%5Cpgfplotsset%7Bwidth%3D10cm%2Ccompat%3D1.9%7D%0A%25%5Cusepgfplotslibrary%7Bexternal%7D%0A%25%5Ctikzexternalize%0A%5Cbegin%7Bdocument%7D%0A%5Cbegin%7Btikzpicture%7D%0A%5Cbegin%7Baxis%7D%0A++++%5B%0A++++view%3D%7B60%7D%7B30%7D%2C%0A++++%5D%0A%5Caddplot3%5B%0A++++domain%3D0%3A5%2Api%2C%0A++++samples+%3D+60%2C%0A++++samples+y%3D0%2C%0A%5D%0A%28%7Bsin%28deg%28x%29%29%7D%2C%0A%7Bcos%28deg%28x%29%29%7D%2C%0A%7Bx%7D%29%3B%0A%5Cend%7Baxis%7D%0A%5Cend%7Btikzpicture%7D%0A%5Cend%7Bdocument%7D)

這段程式碼的輸出如下圖所示——當你開啟連結時，LaTeX 文件前言區會自動加入：

![Parametricplot.png](/files/ab0eea5250215ff77db9ca027b983601c29a5636)

#### 程式碼說明

這個範例中只有兩個新東西：第一， `samples y=0` 用來防止 `pgfplots` 將螺旋線兩端的極端點連接起來；第二，將要繪製的函數傳入 `addplot3` 環境的方式。每個參數函數都以大括號分組，而三個參數則以括號分隔。

## 參考指南

| 命令／選項／環境         | 說明                                     | 可能的值                                                                                                                                                                                                                                                                                                |
| ---------------- | -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **axis**         | 具有線性縮放的普通圖形                            |                                                                                                                                                                                                                                                                                                     |
| **semilogxaxis** | x 為對數縮放，y 為普通縮放                        |                                                                                                                                                                                                                                                                                                     |
| **semilogyaxis** | y 為對數縮放，x 為普通縮放                        |                                                                                                                                                                                                                                                                                                     |
| **loglogaxis**   | x 與 y 座標軸皆為對數縮放                        |                                                                                                                                                                                                                                                                                                     |
| **axis lines**   | 改變座標軸的繪製方式。預設為 '*方框*                   | box, left, middle, center, right, none                                                                                                                                                                                                                                                              |
| **legend pos**   | 圖例框的位置                                 | south west, south east, north west, north east, outer north east                                                                                                                                                                                                                                    |
| **mark**         | 資料繪圖中使用的標記類型。當使用單一字元時，該字元的外觀與實際標記非常相似。 | \*, x , +, \|, o, asterisk, star, 10-pointed star, oplus, oplus\*, otimes, otimes\*, square, square\*, triangle, triangle\*, diamond, halfdiamond\*, halfsquare\*, right\*, left\*, Mercedes star, Mercedes star flipped, halfcircle, halfcircle\*, pentagon, pentagon\*, cubes. （cubes 只適用於 3D 圖。） |
| **colormap**     | 圖中要使用的配色方案，可以自訂，但也有一些預先定義的色圖           | hot, hot2, jet, blackwhite, bluered, cool, greenyellow, redyellow, violet.                                                                                                                                                                                                                          |

## 延伸閱讀

詳情請見：

* [在 LaTeX 中使用顏色](/latex/zh-tw/ge-shi-hua/13-using-colors-in-latex.md)
* [TikZ 套件](/latex/zh-tw/tu-biao-yu-biao-ge/05-tikz-package.md)
* [pgfplots 與 tikzpictures 的外部化](/latex/zh-tw/wen-yu-da/60-i-have-a-lot-of-tikz-matlab2tikz-or-pgfplots-figures-so-i-m-getting-a-compilation-timeout.-can-i.md)
* [插入圖片](/latex/zh-tw/geng-duo-zhu-ti/27-inserting-images.md)
* [表格與圖形清單](/latex/zh-tw/tu-biao-yu-biao-ge/03-lists-of-tables-and-figures.md)
* [圖片與表格的定位](/latex/zh-tw/tu-biao-yu-biao-ge/02-positioning-images-and-tables.md)
* [直接在 LaTeX 中繪製圖表](/latex/zh-tw/tu-biao-yu-biao-ge/04-picture-environment.md)
* [該 **pgfplots** 套件說明文件](http://mirrors.ctan.org/graphics/pgf/contrib/pgfplots/doc/pgfplots.pdf).
* [TikZ 與 PGF 套件：3.0.0 版手冊](http://mirror.utexas.edu/ctan/graphics/pgf/base/doc/pgfmanual.pdf)
* [TeXample.net 上的 TikZ 與 PGF 範例](http://www.texample.net/tikz/examples/all/)


---

# 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-tw/te-ding-ling-yu/08-pgfplots-package.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.
