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.17Custom Annotations

Often, one may want to add custom drawing elements or descriptive texts to an axis. These graphical elements should be associated to some logical coordinate, grid point, or perhaps they should just be placed somewhere into the axis.

pgfplots assists with the following ways when it comes to annotations:

  • 1. You can explicitly provide any TikZ instruction like \draw ... ; into the axis. Here, the axis cs allows to provide coordinates of pgfplots.

    Furthermore, rel axis cs allows to position TikZ elements relatively (like “\(50\%\) of the axis’ width).

  • 2. pgfplots can automatically generate nodes at every coordinate using its nodes near coords feature.

  • 3. pgfplots allows you to place nodes on a plot, using the \addplot ... node[pos=(math image)fraction(math image)] {}; feature.

This section explains all of the approaches, except for the nodes near coords feature which is documented in its own section.

4.17.1Accessing Axis Coordinates in Graphical Elements
  • Coordinate system axis cs

  • pgfplots provides a new coordinate system for use inside of an axis, the “axis coordinate system”, axis cs.

    Note that this coordinate system is actually the default one whenever one writes graphical elements in an axis. There is just one place where you really need to provide this coordinate system explicitly: if you have symbolic x coords.

    Consequently, you can refer to this documentation as reference only; most standard use cases work directly (as of compat=1.11).

    It can be used to draw any TikZ graphics at axis coordinates. It is used like

    \draw (axis cs:18943,2.873391e-05) |- (axis cs:47103,8.437499e-06);

    (-tikz- diagram)

    % Preamble: \pgfplotsset{width=7cm,compat=1.18} \tikzstyle{every pin}=[ fill=white, draw=black, font=\footnotesize, ] \begin{tikzpicture} \begin{loglogaxis}[ xlabel={\textsc{Dof}}, ylabel={$L_2$ Error}, ] \addplot coordinates { (11, 6.887e-02) (71, 3.177e-02) (351, 1.341e-02) (1471, 5.334e-03) (5503, 2.027e-03) (18943, 7.415e-04) (61183, 2.628e-04) (187903, 9.063e-05) (553983, 3.053e-05) }; \node [coordinate,pin=above:{Bad!}] at (axis cs:5503,2.027e-03) {}; \node [coordinate,pin=left:{Good!}] at (axis cs:187903,9.063e-05) {}; \end{loglogaxis} \end{tikzpicture}

    However, since axis cs is the default coordinate system of pgfplots, you can simply omit the prefix axis cs: in coordinate descriptions.61

    (-tikz- diagram)

    % Preamble: \pgfplotsset{width=7cm,compat=1.18} \begin{tikzpicture} \begin{loglogaxis}[ xlabel=\textsc{Dof}, ylabel=$L_2$ Error, ] \draw (1793,4.442e-05) |- (4097,1.207e-05) node [near start,left] {$\frac{dy}{dx} = -1.58$}; \addplot coordinates { (5, 8.312e-02) (17, 2.547e-02) (49, 7.407e-03) (129, 2.102e-03) (321, 5.874e-04) (769, 1.623e-04) (1793, 4.442e-05) (4097, 1.207e-05) (9217, 3.261e-06) }; \end{loglogaxis} \end{tikzpicture}

    The effect of axis cs is to apply any custom transformations (including symbolic x coords), logarithms, data scaling transformations or whatever pgfplots usually does and provides a low level pgf coordinate as result.

    In case you need only one component (say, the \(y\) component) of such a vector, you can use the \pgfplotstransformcoordinatey command, see Section 9.4 for details about basic level access.

    The result of axis cs is always an absolute position inside of an axis. This means, in particular, that adding two points has unexpected effects: the expression (0,0) ++ (1,0) is not necessarily the same as (1,0). The background for such unexpected effects is that pgfplots applies a shifted linear transformation which moves the origin in order to support its high accuracy and high data range (compare the documentation of disabledatascaling).

    In order to express relative positions (or lengths), you need to use axis direction cs.

  • Coordinate system axis direction cs

  • While axis cs allows to supply absolute positions, axis direction cs supplies directions. It allows to express relative positions, including lengths and dimensions, by means of axis coordinates.

    As noted in the documentation for axis cs, adding two coordinates by means of the TikZ ++ operator may have unexpected effects. The correct way for ++ operations is axis direction cs:

    (-tikz- diagram)

    % Preamble: \pgfplotsset{width=7cm,compat=1.18} \begin{tikzpicture} \begin{axis} \draw [red,-stealth] (1000,0) -- % = line-to ++ % = calculate a vector sum (axis direction cs:1000,0); \addplot [only marks,mark=*] coordinates { (1000,0) (2000,1) }; \end{axis} \end{tikzpicture}

    Here, the target of the red arrow is the position (2000,0) as expected.

    Using relative positions is mainly useful for linear axes. Applying this command to log-axes might still work, but it requires more care.

    One use case is to supply lengths – for example in order to support circle or ellipse paths. The correct way to draw an ellipse in pgfplots would be to specify the two involved radii by means of two (axis direction cs:(math image)x,y(math image)) expressions. In general, this is possible if you use the basic level macros \pgfpathellipse and \pgfplotspointaxisdirectionxy. Please refer to the documentation of \pgfplotspointaxisdirectionxy for two examples of drawing arbitrary ellipses by means of this method.

    Since drawing circles and ellipses inside of an axis is a common use case, pgfplots automatically communicates its coordinate system transformations to TikZ: whenever you write \draw ellipse[x radius=(math image)x(math image),y radius=(math image)y(math image)], the arguments (math image)x(math image) and (math image)y(math image) are considered to be pgfplots direction vectors and are handed over to axis direction cs. Consequently, ellipses with axis parallel radii are straightforward and use the normal TikZ syntax:

    (-tikz- diagram)

    % Preamble: \pgfplotsset{width=7cm,compat=1.18} % requires \pgfplotsset{compat=1.5.1} ! \begin{tikzpicture} \begin{axis}[ xmin=-2.5, xmax=2.5, ymin=-2.5, ymax=2.5, xtick={-2,-1,0,1,2}, ytick={-2,-1,0,1,2}, grid=major, ] % standard tikz syntax: \draw [black] (0,0) ellipse [ x radius=1, y radius=2, ]; \draw [red] (0,0) ellipse [ rotate=90, x radius=1, y radius=2, ]; % see \pgfplotspointaxisdirectionxy % for arbitrary ellipses \end{axis} \end{tikzpicture}

    Here, the two ellipses are specified as usual in TikZ. pgfplots ensures that all necessary transformations are applied to the two radii. Note that pgfplots usually has different axis scales for \(x\) and \(y\). As a consequence, the rotated red ellipse does not fit into the axis lines; we would need to use axis equal to allow properly rotated ellipses.

Attention:

this modification to circles and ellipses requires \pgfplotsset{compat=1.5.1}.

The same applies to circles: in the standard view, a circle with radius=\(r\) will appear as an ellipse due to the different axis scales. Supplying axis equal results in true circles:

(-tikz- diagram)

% Preamble: \pgfplotsset{width=7cm,compat=1.18} % requires \pgfplotsset{compat=1.5.1} ! \begin{tikzpicture} \begin{axis}[tiny,enlargelimits, xmin=-1,xmax=1, ymin=-1,ymax=1, xtick={-1,0,1}, ytick={-1,0,1}, grid=major, ] \draw [blue] (0,0) circle [radius=1]; \end{axis} \end{tikzpicture}

(-tikz- diagram)

% Preamble: \pgfplotsset{width=7cm,compat=1.18} \begin{tikzpicture} \begin{axis}[tiny,enlargelimits, axis equal, xmin=-1,xmax=1, ymin=-1,ymax=1, xtick={-1,0,1}, ytick={-1,0,1}, grid=major, ] \draw [blue] (0,0) circle [radius=1]; \end{axis} \end{tikzpicture}

In case you need access to axis direction cs inside of math expressions, you can employ the additional math function transformdirectionx. It does the same as axis direction cs, but only in \(x\) direction. The result of transformdirectionx is a dimensionless unit which can be interpreted relative to the current pgf \(x\) unit vector \(e_x\) (see the documentation of \pgfplotstransformdirectionx for details). There are the math commands transformdirectionx, transformdirectiony, and (if the axis is three-dimensional) transformdirectionz. Each of them defines \pgfmathresult to contain the result of \pgfplotstransformdirectionx (or its variants for \(y\) and \(z\), respectively).

  • Predefined node current plot begin

  • This coordinate will be defined for every plot and can be used as (math image)trailing path commands(math image) or after a plot. It is the first coordinate of the current plot.

  • Predefined node current plot end

  • This coordinate will be defined for every plot. It is the last coordinate of the current plot.

  • /pgfplots/allow reversal of rel axis cs=true|false (initially true)

  • A fine-tuning key which specifies how to deal with x dir=reverse and rel axis cs and ticklabel cs.

    The initial configuration true means that points placed with rel axis cs and/or ticklabel cs will be at the same position inside of the axes even if its ordering has been reversed. The choice false will disable the special treatment of x dir=reverse.

61 As of pgfplots version 1.11 and compat=1.11. All older versions explicitly require the prefix; coordinates without the prefix will be placed at the wrong position.

4.17.2Changing the Appearance of Individual Coordinates

Some plot handlers, especially scatter plots in their different variants, support to modify the appearance of individual markers. To this end, they accept the syntax coordinate style:

(-tikz- diagram)

% Preamble: \pgfplotsset{width=7cm,compat=1.18} \begin{tikzpicture} \begin{axis}[axis equal] \addplot[ scatter, only marks, samples=50, point meta=100-sqrt(x^2+y^2), coordinate style/.condition= {sqrt(x^2+y^2) < 0.5}{scale=2}, coordinate style/.condition={\coordindex == 25}{ /pgfplots/scatter/@post marker code/.add code={ \node [pin=45:Point no 25] {}; }{}, }, ] (rand,rand); \draw (0,0) circle (0.5); \end{axis} \end{tikzpicture}

The previous example is a scatter plot of random points. The first coordinate style ensures that all points falling into the circle of radius \(0.5\) are drawn twice as large. The second coordinate style applies special drawing instructions to the point with index \(25\): it attaches a pin.

The key coordinate style is documented on page (??).

4.17.3Placing Nodes on Coordinates of a Plot

The \addplot command is not only used for pgfplots, it can also carry additional drawing instructions which are handed over to TikZ after the plot’s path is complete. Among others, this can be used to add further nodes on the path.

  • /tikz/pos={(math image)fraction(math image)}

  • The (math image)fraction(math image) identifies a part of the recently completed plot if it is used before the trailing semicolon:

    (-tikz- diagram)

    % Preamble: \pgfplotsset{width=7cm,compat=1.18} \begin{tikzpicture} \begin{axis} \addplot [blue,domain=0:360] {sin(x)} [yshift=8pt] node [pos=0] {$0$} node [pos=0.25] {$\pi/2$} node [pos=0.5] {$\pi$} node [pos=0.75] {$3/2\pi$} node [pos=1] {$2\pi$} ; \end{axis} \end{tikzpicture}

    Here, the [yshift=8pt] tells TikZ to shift all following nodes upwards. The node[pos=0] {$0$} instruction tells TikZ to add a text node at \(0\%\) of the recently completed plot. The relative position \(0\%\) (pos=0) refers to the first coordinate which has been seen by pgfplots, and \(100\%\) (pos=1) refers to the last coordinate. Any value between \(0\) and \(1\) is interpolated in-between. Note that all these nodes belong to the plot’s visualization (which is terminated by the semicolon). Consequently, all these nodes inherit the same graphic settings (like color choices).

    The position on the plot is computed by pgfplots using logical coordinates. That means: it computes the overall length of the curve before the curve is projected to screen coordinates and identifies the desired position.62 Afterwards, it projects the final position to screen coordinates. Thus, the position identifies a location on the plot which is always the same, even in case of a rotated three-dimensional axis. pgfplots will linearly interpolate the fraction between successive coordinates.

    Valid choices for (math image)fraction(math image) are any numbers in the range \([0,1]\).

    Note that the precise meaning of pos depends on the current plot handler: for most plot handlers, it defaults to linear interpolation (as in the examples above). For only marks, scatter, ybar, xbar, ybar interval, and xbar interval, it snaps to the nearest encountered coordinate. In this context, “snap to nearest” means that pos=\(p\) refers to the coordinate with index \(i = \text {round}(p \cdot N)\) where \(N\) is the total number of points:

    (-tikz- diagram)

    % Preamble: \pgfplotsset{width=7cm,compat=1.18} \begin{tikzpicture} \begin{axis}[title=Snap to nearest for scatter plots] \addplot+ [only marks] coordinates { (0,0) (1,1) (2,2) (3,3) } node [pos=0, pin=0 :0 ] {} node [pos=0.1, pin=90 :0.1 ] {} node [pos=0.2, pin=200:0.2 ] {} node [pos=0.3, pin=135:0.3 ] {} node [pos=0.4, pin=0 :0.4 ] {} node [pos=0.5, pin=60 :0.5 ] {} node [pos=0.75,pin=180:0.75] {} node [pos=1, pin=90 :1 ] {} ; \end{axis} \end{tikzpicture}

    the previous example shows that pos=\(p\) maps to one of the four available coordinates, namely the one whose index is closest to \(p\cdot N\). Note that in such a case, the distance between coordinates is irrelevant – only the coordinate index counts.

    Note that the fact that pgfplots uses logical coordinates to compute the target positions can produce unexpected effects if \(x\) and \(y\) axis operate on a different scales. Suppose, for example, that \(x\) is always of order \(10^3\) whereas \(y\) is of order \(10^{-3}\). In such a scenario, the \(y\)-coordinate have no significant contribution to the curve’s length – although the rescaled axes clearly show “significant” \(y\) dynamics. Consider using axis equal together with pos to produce comparable effects.

  • /tikz/sloped(initially false)

  • Providing the TikZ key sloped to a node identified by pos causes it to be rotated such that it adapts to the plot’s gradient.

    (-tikz- diagram)

    % Preamble: \pgfplotsset{width=7cm,compat=1.18} \begin{tikzpicture} \begin{axis} \addplot [blue,domain=0:360,samples=31] {sin(x)} [every node/.style={yshift=8pt},sloped] node [pos=0] {$0$} node [pos=0.25] {$\pi/2$} node [pos=0.5] {$\pi$} node [pos=0.75] {$3/2\pi$} node [pos=1] {$2\pi$} ; \end{axis} \end{tikzpicture}

    Note that the sequence in which sloped and shift transformations are applied is important: if shifts are applied first (as would be the case without the every node/.style construction), the shifts do not respect the rotation. If sloped is applied first, any subsequent shifts will be applied in the rotated coordinates. Thus, the case every node/.style={yshift=8pt} shifts every node by 8pt in direction of its normal vector.

    The sloped transformation is based on the gradient between two points (the two points adjacent to pos). Consequently, it inherits any sampling weaknesses. To see this, consider the example above with a different number of samples:

    (-tikz- diagram)

    % Preamble: \pgfplotsset{width=7cm,compat=1.18} % same as above with different number of samples \begin{tikzpicture} \begin{axis} \addplot [blue,domain=0:360,samples=25] {sin(x)} [every node/.style={yshift=8pt},sloped] node [pos=0] {$0$} node [pos=0.25] {$\pi/2$} node [pos=0.5] {$\pi$} node [pos=0.75] {$3/2\pi$} node [pos=1] {$2\pi$} ; \end{axis} \end{tikzpicture}

    Here, the two extreme points have small slopes due to the sampling. While this does not seriously affect the quality of the plot, it has a huge impact on the transformation matrices. Keep this in mind when you work with sloped (perhaps it even helps to add a further rotate argument).

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

  • If /tikz/sloped is enabled and one has some difficult line plot, the transformation may cause nodes to be drawn upside down. The default configuration allow upside down=false will switch the rotation matrix, whereas allow upside down allows this case.

Occasionally, one wants to place a node using pos and one wants to typeset the coordinates of that point inside of the node. This can be accomplished using \pgfplotspointplotattime:

  • \pgfplotspointplotattime

  • \pgfplotspointplotattime{(math image)fraction(math image)}

  • This command is part of the pos={(math image)fraction(math image)} implementation: it defines the current point of pgf to (math image)fraction(math image) of the current plot. Without an argument in curly braces, \pgfplotspointplotattime will take the current argument of the pos key.

    Thus, the command computes the basic pgf coordinates – but it also returns the logical coordinates of the resulting point into the following keys:

62 This can be a time-consuming process. Consider using the external library if you have lots of such figures.

4.17.4Placing Decorations on Top of a Plot

TikZ comes with the powerful decorations library (or better: set of libraries). Decorations allow to replace or extend an existing path by means of fancy additional graphics. An introduction into the decorations functionality of TikZ is beyond the scope of this manual and the interested reader should read the associated section in [7].

This section shows how to use decorations to enhance plots in pgfplots. Suppose you have some graphics for which you would like to add “direction pointers”:

(-tikz- diagram)

% Preamble: \pgfplotsset{width=7cm,compat=1.18} \begin{tikzpicture}[] % An undecorated graphics with a lot of % pretty-printing styles: \begin{axis}[ axis lines=middle, title=Undecorated Graphics, xmin=-2, xmax=2, ymin=-2, ymax=2, xtick={-1,1}, ytick={-1,1}, % this disables the standard % tick label *text* (but not the line) yticklabel=\ , extra description/.code={ % this generates custom y labels to implement % individual styles for every tick: \node [below left] at (axis cs:0,-1) {$-1$}; \node [above left] at (axis cs:0,1) {$1$}; }, axis line style={->}, ] \addplot [blue,samples=100,domain=0:2*pi] ({sin(deg(2*x))}, {sin(deg(x))}); \end{axis} \end{tikzpicture}

Our aim is to add short pointers indicating the direction of the parametrization.

The solution is to use \usetikzlibrary{decorations.markings} and a decoration inside of \addplot:

(-tikz- diagram)

% Preamble: \pgfplotsset{width=7cm,compat=1.18} % requires \usetikzlibrary{decorations.markings} \begin{tikzpicture}[] % Same as in previous example, but with decorations: \begin{axis}[ axis lines=middle, title=Decorated Graphics, xmin=-2, xmax=2, ymin=-2, ymax=2, xtick={-1,1}, ytick={-1,1}, % this disables the standard % tick label *text* (but not the line) yticklabel=\ , extra description/.code={ % this generates custom y labels to implement % individual styles for every tick: \node [below left] at (axis cs:0,-1) {$-1$}; \node [above left] at (axis cs:0,1) {$1$}; }, axis line style={->}, ] \addplot[blue,samples=100,domain=0:2*pi, postaction={decorate},% ------ decoration={markings, % ------ mark=at position 0.25 with {\arrow{stealth}}, mark=at position 0.5 with {\arrow{stealth}}, mark=at position 0.75 with {\arrow{stealth}}} ] ({sin(deg(2*x))}, {sin(deg(x))}); \end{axis} \end{tikzpicture}

The only changes are in the option list for \addplot: it contains a postaction={decorate} which activates the decoration (without replacing the original path) and some specification decoration containing details about how to decorate the path.

A discussion of details of the decorations libraries is beyond the scope of this manual (see [7] for details), but the main point is to add the required decorations to \addplot and its option list.