tikz.dev / PGFplots Manual

Manual for Package pgfplots
2D/3D Plots in LA, Version 1.18.1
http://sourceforge.net/projects/pgfplots

The Reference

\(\newcommand{\footnotename}{footnote}\) \(\def \LWRfootnote {1}\) \(\newcommand {\footnote }[2][\LWRfootnote ]{{}^{\mathrm {#1}}}\) \(\newcommand {\footnotemark }[1][\LWRfootnote ]{{}^{\mathrm {#1}}}\) \(\let \LWRorighspace \hspace \) \(\renewcommand {\hspace }{\ifstar \LWRorighspace \LWRorighspace }\) \(\newcommand {\mathnormal }[1]{{#1}}\) \(\newcommand \ensuremath [1]{#1}\) \(\newcommand {\LWRframebox }[2][]{\fbox {#2}} \newcommand {\framebox }[1][]{\LWRframebox } \) \(\newcommand {\setlength }[2]{}\) \(\newcommand {\addtolength }[2]{}\) \(\newcommand {\setcounter }[2]{}\) \(\newcommand {\addtocounter }[2]{}\) \(\newcommand {\arabic }[1]{}\) \(\newcommand {\number }[1]{}\) \(\newcommand {\noalign }[1]{\text {#1}\notag \\}\) \(\newcommand {\cline }[1]{}\) \(\newcommand {\directlua }[1]{\text {(directlua)}}\) \(\newcommand {\luatexdirectlua }[1]{\text {(directlua)}}\) \(\newcommand {\protect }{}\) \(\def \LWRabsorbnumber #1 {}\) \(\def \LWRabsorbquotenumber "#1 {}\) \(\newcommand {\LWRabsorboption }[1][]{}\) \(\newcommand {\LWRabsorbtwooptions }[1][]{\LWRabsorboption }\) \(\def \mathchar {\ifnextchar "\LWRabsorbquotenumber \LWRabsorbnumber }\) \(\def \mathcode #1={\mathchar }\) \(\let \delcode \mathcode \) \(\let \delimiter \mathchar \) \(\def \oe {\unicode {x0153}}\) \(\def \OE {\unicode {x0152}}\) \(\def \ae {\unicode {x00E6}}\) \(\def \AE {\unicode {x00C6}}\) \(\def \aa {\unicode {x00E5}}\) \(\def \AA {\unicode {x00C5}}\) \(\def \o {\unicode {x00F8}}\) \(\def \O {\unicode {x00D8}}\) \(\def \l {\unicode {x0142}}\) \(\def \L {\unicode {x0141}}\) \(\def \ss {\unicode {x00DF}}\) \(\def \SS {\unicode {x1E9E}}\) \(\def \dag {\unicode {x2020}}\) \(\def \ddag {\unicode {x2021}}\) \(\def \P {\unicode {x00B6}}\) \(\def \copyright {\unicode {x00A9}}\) \(\def \pounds {\unicode {x00A3}}\) \(\let \LWRref \ref \) \(\renewcommand {\ref }{\ifstar \LWRref \LWRref }\) \( \newcommand {\multicolumn }[3]{#3}\) \(\require {textcomp}\) \( \newcommand {\meta }[1]{\langle \textit {#1}\rangle } \) \(\newcommand {\toprule }[1][]{\hline }\) \(\let \midrule \toprule \) \(\let \bottomrule \toprule \) \(\def \LWRbooktabscmidruleparen (#1)#2{}\) \(\newcommand {\LWRbooktabscmidrulenoparen }[1]{}\) \(\newcommand {\cmidrule }[1][]{\ifnextchar (\LWRbooktabscmidruleparen \LWRbooktabscmidrulenoparen }\) \(\newcommand {\morecmidrules }{}\) \(\newcommand {\specialrule }[3]{\hline }\) \(\newcommand {\addlinespace }[1][]{}\) \(\require {colortbl}\) \(\let \LWRorigcolumncolor \columncolor \) \(\renewcommand {\columncolor }[2][named]{\LWRorigcolumncolor [#1]{#2}\LWRabsorbtwooptions }\) \(\let \LWRorigrowcolor \rowcolor \) \(\renewcommand {\rowcolor }[2][named]{\LWRorigrowcolor [#1]{#2}\LWRabsorbtwooptions }\) \(\let \LWRorigcellcolor \cellcolor \) \(\renewcommand {\cellcolor }[2][named]{\LWRorigcellcolor [#1]{#2}\LWRabsorbtwooptions }\) \(\newcommand {\intertext }[1]{\text {#1}\notag \\}\) \(\let \Hat \hat \) \(\let \Check \check \) \(\let \Tilde \tilde \) \(\let \Acute \acute \) \(\let \Grave \grave \) \(\let \Dot \dot \) \(\let \Ddot \ddot \) \(\let \Breve \breve \) \(\let \Bar \bar \) \(\let \Vec \vec \) \(\newcommand {\nicefrac }[3][]{\mathinner {{}^{#2}\!/\!_{#3}}}\)

4.9Axis Descriptions

Axis descriptions are labels for \(x\)- and \(y\)-axis, titles, legends and the like. Axis descriptions are drawn after the plot is finished and they are not subjected to clipping.

4.9.1Placement of Axis Descriptions

This section describes how to modify the placement of titles, labels, legends and other axis descriptions. It may be skipped at first reading.

There are different methods to place axis descriptions. One of them is to provide coordinates relative to the axis’ rectangle such that (0,0) is the lower left corner and (1,1) is the upper right corner – this is very useful for figure titles or legends. Coordinates of this type, i.e. without unit like (0,0) or (1.03,1), are called axis description cs (the cs stands for “coordinate system”). One other method is of primary interest for axis labels – they should be placed near the tick labels, but it a way that they don’t overlap or obscure tick labels. Furthermore, axis labels shall be placed such that they are automatically moved if the axis is rotated (or tick labels are moved to the right side of the figure). There is a special coordinate system to realize these two demands, the ticklabel cs.

In the following, the two coordinate systems axis description cs and ticklabel cs are described in more detail. It should be noted that axis description cs is used automatically, so it might never be necessary to use it explicitly.

Remarks:

Besides the mentioned positioning methods, there is also the predefined node current axis. The anchors of current axis can also be used to place descriptions: At the time when axis descriptions are drawn, all anchors which refer to the axis origin (that means the “real” point \((0,0)\)) or any of the axis corners can be referenced using current axis.(math image)anchor name(math image). Please see Section 4.19, Alignment, for further details.

44 This was different in versions before 1.3: earlier versions did not have the distinction between axis description cs and rel axis cs.

45 Actually, the outer normal has the impression of being “orthogonal” to its axis, which appears to be sufficient.

4.9.2Alignment of Axis Descriptions

This section describes how to modify the default alignment of axis descriptions. It can be skipped at first reading.

The two topics positioning and alignment always work together: positioning means to select an appropriate coordinate and alignment means to select an anchor inside of the description which will actually be moved to the desired position.

TikZ uses many anchors to provide alignment; most of them are named like north, north east etc. These names hold for any axis description as well (as axis descriptions are TikZ nodes). Readers can learn details about this topic in the PGF/TikZ manual or some more advice in Section 4.19.

When it comes to axis descriptions, pgfplots offers some specialized anchors and alignment methods which are described below.

  • Anchor near xticklabel

  • Anchor near yticklabel

  • Anchor near zticklabel

  • Anchor near ticklabel

  • These anchors can be used to align at the part of a node (for example, an axis description) which is nearest to the tick labels of a particular axis (or nearest to the position where tick labels would have been drawn if there were any).

    These anchors are used for axis labels, especially for three dimensional axes. Furthermore, they are used for every tick label.

    Maybe it is best to demonstrate it by example:

    (-tikz- diagram) (-tikz- diagram)

    % Preamble: \pgfplotsset{width=7cm,compat=1.18} \begin{tikzpicture} \begin{axis}[ title=Without \texttt{near ticklabel}, ylabel={$f(x)=x$}, every axis y label/.style={ at={(ticklabel cs:0.5)},rotate=90,anchor=center, }, clip=false, % to display the \path below ylabel style={draw=red}, yticklabel style={draw=red}, ] \addplot {x}; % visualize the position: \fill (yticklabel cs:0.5) circle(2pt); \end{axis} \end{tikzpicture} \begin{tikzpicture} \begin{axis}[ title=With \texttt{near ticklabel}, ylabel={$f(x)=x$}, every axis y label/.style={ at={(ticklabel cs:0.5)},rotate=90,anchor=near ticklabel, }, clip=false, ylabel style={draw=red}, yticklabel style={draw=red}, ] \addplot {x}; \fill (yticklabel cs:0.5) circle(2pt); \end{axis} \end{tikzpicture}

    The motivation is to place nodes such that they are anchored next to the tick label, regardless of the node’s rotation or the position of ticks. The special anchor near ticklabel is only available for axis labels (as they have a uniquely identified axis, either \(x\), \(y\) or \(z\)).

    In more detail, the anchor is placed such that first, the node’s center is on a line starting in the node’s at position going in direction of the inwards normal vector of the axis line which contains the tick labels and second, the node does not intrude the axis (but see also the key near ticklabel align and the details in the lengthy elaboration in the documentation for near xticklabel opposite below). This normal vector is the same which is used for the shift argument in ticklabel cs: it is orthogonal to the tick label axis. Furthermore, near ticklabel inverts the transformation matrix before it computes this intersection point.

    The near ticklabel anchor and its friends will be added temporarily to any shape used inside of an axis. This includes axis descriptions, but it is not limited to them: it applies to every TikZ \node[anchor=near xticklabel] ... setting.

    Note that it is not necessary at all to have tick labels in an axis. The anchor will be placed such that it is near the axis on which tick labels would be drawn. In fact, every tick label uses anchor=near ticklabel as initial configuration.

  • Anchor near xticklabel opposite

  • Anchor near yticklabel opposite

  • Anchor near zticklabel opposite

  • Anchor near ticklabel opposite

  • These anchors are similar to near xticklabel and its variants, except that they align at the opposite direction.

    Mathematically speaking, the only difference to near xticklabel and its variants is the sign in front of the normal vector.

    But it is probably best explained by means of an example.

    (-tikz- diagram)

    % Preamble: \pgfplotsset{width=7cm,compat=1.18} \begin{tikzpicture} \begin{axis}[ clip=false, small, title=\texttt{near ticklabel} (\texttt{opposite}), min=0, max=1, ] \node [draw=yellow,anchor=near xticklabel,font=\small] (namex) at (xticklabel cs:0.2) {\texttt{near xticklabel}.}; \fill (xticklabel cs:0.2) circle(2pt); \draw [green,-stealth] (xticklabel* cs:0.2) -- (xticklabel cs:0.2); \draw [blue,-stealth] (xticklabel cs:0.2) -- (namex.center); \draw [red,-stealth] (namex.north east) -- (xticklabel cs:0.2); \node [draw=yellow,anchor=near xticklabel opposite,font=\small] (namexx) at (xticklabel* cs:0.6) {\texttt{near xticklabel opposite}.}; \fill [red] (xticklabel* cs:0.6) circle(2pt); \draw [blue,-stealth] (xticklabel* cs:0.6) -- (namexx.center); \draw [red,thick,-stealth] (namexx.south west) -- (xticklabel* cs:0.6); \node [draw=yellow,anchor=near yticklabel,font=\small] (name) at (yticklabel cs:1) {\texttt{near yticklabel}.}; \fill (yticklabel cs:1) circle(2pt); \draw [green,-stealth] (yticklabel* cs:1) -- (yticklabel cs:1); \draw [blue,-stealth] (yticklabel cs:1) -- (name.center); \draw [red,-stealth] (name.north west) -- (yticklabel cs:1); \end{axis} \end{tikzpicture}

    The figure is a boxed three-dimensional axis with standard ranges. It has three manually placed nodes. The nodes are placed at (xticklabel cs:0.2), at (xticklabel* cs:0.6), and at (yticklabel cs:1), respectively. The ‘at’ locations are visually emphasized using filled circles.

    Despite the different locations, we clearly see the effect of near xticklabel opposite: it causes the node to be aligned into the box rather than outside of the box. Note that this is the only essential difference between the two nodes ‘near xticklabel opposite’ and ‘near xticklabel’.

    The figure also shows the difference between xticklabel cs and xticklabel* cs when we compare the ‘at’ locations. Take, for example, the two nodes on the \(x\)-axis. The position at (xticklabel cs:0.2) is shifted by the green arrow. The length of this arrow is precisely the length of the largest \(x\) tick label. The position at (xticklabel* cs:0.6) is exactly on the axis; it ignores the size of any tick labels. Note that the direction of the green arrow is the “outer normal vector in \(x\) direction” (in our case, it is the vector sum of the \(z\) and \(y\) unit vectors with appropriate signs).

    The difference between near xticklabel opposite and near xticklabel is that the direction of the green arrow (the “outer normal”) is flipped.

    The nodes also highlight how the anchoring works. This technique is almost the same for both anchor=near xticklabel and anchor=near xticklabel opposite. Let us discuss the technique for the node with text ‘near yticklabel’. The black circle is placed at (yticklabel cs:1). This position has been computed by starting at \(100\%\) of the \(y\)-axis46 and moving along the green vector whose magnitude is the size of the bounding box of the largest \(y\) tick label. As soon as the ‘at’ location is fixed, the algorithm for near yticklabel starts. First, it computes the anchor inside of the node for which we do not penetrate the \(y\)-axis. To this end, it checks the direction of the green vector. It came up with north west. Then, it considers the red line which starts at (name.north west) and has the same direction as the \(y\)-axis. Note that the red line and the \(y\)-axis are parallel. It also considers the blue line. This line points into the direction of the green line and is fixed by the current node’s center. The precise intersection point of the red line and the blue line are the result of anchor=near yticklabel. The same applies for the other two nodes as well: the red line is always parallel to the axis under consideration and is anchored at the “snap to nearest anchor” of the node. The blue line is always parallel to the outer normal vector of the axis under consideration, and is anchored at the current node’s center.

  • /pgfplots/near ticklabel align=inside|center|outside (initially center)

  • Allows to change the alignment algorithm of anchor=near ticklabel.

    In the default configuration, anchor=near ticklabel and its variants take the node’s center in order to derive the final anchor. This corresponds to the target of the blue line in the illustration for near xticklabel opposite, see above.

    This key changes the node’s anchor which is used here. The choice center can move half of the node’s bounding box beyond the associated axis. The choice inside moves the complete node’s bounding box in a way such that it is not beyond the associated axis. The choice outside moves the entire node’s bounding box in a way that it is beyond the associated axis:

    (-tikz- diagram)

    % Preamble: \pgfplotsset{width=7cm,compat=1.18} \begin{tikzpicture} \begin{axis}[ clip=false, small, title=\texttt{near ticklabel align}, min=0, max=1, /tikz/node style/.style={ draw=yellow, anchor=near yticklabel, font=\tiny, }, ] \node [node style,/pgfplots/near ticklabel align=center] (C) at (yticklabel cs:0) {\texttt{center}.}; \node [node style,/pgfplots/near ticklabel align=inside] (I) at (yticklabel cs:1) {\texttt{inside}.}; \node [node style,/pgfplots/near ticklabel align=outside] (O) at (yticklabel cs:1) {\texttt{outside}.}; \fill (yticklabel cs:0) circle(2pt); \fill (yticklabel cs:1) circle(2pt); \fill [blue] (C.center) circle(1pt); \fill [blue] (I.south west) circle(1pt); \fill [blue] (O.north east) circle(1pt); \draw [green,-stealth] (yticklabel* cs:0) -- (yticklabel cs:0); \draw [blue] (yticklabel cs:0) -- (C.center); \draw [red,-stealth] (C.north west) -- (yticklabel cs:0); \draw [green,-stealth] (yticklabel* cs:1) -- (yticklabel cs:1); \draw [blue] (yticklabel cs:1) -- (O.north east); \draw [red,-stealth] (O.north west) -- (yticklabel cs:1); \draw [red,-stealth] (I.north west) -- (yticklabel cs:1); \end{axis} \end{tikzpicture}

    The example is similar to the one above: it generates an empty axis with a default range. Then, it creates three nodes: one for choice center, one for choice inside, and one for choice outside. The node for center is placed at (yticklabel cs:0) (lower black circle). We see that its bounding box extends the size of the \(y\)-axis. This is because its anchor C.center is used for the alignment. Both the node for inside and the node for outside are placed at (yticklabel cs:1) (upper black circle). Their only difference is the choice for near ticklabel align. The node for inside does not extend the size of the \(y\)-axis; it is placed within its boundaries – because its internal anchor (I.north east) (blue) has automatically been used in order to align the node. The node for outside is completely outside of the extends for the \(y\)-axis because its (blue) anchor (O.south west) has been chosen.

    Note that the red lines are always the same. They are the “snap to nearest” anchor such that the node is outside of the axis. Only the location of the blue anchors is affected by this key.

    Note that near ticklabel align always results in the same alignment, independent of the actual position of the node. This is because an anchor is independent of the at location of a node. In this context, the names “inside” and “outside” might be a bad choice: they stress the intended meaning if the node is chosen at the upper end of the axis. However, if you say at (yticklabel cs:0), near ticklabel align=inside, it will actually end up outside of the axis. This is because the “inside” anchor has been computed without considering where the node is.

  • /pgfplots/near ticklabel at={(math image)coordinate(math image)} (initially empty)

  • Occasionally, anchor=near ticklabel results in a different anchor depending on where the node is placed. This can happen for a polaraxis.

    If this key is needed, pgfplots will spit out the warning “The anchor ‘near ticklabel’ cannot be computed correctly because the position is missing. Please add ‘near ticklabel at=coordinate’ with a suitable coordinate”.

    pgfplots uses context information to determine the correct information, so this may be unnecessary. If you encounter this warning, you should add near ticklabel at=(math image)value(math image) with a suitable value.

  • /tikz/sloped like x axis(no value)

  • /tikz/sloped like y axis(no value)

  • /tikz/sloped like z axis(no value)

  • /tikz/sloped like x axis={(math image)options(math image)}

  • /tikz/sloped like y axis={(math image)options(math image)}

  • /tikz/sloped like z axis={(math image)options(math image)}

  • A key which replaces the rotational/scaling parts of the transformation matrix such that the node is sloped like the provided axis. For two dimensional plots, sloped like y axis is effectively the same as rotate=90. For a three dimensional axis, this will lead to a larger difference:

    (-tikz- diagram)

    % Preamble: \pgfplotsset{width=7cm,compat=1.18} \begin{tikzpicture} \begin{axis}[ xlabel=Variable 1, ylabel=Variable 2, zlabel=value, xlabel style={sloped like x axis}, ylabel style={sloped}, ] \addplot3 [surf] {y*x*(1-x)}; \end{axis} \end{tikzpicture}

    Inside of axis labels, sloped is an alias for sloped like (math image)char(math image) axis with the correct (math image)char(math image) chosen automatically.

    Please note that rotated text might not look very good (neither on screen nor printed).

    It is possible to customize sloped like x axis by means of the following keys, which need to be provided as (math image)options(math image) (simply ignore the lengthy gray key prefixes):

    • /pgfplots/sloped/allow upside down=true|false (initially false)

    • Use sloped like x axis=allow upside down to enable upside down labels.

    • /pgfplots/sloped/execute for upside down=code (initially empty)

    • Use sloped like x axis={execute for upside down=\tikzset{anchor=north}} or something like that to handle upside down text nodes in a customized way (this is used by the smithchart library).

    • /pgfplots/sloped/reset nontranslations=true|false (initially true)

    • Use sloped like x axis={reset nontranslations=false} to append the transformations to the actual transformation matrix (instead of replacing it).

    • /pgfplots/sloped/at position={(math image)position(math image)} (initially empty)

    • This key can either be empty or a position. It is merely of interest for axes in which the transformation depends on the axis position as for polaraxis.

46 In our example, percentages and absolute values are accidentally the same.

4.9.3Labels
  • /pgfplots/xlabel={(math image)text(math image)}

  • /pgfplots/ylabel={(math image)text(math image)}

  • /pgfplots/zlabel={(math image)text(math image)}

  • These options set axis labels to (math image)text(math image) which is any text.

    To include special characters, you can use curly braces: “xlabel={, = characters}”. This is necessary if characters like ‘=’ or ‘,’ need to be included literally.

    Use xlabel/.add={(math image)prefix(math image)}{(math image)suffix(math image)} to modify an already assigned label.

    Labels are TikZ nodes which are placed with

    % for x: \node [ style=every axis label, style=every axis x label, ] % for y: \node [ style=every axis label, style=every axis y label, ]

    so their position and appearance can be customized.

    For example, a multiline xlabel can be configured using

    \begin{axis}[xlabel style={align=right,text width=3cm},xlabel=A quite long label with a line break] ... \end{axis}

    See the PGF/TikZ manual to learn more about align and text width.

Upgrade notice:

Since version 1.3, label placement can respect the size of adjacent tick labels. Use \pgfplotsset{compat=1.3} (or newer) in the preamble to activate this feature. See xlabel near ticks for details.

  • /pgfplots/xlabel shift={(math image)dimension(math image)} (initially 0pt)

  • /pgfplots/ylabel shift={(math image)dimension(math image)} (initially 0pt)

  • /pgfplots/zlabel shift={(math image)dimension(math image)} (initially 0pt)

  • /pgfplots/label shift={(math image)dimension(math image)}

  • Shifts labels in direction of the outer normal vector of the axis by an amount of (math image)dimension(math image). The label shift sets all three label shifts to the same value.

Attention:

This does only work if \pgfplotsset{compat=1.3} (or newer) has been called (more precisely: if xlabel near ticks is active for the respective axis).

  • /pgfplots/xlabel near ticks(no value)

  • /pgfplots/ylabel near ticks(no value)

  • /pgfplots/zlabel near ticks(no value)

  • /pgfplots/compat=1.3

  • These keys place axis labels (like xlabel) near the tick labels. If tick labels are small, labels will move closer to the axis. If tick labels are large, axis labels will move away from the axis. This is the default for every three dimensional plot, but it won’t be used initially for two-dimensional plots for backwards compatibility. Take a look at the definition of near ticklabel for an example.

    The definition of these styles is

    It is encouraged to write

    \pgfplotsset{compat=1.3} % or newer

    in your preamble to install the styles document-wide – it leads to the best output (it avoids unnecessary space). It is not activated initially for backwards compatibility with older versions which used fixed distances from the tick labels.

Whenever possible, consider using /.append style instead of overwriting the default styles to ensure compatibility with future versions.

4.9.4Legends

Legends can be generated in two ways: the first is to use \addlegendentry or \legend inside of an axis. The other method is to use the key legend entries.

  • \addlegendentryexpanded[(math image)options(math image)]{(math image) text(math image)}

  • A variant of \addlegendentry which provides a method to deal with macros inside of (math image) text(math image).

    Suppose (math image) text(math image) contains some sort of parameter which varies for every plot. Moreover, you like to use a loop to generate the plots. Then, it is simpler to use \addlegendentryexpanded:

    (-tikz- diagram)

    % Preamble: \pgfplotsset{width=7cm,compat=1.18} \begin{tikzpicture} \begin{axis} \foreach \p in {1,2,3} { \addplot {x^\p}; \addlegendentryexpanded{$x^\p$} } \end{axis} \end{tikzpicture}

    Note that this example wouldn’t have worked with \addlegendentry{$x^\p$} because the macro \p is no longer defined when pgfplots attempts to draw the legend.

    The invocation \addlegendentryexpanded{$x^\p$} is equivalent to calling \addlegendentry{$x^2$} if \p expands to 2.

    The argument (math image) text(math image) is expanded until nothing but un-expandable material remains (i.e. it uses the primitive \edef). Occasionally, (math image) text(math image) contains parts which should be expanded (like \p) and other parts which should be left unexpanded (for example \pgfmathprintnumber{\p}). Then, use

    \noexpand\pgfmathprintnumber{\p}

    or, equivalently

    \protect\pgfmathprintnumber{\p}

    to avoid expansion of the macro which follows the \protect immediately.

  • \legend{(math image)list(math image)}

  • You can use \legend{(math image)list(math image)} to assign a complete legend.

    \legend{$d=2$,$d=3$,$d=4$,$d=5$,$d=6$}

    The argument of \legend is a list of entries, one for each plot.

    Two different delimiters are supported:

    • 1. There are comma-separated lists like

      \legend{$d=2$,$d=3$,$d=4$,$d=5$,$d=6$}

      These lists are processed using the pgf \foreach command and are quite powerful.

      The \foreach command supports a dots notation to denote ranges like \legend{1,2,...,5} or even \legend{$x^1$,$x^...$,$x^d$}.

Attention with periods:

to avoid confusion with the dots ... notation, you may need to encapsulate a legend entry containing periods by curly braces: \legend{{ML spcm.},{CW spcm.},{ML AC}} (or use the \\ delimiter, see below).

  • 2. It is also possible to delimit the list by ‘\\’. In this case, the last element must be terminated by \\ as well:

    \legend{$a=1, b=2$\\,$a=2, b=3$\\$a=3, b=5$\\}

    This syntax simplifies the use of ‘,’ inside of legend entries, but it does not support the dots notation.

  • The short marker/line combination shown in legends is acquired from the (math image)style options(math image) argument of \addplot.

    Using \legend overwrites any other existing legend entries.

    4.9.5Legend Appearance
    • /pgfplots/legend columns={(math image)number(math image)} (default 1)

    • Allows to configure the maximum number of adjacent legend entries. The default value 1 places legend entries vertically below each other.

      Use legend columns=-1 to draw all entries horizontally.

    • /pgfplots/legend plot pos=left|right|none (initially left)

    • Configures where the small line specifications will be drawn: left of the description, right of the description or not at all.

    • /pgfplots/legend image code/.code={(math image)...(math image)}

    • Allows to replace the default images which are drawn inside of legends. When this key is evaluated, the current plot specification has already been activated (using \begin{scope}[current plot style])47, so any drawing operations use the same styles as the \addplot command.

      The default is the style line legend.

    Technical note:

    At the time when legend images are drawn, the style every axis legend is in effect – which have unwanted side-effects due to changed parameters (especially those concerning node placement, alignment, and shifting). It might be necessary to reset these parameters manually (pgfplots also attempts to reset the fill color).

    • /pgfplots/empty legend(style, no value)

    • A style which clears legend image code, thereby omitting the legend image.

    47 This was different in versions before 1.3. The new scope features allow plot styles to change legend image code.

    4.9.6Legends with \label and \ref

    pgfplots offers a \label and \ref feature for to assemble a legend manually, for example as part of the figure caption. These references work as usual references: a \label remembers where and what needs to be referenced and a \ref expands to proper text. In context of plots, a \label remembers the plot specification of one plot and a \ref expands to the small image which would also be used inside of legends.

    (-tikz- diagram)

    % Preamble: \pgfplotsset{width=7cm,compat=1.18} \begin{tikzpicture}[baseline] \begin{axis} \addplot+ [ only marks, samples=15, error bars/y dir=both, error bars/y fixed=2.5, ] {3*x+2.5*rand}; \label{pgfplots:label1} \addplot+ [mark=none] {3*x}; \label{pgfplots:label2} \addplot {4*cos(deg(x))}; \label{pgfplots:label3} \end{axis} \end{tikzpicture}
    The picture shows the estimations \ref{pgfplots:label1} which are subjected to noise. It appears the model \ref{pgfplots:label2} fits the data appropriately. Finally, \ref{pgfplots:label3} is only here to get three examples.

    The picture shows the estimations (-tikz- diagram) which are subjected to noise. It appears the model (-tikz- diagram) fits the data appropriately. Finally, (-tikz- diagram) is only here to get three examples.

    • \label{(math image)label name(math image)}

    • \label[(math image)reference(math image)]{(math image)label name(math image)}

    • When used after \addplot, this command creates a label named (math image)label name(math image).48 If this label is cross-referenced with \ref{(math image)label name(math image)} somewhere, the associated plot specification will be inserted.

      Label3 = (-tikz- diagram); Label2 = (-tikz- diagram)

      Label3 = \ref{pgfplots:label3}; Label2 = \ref{pgfplots:label2}

      The label is assembled using legend image code and the plot style of the last plot. Any pgfplots option is expanded until only TikZ (or pgf) options remain; these options are used to get an independent label.

      More precisely, the small image generated by \ref{(math image)label name(math image)} is

      where the contents is determined by legend image code and the plot style.

      The second syntax, \label[(math image)reference(math image)]{(math image)label name(math image)} allows to label particular pieces of an \addplot command. It is (currently) only interesting for scatter/classes: there, it allows to reference particular classes of the scatter plot. See page (page for section 4.5.12) for more details.

      Note that \label information, even the small TikZ pictures here, can be combined with the external library for image externalization, see Section 8.1 for details (in particular, the external/mode key). In other words, references remain valid even if the defining axis has been externalized.

    • \ref{(math image)label name(math image)}

    • Can be used to reference a labeled, single plot. See the example above.

      This will also work together with hyperref links and \pageref.49

    • /pgfplots/refstyle={(math image)label name(math image)}

    • Can be used to set the styles of a labeled, single plot. This allows to write

      \addplot[/pgfplots/refstyle={pgfplots:label2}]

      somewhere. Please note that it may be easier to define a style with .style.

    • /pgfplots/invoke before crossref tikzpicture={(math image) code(math image)}

    • /pgfplots/invoke after crossref tikzpicture={(math image) code(math image)}

    • Code which is invoked just before or just after every cross reference picture. This applies to legend images generated with \ref, legend to name and colorbar to name images.

      The initial configuration checks if the external library is in effect. If so, it modifies the generated figure names by means of \tikzappendtofigurename{_crossref}.

    48 This feature is only available in , sorry.

    49 Older versions of pgfplots required the use of \protect\ref when used inside of captions or section headings. This is no longer necessary.

    4.9.7Legends Outside Of an Axis

    Occasionally, one has multiple adjacent plots, each with the same legend – and just one legend suffices. But where shall it be placed? And how? One solution is to use the overlay key to exclude the legend from bounding box computations, and place it absolutely such that it fits. Another is the legend to name feature:

    • /pgfplots/legend to name={(math image)name(math image)} (initially empty)

    • Enables a legend export mode: instead of drawing the legend, a self-contained, independent set of drawing commands will be stored using the label (math image)name(math image). The definition is done using \label{(math image)name(math image)}, just like any other label. The name can be referenced using

      \ref{(math image)name(math image)}.

      Thus, typing \ref{(math image)name(math image)} somewhere outside of the axis, maybe even outside of any picture, will cause the legend to be drawn.

      (-tikz- diagram) (-tikz- diagram) (-tikz- diagram)

      (-tikz- diagram)

      % Preamble: \pgfplotsset{width=7cm,compat=1.18} \pgfplotsset{footnotesize,samples=10} \begin{center}% note that \centering uses less vspace... \begin{tikzpicture} \begin{axis}[ legend columns=-1, legend entries={$(x+0)^k$;,$(x+1)^k$;,$(x+2)^k$;,$(x+3)^k$}, legend to name=named, title={$k=1$}, ] \addplot {x}; \addplot {x+1}; \addplot {x+2}; \addplot {x+3}; \end{axis} \end{tikzpicture} % \begin{tikzpicture} \begin{axis}[title={$k=2$}] \addplot {x^2}; \addplot {(x+1)^2}; \addplot {(x+2)^2}; \addplot {(x+3)^2}; \end{axis} \end{tikzpicture} % \begin{tikzpicture} \begin{axis}[title={$k=3$}] \addplot {x^3}; \addplot {(x+1)^3}; \addplot {(x+2)^3}; \addplot {(x+3)^3}; \end{axis} \end{tikzpicture} \\ \ref{named} \end{center}

      Note that only the first plot has legend entries. Thus, its legend will be created as usual, and stored under the name ‘named’, but it won’t be drawn. The stored legend can then be drawn with \ref{named} below the three plots. Since there is no picture in this context, a \tikz picture is created and a \matrix[/pgfplots/every axis legend] path is drawn inside of it, resulting in the legend as if it had been placed inside of the axis.

      The stored legend will contain the currently active values of legend and plot style related options. This includes legend image code, every axis legend, and any plot style options (and some more). The algorithm works in the same way as for \label and \ref, i.e. it keeps any options with /tikz/ prefix and expands those with /pgfplots/ prefix.

      Note that the legend is drawn with every axis legend, even though the placement options might be chosen to fit into an axis. You may want to adjust the style in the same axis in which the stored legend has been defined (the value will be copied and restored as well).

    About \ref{(math image)name(math image)}

    The \ref{(math image)name(math image)} command retrieves a stored legend (one defined by legend to name) and draws it.

    \ref{named}: (-tikz- diagram)

    If you want the legend to be exported and drawn inside of the current axis, consider using extra description/.append code={\ref{(math image)name(math image)}}.

    Note that \ref can be combined with the external library for image externalization. In other words, the legend will work even if the defining axis has been externalized, see Section 8.1 for details (in particular the external/mode key).

    Note furthermore that this .aux file related stuff is (currently) only supported, if pgfplots is run by means of , sorry.

    • \pgfplotslegendfromname{(math image)name(math image)}

    • This command poses an equivalent alternative for \ref{(math image)name(math image)}: it has essentially the same effect, but it does not create links when used with the hyperref package.50

    • /pgfplots/every legend to name picture(style, no value)

    • A style which is installed when \ref is used outside of a picture: a new picture will be created with \tikz[/pgfplots/every legend to name picture].

      Thus, you can redefine this style to set alignment options (such as baseline). For example, the initialization

      \pgfplotsset{ legend style={matrix anchor=west,at={(0pt,0pt)}}, every legend to name picture/.style={baseline}, } ...

      will cause the legend to be positioned such that its west anchor is at y=0pt. The baseline option will align this point of the legend with the text baseline (please refer to the documentation for baseline in Section 4.19 for details).

    50 Since this manual uses colored links, the text in \ref would usually be blue. Using \pgfplotslegendfromname avoids link text colors in the legend (this has been applied to the manual styles here).

    4.9.8Legends with Customized Texts or Multiple Lines

    Occasionally, one may want multiple lines for legend entries. That is possible as well using a fixed text width:

    (-tikz- diagram)

    % Preamble: \pgfplotsset{width=7cm,compat=1.18} \begin{tikzpicture} \begin{semilogyaxis}[ domain=0:4, ] \addplot {x}; \addlegendentry{$x$} \addplot {x^2}; \addlegendentry{$x^2$} \addplot {x^3}; \addlegendentry{$x^3$} \addlegendimage{empty legend} \addlegendentry [text width=25pt,text depth=] {Neg. Sign:} \addplot {x^(-1)}; \addlegendentry{$x^{-1}$} \addplot {x^(-2)}; \addlegendentry{$x^{-2}$} \addplot {x^(-3)}; \addlegendentry{$x^{-3}$} \end{semilogyaxis} \end{tikzpicture}

    The example provides options for the single multiline element. Note that the initial configuration of legend style employs text depth=0.15em, which needs to be reset manually to text depth={}.51

    There are two approaches with the same effect which are subject of the following example:

    (-tikz- diagram)

    % Preamble: \pgfplotsset{width=7cm,compat=1.18} \begin{tikzpicture} \begin{semilogyaxis}[ domain=0:4, legend entries={ $x$,$x^2$,$x^3$, {[text width=25pt,text depth=]Neg. Sign:}, $x^{-1}$,$x^{-2}$,$x^{-3}$}, % same effect: % legend style={ % nodes={text width=25pt,text depth=},} ] \addplot {x}; \addplot {x^2}; \addplot {x^3}; \addlegendimage{empty legend} \addplot {x^(-1)}; \addplot {x^(-2)}; \addplot {x^(-3)}; \end{semilogyaxis} \end{tikzpicture}

    Here, the legend entries are provided using the single key syntax. Note that the special options are provided as part of the legend entry, using square brackets right before the text as such. The comments indicate that you could also add the text width stuff to legend style, in which case it would hold for every node.

    Note that legend texts are realized using \node[(math image)options(math image)] {(math image)text(math image)};, so anything which produces a valid TikZ node is permitted (this includes minipage or tabular environments inside of (math image)text(math image)).

    51 Perhaps I can reset text depth automatically in the future.

    4.9.9Axis Lines

    An extension by Pascal Wolkotte

    By default the axis lines are drawn as a box, but it is possible to change the appearance of the \(x\)- and \(y\)-axis lines.

    • /pgfplots/axis line style={(math image)key-value-list(math image)}

    • A command which appends (math image)key-value-list(math image) to all axis line appearance styles.

    • /pgfplots/inner axis line style={(math image)key-value-list(math image)}

    • A command which appends (math image)key-value-list(math image) to both, every inner x axis line and the \(y\) variant.

    • /pgfplots/outer axis line style={(math image)key-value-list(math image)}

    • A command which appends (math image)key-value-list(math image) to both, every outer x axis line and the \(y\) variant.

    • /pgfplots/x axis line style={(math image)key-value-list(math image)}

    • /pgfplots/y axis line style={(math image)key-value-list(math image)}

    • /pgfplots/z axis line style={(math image)key-value-list(math image)}

    • A command which appends (math image)key-value-list(math image) to all axis lines styles for either \(x\)- or \(y\)-axis.

    • /pgfplots/every boxed x axis(no value)

    • /pgfplots/every boxed y axis(no value)

    • /pgfplots/every boxed z axis(no value)

    • A style which will be installed as soon as axis x line=box (y) is set.

      The default is simply empty.

    4.9.10Moving Axis Lines

    pgfplots offers styles to shift axis lines along their normal vector:

    4.9.11Two Ordinates (\(y\)-axis) or Multiple Axes

    In some applications, more than one \(y\)-axis is used if the \(x\) range is the same. This section demonstrates how to create them. The idea in pgfplots is to draw two axes on top of each other, one with descriptions only on the left and the second with descriptions only on the right:

    (-tikz- diagram)

    % Preamble: \pgfplotsset{width=7cm,compat=1.18} \begin{tikzpicture} % let both axes use the same layers \pgfplotsset{set layers} \begin{axis}[ scale only axis, xmin=-5,xmax=5, axis y line*=left, % the '*' avoids arrow heads xlabel=$x$, ylabel=First ordinate, ] \addplot {x^2}; \end{axis} \begin{axis}[ scale only axis, xmin=-5,xmax=5, axis y line*=right, axis x line=none, ylabel=Second ordinate, ] \addplot [red] {3*x}; \end{axis} \end{tikzpicture}

    Thus, the two axes are drawn “on top” of each other – one, which contains the \(x\)-axis and the left \(y\)-axis, and one which has only the right \(y\)-axis. Since pgfplots does not really know what it’s doing here, user attention in the following possibly non-obvious aspects is required:

    • 1. Scaling. You should set scale only axis because this forces equal dimensions for both axis, without respecting any labels.

    • 2. Same \(x\) limits. You should set those limits explicitly.

    • 3. You need to tell pgfplots that it should share the same graphics layers for both axes. In this case, pgfplots will draw plots of the first axis and of the second axis onto the same layer. It will also draw background(s) into the background layer and descriptions into the foreground layer. Use the key \pgfplotsset{set layers} in front of the first axis to prepare the complete picture for layered graphics.

    You may want to consider different legend styles. It is also possible to use only the axis, without any plots:

    (-tikz- diagram)

    % Preamble: \pgfplotsset{width=7cm,compat=1.18} % \usepackage{textcomp} \begin{tikzpicture} % let both axes use the same layers \pgfplotsset{set layers} \begin{axis}[ scale only axis, xmin=-5,xmax=5, axis y line*=left, % '*' avoids arrow heads xlabel=$x$, ylabel=Absolute, ] \addplot {x^2}; \end{axis} \begin{axis}[ scale only axis, xmin=-5,xmax=5, ymin=0,ymax=1000, yticklabel={ $\pgfmathprintnumber{\tick}$\textperthousand }, axis y line*=right, axis x line=none, ylabel=per thousand, ] \end{axis} \end{tikzpicture}
    4.9.12Axis Discontinuities

    An extension by Pascal Wolkotte

    In case the range of either of the axis do not include the zero value, it is possible to visualize this with a discontinuity decoration on the corresponding axis line.

    A problem might occur with the placement of the ticks on the axis. This can be solved by specifying the minimum or maximum axis value for which a tick will be placed.

    • /pgfplots/hide x axis=true|false (initially false)

    • /pgfplots/hide y axis=true|false (initially false)

    • /pgfplots/hide z axis=true|false (initially false)

    • /pgfplots/hide axis=true|false (initially false)

    • Allows to hide either a selected axis or all of them. No outer rectangle, no tick marks and no labels will be drawn. Only titles and legends will be processed as usual.

      Axis scaling and clipping (!) will be done as if you did not use hide axis.

      (-tikz- diagram)

      % Preamble: \pgfplotsset{width=7cm,compat=1.18} \begin{tikzpicture} \begin{axis}[ hide x axis, hide y axis, title={$x^2\cos(x)$}, ] \addplot {cos(x)*x^2}; \end{axis} \end{tikzpicture}% <- eliminate space.

      (-tikz- diagram)

      % Preamble: \pgfplotsset{width=7cm,compat=1.18} \begin{tikzpicture} \begin{axis}[ hide x axis, axis y line=left, title={$x^2\cos(x)$}, ] \addplot {cos(x)*x^2}; \end{axis} \end{tikzpicture}% <- eliminate space

      Note that a hidden axis contributes nothing to the resulting picture’s bounding box,52 see clip bounding box.

      (-tikz- diagram)

      % Preamble: \pgfplotsset{width=7cm,compat=1.18} % requires \usepgfplotslibrary{patchplots} % and compat=1.8 or newer \begin{tikzpicture} \begin{axis}[hide axis] \addplot3 [ patch, patch type=biquadratic, shader=interp, ] coordinates { (0,0,1) (6,1,0) (5,5,0) (-1,5,0) (3,1,0) (6,3,0) (2,6,0) (0,3,0) (3,3.75,0) }; \end{axis} \end{tikzpicture}% <- eliminate space

      This can be used to embed a pgfplots path which needs an axis to a standard TikZ picture. See also Section 4.26 for details how to synchronize the alignment between a pgfplots figure (which typically rescales its coordinates) to that of a standard tikzpicture.

      Note that pgfplots uses the input coordinates to determine the bounding box of the picture. In this case, the bounding box is slightly smaller than the shading. A cure would be to increase the bounding box manually.

      You may want to disable the clip path using the option clip=false.

    52 Since version 1.8.

    4.9.13Color Bars

    pgfplots supports mesh, surface and scatter plots which can use color maps. While color maps can be chosen as described in Section 4.7.6, they can be visualized using color bars.

    Remarks for special cases:

    • Since there is always only one color bar per plot, this color bar uses the axis wide configurations of color map and color data. Consider using colorbar source to select color data limits of a particular \addplot command instead.

    • If someone needs more than one color bar, the draw command above needs to be updated. See the key colorbar/draw/.code for this special case.

    Attention:

    colorbar right redefines every colorbar. That means any user customization must take place after colorbar right:

    % correct: \begin{axis}[colorbar right, colorbar style={}] % wrong, colorbar right resets the customization: \begin{axis}[colorbar style={}, colorbar right]

    Attention:

    colorbar left redefines every colorbar. That means any user customization must take place after colorbar left (see also the documentation for colorbar right).

    Attention:

    colorbar horizontal redefines every colorbar. That means any user customization must take place after colorbar horizontal:

    % correct: \begin{axis}[colorbar horizontal, colorbar style={}] % wrong, colorbar horizontal resets the customization: \begin{axis}[colorbar style={}, colorbar horizontal]

    Remark:

    A color bar is just a normal axis. That means every colorbar can contain specifications where to place tick labels, extra ticks, scalings and most other features of a normal axis as well (except nested color bars).

    • /pgfplots/colorbar style={(math image)key-value list(math image)}

    • A shortcut for every colorbar/.append style={(math image)key-value list(math image)}. It appends options to the colorbar style.

    • Predefined node current colorbar axis

    • A predefined node for the color bar of an axis. After \end{axis}, this node can be used to align further graphical elements at the color bar. Note that current axis refers to the axis as such while current colorbar axis refers to the color bar (which is an axis itself).

    • /pgfplots/colorbar/draw/.code={(math image)...(math image)}

    • This code key belongs to the low level interface of color bars. It is invoked whenever a color bar needs to be drawn. Usually, it won’t be necessary to use or modify this key explicitly.

      When this key is invoked, the styles inherited from the parent axis are already set and the required variables (see the documentation of every colorbar) are initialized.

      This code key can be replaced if one needs more than one color bar (or other wrinkles).

      The initial configuration is

      Please note that a color bar axis is nothing special as such – it is just a normal axis with one \addplot graphics command and it is invoked with a special set of options. The only special thing is that a set of styles and some variables are inherited from its parent axis.

    Attention:

    this style merely changes the appearance of the colorbar. The way colormaps are used to determine plot colors is unrelated to this key. See also colormap access=direct for ways to affect the color selection.

    The style uses \addplot3[(math image)options(math image)] to draw the colorbar, with domain set to the color range and the current value of the samples key to determine the number of samples. In other words: it uses \addplot expression and a surface plot to visualize the colorbar. Use colorbar style={samples=10} to change the number of samples.

    (-tikz- diagram)

    % Preamble: \pgfplotsset{width=7cm,compat=1.18} \begin{tikzpicture} \begin{axis}[colorbar sampled,colorbar style={samples=8}] \addplot [mesh,samples=40] {sin(deg(x))}; \end{axis} \end{tikzpicture}

    The (math image)options(math image) can be used to change the \addplot3 options used for the colorbar visualization. For example, colorbar sampled={surf,shader=interp} will use Gouraud shading which has visually the same effect as the standard color bar.

    Attention:

    this style merely changes the appearance of the colorbar. The way colormaps are used to determine plot colors is unrelated to this key. See also colormap access=direct for ways to affect the color selection.

    The initial configuration uses a scatter plot to visualize the colorbar, it can be changed by specifying (math image)options(math image).

    Furthermore, the axis appearance is changed using axis y line*=left|right, depending on the position of the color bar (or axis x line*=bottom for colorbar horizontal).

    Consider the tick align=outside feature if you prefer tick lines outside of the colorbar instead of inside.

    • /pgfplots/every colorbar sampled line(style, no value)

    • A style which is used by colorbar sampled line to change the color of the line without ticks.

      It is initially set to help lines.

    Limitations:

    This style has its best fit for colormap access=const, especially in conjunction with sample for=const.54 It may produce unexpected results when used for continuous mappings.

    53 This precise number formatting will be improved eventually – it is too limited for all number ranges.

    54 Note that sample for=const adds a dummy color. This dummy color is omitted when displaying colorbar as legend, assuming it is a dummy color for the last interval. This may produce unexpected effects when used with a continuous colormap.

    4.9.14Color Bars Outside Of an Axis

    Occasionally, one has multiple adjacent plots, each with the same colormap and the same point meta min and point meta max values and we’d like to show a single colorbar. pgfplots supports the colorbar to name feature which is similar to the related method for legends, legend to name:

    4.9.15Tick Labels

    Ticks and their labels are documented in Section 4.15.