tikz.dev / PGFplots Manual

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

Related Libraries

\(\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}}}\)

5.7Fill between

  • \usepgfplotslibrary{fillbetween} % and plain

  • \usepgfplotslibrary[fillbetween] % Cont

  • \usetikzlibrary{pgfplots.fillbetween} % and plain

  • \usetikzlibrary[pgfplots.fillbetween] % Cont

  • The fillbetween library allows to fill the area between two arbitrary named plots. It can also identify segments of the intersections and fill the segments individually.

5.7.1Filling an Area
  • \addplot fill between [{(math image)options defined with prefix /tikz/fill between(math image)}] ;

  • \addplot[(math image)options(math image)] fill between [{(math image)options defined with prefix /tikz/fill between(math image)}] (math image)trailing path commands(math image);

  • \addplot3

  • A special plotting operation which takes two named paths on input and generates one or more paths resembling the filled area between the input paths.

    (-tikz- diagram)

    % Preamble: \pgfplotsset{width=7cm,compat=1.18}\usepgfplotslibrary{fillbetween} \begin{tikzpicture} \begin{axis} \addplot+ [name path=A,domain=0:1,samples=2] {x}; \addplot+ [name path=B] table { x y 0 2 0.5 -1 1 3 }; \addplot fill between [of=A and B]; \end{axis} \end{tikzpicture}

    The operation fill between requires at least one input key within (math image)options defined with prefix /tikz/fill between(math image): the two involved paths in the form of=(math image)first(math image) and (math image)second(math image). Here, both (math image)first(math image) and (math image)second(math image) need to be defined using name path (or name path global). The arguments can be exchanged,86 i.e. we would achieve the same effect for of=B and A.

    The argument (math image)options defined with prefix /tikz/fill between(math image) can contain any number of options which have the prefix /tikz/fill between. Note that the prefix refers to the reference manual, you do not need to type the prefix. This excludes drawing options like fill=orange; these options should be given as (math image)options(math image) (or inside of styles like every segment). Allowed options include of, split, soft clip, and style definitions of every segment and its friends, i.e. those which define which paths are to be acquired and how they should be processed before they can be visualized.

    A fill between operation takes the two input paths, analyzes their orientation (i.e. are its coordinates given increasing in \(x\) direction?), connects them, and generates a fill path.

    As mentioned above, the input paths need to be defined in advance (forward references are unsupported). If you would generate the filled path manually, you would draw it before the other ones such that it does not overlap. This is done implicitly by pgfplots: as soon as pgfplots encounters a fill between plot, it will activate layered graphics. The filled path will be placed on layer pre main which is between the main layer and the background layer.

    A fill between operation is just like a usual plot: it makes use of the cycle list, i.e. it receives default plot styles. Our first example above uses the default cycle list which has a brown color. We can easily redefine the appearance just as for any other plot by adding options in square braces:

    (-tikz- diagram)

    % Preamble: \pgfplotsset{width=7cm,compat=1.18}\usepgfplotslibrary{fillbetween} \begin{tikzpicture} \begin{axis} \addplot [blue,name path=A,domain=0:1] {sqrt(x)}; \addplot [red, name path=B,domain=0:1] {sqrt(x/2)}; \addplot [gray] fill between [of=A and B]; \end{axis} \end{tikzpicture}

    Note that the number of data points does not restrict fill between. In particular, you can combine different arguments easily.

    (-tikz- diagram)

    % Preamble: \pgfplotsset{width=7cm,compat=1.18}\usepgfplotslibrary{fillbetween} \begin{tikzpicture} \begin{axis} \addplot [blue,name path=A,domain=0:1] {sin(360*x)}; \addplot [red, name path=B,domain=0:1,samples=2] {0.5}; \addplot [orange] fill between [of=A and B]; \end{axis} \end{tikzpicture}

    The combination of input plots is also possible if one or both of the plots make use of smooth interpolation:

    (-tikz- diagram)

    % Preamble: \pgfplotsset{width=7cm,compat=1.18}\usepgfplotslibrary{fillbetween} \begin{tikzpicture} \begin{axis} \addplot+ [name path=A,samples=7,smooth,domain=0:1] {sin(360*x)}; \addplot+ [name path=B,samples=15,domain=0:1] {cos(360*x)}; \addplot [orange] fill between [of=A and B]; \end{axis} \end{tikzpicture}

    Actually, a fill between path operates directly on the low-level input path segments. As such, it is much closer to, say, a TikZ decoration than to a plot; only its use cases (legends, styles, layering) are tailored to the use as a plot. However, the input paths can be paths and/or plots. The example below combines one \addplot and one \path.

    (-tikz- diagram)

    % Preamble: \pgfplotsset{width=7cm,compat=1.18}\usepgfplotslibrary{fillbetween} \begin{tikzpicture} \begin{axis}[ymin=-0.2,enlargelimits] \addplot+ [name path=A,smooth] coordinates {(0,0) (1,1) (2,0)}; \path [name path=B] (0.5,-0.2) -- (1.8,-0.2); \addplot [orange] fill between [of=A and B]; \end{axis} \end{tikzpicture}

    As mentioned above, fill between takes the two input paths as such and combines them to a filled segment. To this end, it connects the endpoints of both paths. This can be seen in the example above: the path named ‘B’ has different \(x\)-coordinates than ‘A’ and results in a trapezoidal output.

    Here is another example in which a plot and a normal path are combined using fill between. Note that the \draw path is generated using nodes of path ‘A’. In such a scenario, we may want to fill only the second segment which is also possible, see split below.

    (-tikz- diagram)

    % Preamble: \pgfplotsset{width=7cm,compat=1.18}\usepgfplotslibrary{fillbetween} \begin{tikzpicture} \begin{axis} \addplot+ [name path=A,samples=15,domain=0:1] {cos(360*x)} coordinate [pos=0.25] (nodeA0) {} coordinate [pos=0.75] (nodeA1) {}; \draw [name path=B] (nodeA0) -- (nodeA1); \addplot [orange] fill between [of=A and B]; \end{axis} \end{tikzpicture}

    A fill between plot is different from other plotting operations with respect to the following items:

    • 1. It has no own markers and no nodes near coords. However, its input paths can have both.

    • 2. It supports no pos nodes. However, its input paths can have any annotations as usual.

    • 3. It supports no error bars. Again, its input paths support what pgfplots offers for plots.

    • 4. It cannot be stacked (its input plots can be, of course).

    Note that more examples can also be found in Section 4.5.10.2 on page (page for section 4.5.10.2) which covers Area Plots and has a lot of examples on fill between.

86 Note that some options refer explicitly to either the first or the second input path. These options are documented accordingly.

5.7.2Filling Different Segments of the Area
5.7.3Filling only Parts Under a Plot (Clipping)
  • /tikz/fill between/soft clip=(math image)argument(math image)

  • /tikz/fill between/soft clip first=(math image)argument(math image)

  • /tikz/fill between/soft clip second=(math image)argument(math image)

  • Installs “soft-clips” on both or just one of the involved paths. Soft-clipping means to modify the input paths such that they respect a clipping region.

    In its default configuration, fill between connects the start/end points of the two involved paths.

    This is often what you want, but there are use cases where only parts between the input parts should be filled: suppose we have \(f(x)=x^2\) and we want to fill below the interval \([3,5]\). The case “fill below” means to fill between our function and the \(x\)-axis:

    (-tikz- diagram)

    % Preamble: \pgfplotsset{width=7cm,compat=1.18}\usepgfplotslibrary{fillbetween} \begin{tikzpicture} \begin{axis} \addplot+ [name path=A,domain=0:5] {x^2}; \path [name path=B] (\pgfkeysvalueof{/pgfplots/xmin},0) -- (\pgfkeysvalueof{/pgfplots/xmax},0); \addplot [orange] fill between [of=A and B]; \end{axis} \end{tikzpicture}

    Clearly, we have filled too much. A solution might be to shorten the path B – but that would still connect the left and right end points of \(f(x)\) with the shortened line.

    This is where soft clip has its uses: we can select the area of interest by installing a soft clip path:

    (-tikz- diagram)

    % Preamble: \pgfplotsset{width=7cm,compat=1.18}\usepgfplotslibrary{fillbetween} \begin{tikzpicture} \begin{axis} \addplot+ [name path=A,domain=0:5] {x^2}; \path [name path=B] (\pgfkeysvalueof{/pgfplots/xmin},0) -- (\pgfkeysvalueof{/pgfplots/xmax},0); \addplot [orange] fill between [ of=A and B, soft clip={domain=3:5}, ]; \end{axis} \end{tikzpicture}

    Soft-clipping is similar to clipping. In fact, we could have installed a clip path to achieve the same effect.87 However, soft-clipping results in a new path which is aware of the boundaries. Consequently, decorations will be correct, without suffering from missing image parts due to the clipping:

    (-tikz- diagram)

    % Preamble: \pgfplotsset{width=7cm,compat=1.18}\usepgfplotslibrary{fillbetween} \begin{tikzpicture} \begin{axis} \addplot+ [name path=A,domain=0:5] {x^2}; \path [name path=B] (\pgfkeysvalueof{/pgfplots/xmin},0) -- (\pgfkeysvalueof{/pgfplots/xmax},0); \addplot[ orange, decorate,decoration={ footprints, foot of=bird, stride length=15pt, foot sep=2pt, foot length=6pt, }, ] fill between [ of=A and B, soft clip={domain=3:5}, ]; \end{axis} \end{tikzpicture}

    The feature soft clip is a part of fill between in the sense that it determines the fill path.

    The (math image)argument(math image) can be one of the following items:

    • It can be of the form domain=(math image)xmin(math image):(math image)xmax(math image). This choice is equivalent to

      ((math image)xmin(math image),\pgfkeysvalueof{/pgfplots/ymin}) rectangle

      ((math image)xmax(math image),\pgfkeysvalueof{/pgfplots/ymax}).

    • It can be of the form domain y=(math image)ymin(math image):(math image)ymax(math image). This choice is equivalent to

      (\pgfkeysvalueof{/pgfplots/xmin},(math image)ymin(math image)) rectangle

      (\pgfkeysvalueof{/pgfplots/xmax},(math image)ymax(math image)).

    • It can be ((math image)x(math image),(math image)y(math image)) rectangle ((math image)X(math image),(math image)Y (math image)). In this case, it is the rectangle defined by the given points.

    • It can be the name of a named path, i.e. soft clip=A if there exists a path with name path=A.

      In this case, the named path has to be “reasonable simple”. In particular, it should be convex, that is like a rectangle, a circle, or some cloud. It should also be closed.

    In any case, the soft clip path should be larger than the paths it applies to. Please avoid infinitely many intersections points.

    (-tikz- diagram)

    % Preamble: \pgfplotsset{width=7cm,compat=1.18}\usepgfplotslibrary{fillbetween} \begin{tikzpicture} \begin{axis} \draw [help lines,name path=clippath] (0,-5) -- (-5,0) -- (2,4) -- (4,-4) --cycle; \addplot+ [name path=A] {x}; \draw [red,name path=B] (0,\pgfkeysvalueof{/pgfplots/ymin}) -- (0,\pgfkeysvalueof{/pgfplots/ymax}); \addplot[gray!50] fill between [ of=A and B, soft clip={clippath} ]; \end{axis} \end{tikzpicture}

    The previous example defines three named paths: the path A is \(f(x) = x\). The named path clippath serves as clip path, it is some rotated rectangular form. Finally, the path named B is a straight line – and we fill between A and B with the given clippath.

    The choice soft clip first applies the clip path only to the first input path (“A” in our case).

    The choice soft clip second applies the clip path only to the second input path (“B” in our case).

    Finally, soft clip applies the clip path to both input paths.

    (-tikz- diagram)

    % Preamble: \pgfplotsset{width=7cm,compat=1.18}\usepgfplotslibrary{fillbetween} % requires \usepgfplotslibrary{fillbetween} \begin{tikzpicture} \begin{axis} \addplot+ [name path=A,domain=0:5] {x^2}; \path [name path=B] (\pgfkeysvalueof{/pgfplots/xmin},0) -- (\pgfkeysvalueof{/pgfplots/xmax},0); \addplot [gray] fill between [ of=A and B, soft clip={ (3,-1) rectangle (4,100) }, ]; \addplot [gray!30] fill between [ of=A and B, soft clip={ (2,-1) rectangle (3,100) }, ]; \end{axis} \end{tikzpicture}

    Note that there is also a separate module which allows to apply soft-clipping to individual paths. To this end, a decoration=soft clip is available. A use case could be to highlight parts of the input path:

    (-tikz- diagram)

    % Preamble: \pgfplotsset{width=7cm,compat=1.18}\usepgfplotslibrary{fillbetween} \begin{tikzpicture} \begin{axis} \addplot [name path=A,domain=0:5, postaction={decorate,red,thick}, decoration={ soft clip, soft clip path={domain=3:5}, }, ] {x^2}; \path [name path=B] (\pgfkeysvalueof{/pgfplots/xmin},0) -- (\pgfkeysvalueof{/pgfplots/xmax},0); \addplot [orange] fill between [ of=A and B, soft clip={ (3,-1) rectangle (5,100) }, ]; \end{axis} \end{tikzpicture}

    Note that more examples can also be found in Section 4.5.10.2 on page (page for section 4.5.10.2) which covers Area Plots and has a lot of examples on fill between.

87 Installing a clip path might need to adopt layers: fill between is on layer pre main and the clip path would need to be on the same layer.

5.7.4Styles Around Fill Between
  • /tikz/fill between/every odd segment(style, no value)

  • A style which is installed for every odd segment generated by fill between.

    Attention: this style makes only sense if split is active.

    See every segment for the sequence in which the styles will be invoked.

  • /tikz/fill between/every even segment(style, no value)

  • A style which is installed for every even segment generated by fill between.

    Attention: this style makes only sense if split is active.

    See every segment for the sequence in which the styles will be invoked.

  • /tikz/fill between/every segment no (math image)index(math image)(style, no value)

  • A style which is installed for every segment with the designated index (math image)index(math image) generated by fill between.

    An index is a number starting with \(0\) (which is used for the first segment).

    Attention: this style makes only sense if split is active.

    See every segment for the sequence in which the styles will be invoked.

  • /tikz/fill between/every last segment(style, no value)

  • A style which installed for every last segment generated by fill between.

  • \tikzsegmentindex

  • A command which is valid while the paths of \addplot fill between are generated.

    It expands to the segment (math image)index(math image), i.e. the same value which is used by every segment no (math image)index(math image).

    An index is a number starting with \(0\) (which is used for the first segment).

5.7.5Key Reference
  • /tikz/fill between/of=(math image)first(math image) and (math image)second(math image)

  • This key is mandatory. It defines which paths should be combined.

    The arguments are names which have been assigned to paths or plots in advance using name path. Paths with these two names are expected in the same tikzpicture.

    The fillbetween library supports a variety of input paths, namely

    • plots of functions, i.e. each \(x\)-coordinate has at most one \(y\)-coordinate,

    • plots with interruptions,

    • TikZ paths which meet the same restrictions and are labelled by name path,

    • smooth curves or curveto paths,

    • mixed smooth non-smooth parts.

    However, it has at most restricted support (or none at all) for paths which

    • have self-intersections (i.e. parametric plots might pose a problem),

    • have coordinates which are given in a strange input sequence,

    • consist of lots of individually separated sub-paths (like mesh or surf plots).

    Note that the input paths do not necessarily need to be given in the same sequence, see fill between/reverse.

  • /tikz/name path={(math image)name(math image)}

  • A TikZ instruction which assigns a name to a path or plot.88

    This is mandatory to define input arguments for fill between/of.

  • /tikz/fill between/inner moveto=connect|keep (initially connect)

  • Sometimes input paths contain the leading moveto operation and some inner movetos. This key configures how to deal with them.

    The initial choice connect replaces them by lineto operations (and connects them).89

    The choice keep keeps them.

    Typically, fill between requires the initial choice connect as it allows to deal with interrupted paths:

    (-tikz- diagram)

    % Preamble: \pgfplotsset{width=7cm,compat=1.18}\usepgfplotslibrary{fillbetween} \begin{tikzpicture} \begin{axis} \addplot [blue,ultra thick,name path=A, jump mark left] {x}; \path [name path=B] (-5,0) -- (5,0); \addplot [top color=red, bottom color=white] fill between [of=A and B]; \end{axis} \end{tikzpicture}

88 Note that TikZ also knows name path global. This key has the same effect and is an alias for name path within a pgfplots environment.

89 Note that the actual implementation of inner moveto=connect is more complicated: it also deduplicates multiple adjacent movetos and it eliminates “empty” moveto operations at the end of a path (i.e. moveto operations which are not followed by any path operation).

5.7.6Intersection Segment Recombination

The implementation of fill between relies on path recombination internally: all intersection segments are computed and concatenated in a suitable order (possibly reversed).

This method can also be applied to plain TikZ paths to achieve interesting effects:

(-tikz- diagram)

% Preamble: \pgfplotsset{width=7cm,compat=1.18}\usepgfplotslibrary{fillbetween} \begin{tikzpicture} \def\verticalbar{2} \begin{axis}[domain=-5:8,samples=25,smooth,width=12cm,height=7cm] % Draw curves \addplot [name path=g0,thin] {exp(-x^2/4)}; \addlegendentry{$\mathcal{N}(0)$} \addplot [name path=g2.5,thin] {exp(-(x-2.5)^2/4)}; \addlegendentry{$\mathcal{N}(\frac52)$} % Draw vertical bar: \draw [name path=red,red,thick] (\verticalbar,-1) -- (\verticalbar,2); \path [name path=axis] (-10,0) -- (16,0); \addplot [black!10] fill between [ of=g0 and g2.5, soft clip={domain=-6:\verticalbar}, split, every segment no 0/.style={left color=blue,right color=white}, every segment no 1/.style={pattern=grid,pattern color=gray}, ]; \addlegendentry{fill} % compute + label the lower segment (but do not draw it): \path [name path=lower, % draw=red,ultra thick, intersection segments={of=g0 and g2.5,sequence=R1 -- L2} ]; \addplot [pattern=north west lines, pattern color=orange] fill between [ of=axis and lower, soft clip={domain=-6:\verticalbar}, ]; \addlegendentry{lower} \end{axis} \end{tikzpicture}

This example has two plots, one with a Gauss peak at \(x=0\) and one with a Gauss peak at \(x=\frac 52\). Both have standard legend entries. Then we have a red line drawn at \(x=\;\)\verticalbar which is defined as \(x=2\). The third plot is a fill between with splitted segments where the left segment has a shading and the right one has a pattern – and both are clipped to the part which is left of \verticalbar. The option list which comes directly after \addplot, i.e. the [black!10] will be remembered for the legend entry of this plot. The next \path... instruction has no visible effect (and does not increase the size of the document).90 However, it contains the key intersection segments which computes a path consistent of intersection segments of the two functions. In our case, we connect the first (\(1\)st) segment of the path named g2.5 (which is referred to as R in the context of sequence) and the second (\(2\)nd) segment of the path named g0 (which is referred to as L in the context of sequence). The result receives name path=lower. Finally, the last \addplot is a fill between which fills everything between the axis and this lower path segment, again clipped to the parts left of \verticalbar. Note that axis is no magic name; it has been defined in our example as well. This is explained in more detail in the following paragraphs.

  • /tikz/intersection segments={(math image)options with prefix /tikz/segments(math image)}

  • Evaluates (math image)options(math image) and appends intersection segments to the current path.

    This key is actually more a command: it acquires the two input paths which are argument of the mandatory of key and it parses the (math image)series specification(math image) which is argument of sequence. Afterwards, it computes the intersection segments and concatenates them according to (math image)series specification(math image). Each resulting segment is appended to the current path as is.

    The key intersection segments can occur more than once in the current path. Since the key generates path elements, it is sufficient to terminate the path right after options have been processed (i.e. to add ‘;’ right after the option list).

    Note that this method operates on the transformed paths and does not apply coordinate transformations on its own. It is more like a decoration than a standard path command, although it does not have an input path.

    There is also a related key name intersections in the intersections library of TikZ which assigns names to all intersections, see the manual of TikZ for details.

  • /tikz/segments/of={(math image)name1(math image)} and {(math image)name2(math image)}

  • Defines the two input paths.

  • /tikz/segments/sequence={(math image)series specification(math image)} (initially L1 -- R2)

  • Selects the intersection segments and their sequence.

    The (math image)series specification(math image) consists of a sequence of entries of the form L(math image)index(math image) -- R(math image)index(math image) -- L(math image)index(math image). It is probably best shown before we delve into the details:

    (-tikz- diagram)

    % Preamble: \pgfplotsset{width=7cm,compat=1.18}\usepgfplotslibrary{fillbetween} \begin{tikzpicture} \begin{axis}[domain=0:10] \addplot [name path=first,blue] {sin(deg(x)) + 2/5*x}; \addplot [name path=second,red,samples=16,smooth] {cos(deg(1.2*x)) + 2/5*x}; \draw [ black,-stealth, decorate,decoration={ saw, post=lineto, post length=10pt, }, intersection segments={ of=first and second, sequence={ L1 -- R2 -- R3 -- R4 -- L4[reverse] }, }, ]; \end{axis} \end{tikzpicture}

    The preceding example defines two input plots of different sampling density, one is a sharp plot and one is smooth. Afterwards, it draws a third path with a saw decoration – and that path concatenates intersection segments.

    The entry L1 means to take the first intersection segment of the first input path. In this context, the first input path is always called ‘L’, regardless of its actual name. Note that L1 refers to an entire segment (not just a point).

    The second item is -- which means to connect the previous segment with the next one. Without this item, it would have moved to the next one, leaving a gap. Note that -- is normally a connection between two points. In this context, it is a connection between two segments.

    The third item is R2 which means to use the second intersection segment of the second input path. Again, the second input path is always called ‘B’, regardless of its actual name. The other items are straightforward until we arrive at L4[reverse]: it is possible to append an reversed path segment this way.

    The general syntax is to add an (arbitrary) sequence of [--] [L|R] {(math image)index(math image)}[(math image)options(math image)] where (math image)options(math image) is optional. There is one special case: if (math image)index(math image) is *, the entire path will be used. If all encountered indices are *, the intersection will not be computed at all (in this case, intersection segments degenerates to “path concatenation”). Consequently, the following example is a degenerate case in which we did “path concatenation” rather than intersection concatenation:

    (-tikz- diagram)

    \pgfdeclarelayer{pre main} \begin{tikzpicture} \pgfsetlayers{pre main,main} \draw [-stealth,thick,name path=A,red] (0,0) -- (1,1); \draw [-stealth,thick,name path=B,blue] (0,-1) -- (1,0); \pgfonlayer{pre main} \fill [ orange, intersection segments={ of=A and B, sequence={L* -- R*[reverse]}, }, ]; \endpgfonlayer \end{tikzpicture}

    Note that segment indices start at \(1\). They will be processed by means of pgf’s math parser and may depend on \pgfintersectionsolutions (which is the number of intersections).

    Note that there is actually another syntax: you can use A(math image)0-based-index(math image) for the first input path and B(math image)0-based-index(math image) for the second input path. These identifiers were introduced in pgfplots 1.10, but have been deprecated in favor of 1-based indices. The old syntax with 0-based indices will still remain available. It is advised to use L and R instead of A and B.

    Note that curly braces around {(math image)index(math image)} can be omitted if the index has just one digit: L1, L2, or L-2 are all valid.

    It is also possible to use negative indices to count from the last:

    (-tikz- diagram)

    \pgfdeclarelayer{pre main} \begin{tikzpicture} \pgfsetlayers{pre main,main} \draw [-stealth,thick,name path=A,red] (0,0) -- (1,1); \draw [-stealth,thick,name path=B,blue] (0,1) -- (1,0); \pgfonlayer{pre main} \draw [ green, line width=2pt, intersection segments={ of=A and B, sequence={L-1}, }, ]; \endpgfonlayer \end{tikzpicture}

    In this case \(-1\) denotes the first segment in reverse ordering.

    Note that \pgfintersectionsegments is the number of segments in this context.

90 Well, perhaps 8 byte for scopes.

5.7.7Basic Level Reference

There are a couple of basic level functions which allow to control fillbetween on a lower level of abstraction. The author of this package lists them here for highly experienced power-users (only). It might be suitable to study the source code to get details about these methods and how and where they are used.

  • \tikzfillbetween[(math image)options(math image)]{(math image)draw style(math image)}

  • This is the low-level interface of fill between; it generates one or more paths.

    This command can be used inside of a plain TikZ picture, it is largely independent of pgfplots:

    (-tikz- diagram)

    \begin{tikzpicture} \draw [name path=first] (0,0) -- (1,1) -- (2,0); \draw [name path=second] (0,0.5) -- (2,0.5); \tikzfillbetween [of=first and second, split, every even segment/.style={orange} ] {red} \end{tikzpicture}

    The first argument (math image)options(math image) describes how to compute the filled regions like of or split. It corresponds to those items which are in \addplot fill between[(math image)options(math image)].

    The second argument (math image)draw style(math image) is the default draw style which is installed for every generated path segment.

    Note that \tikzfillbetween is no typically \path statement: it generates one or more of TikZ \path statements (each with their own, individual draw style).

    Inside of \tikzfillbetween, the macro \tikzsegmentindex will expand to the current segment index. It can be used inside of styles.

    The key on layer is respected here: if on layer has a valid layer name (pre main by default), the generated paths will be on that layer. However, unlike \addplot fill between, this command does not ensure that layered graphics is active. As soon as you write, say, \pgfsetlayers{pre main,main}, it will automatically use these layers. If not, you will see a warning message in your .log file.

  • \pgfcomputeintersectionsegments{(math image)1 or 2(math image)}

  • Given that some intersections have been computed already (and are in the current scope), this command computes the intersection segments for one of the input arguments.

    On output, \pgfretval contains the number of computed segments. The segments as such can be accessed via \pgfgetintersectionsegmentpath.

    The argument (math image)1 or 2(math image) should be 1 if intersection segments of the first argument of \pgfintersectionofpaths are to be computed and 2 if the second argument should be used as input.

    This macro is part of fillbetween.

    Let us illustrate the effects of some of these methods on the following example.

    (-tikz- diagram)

    \begin{tikzpicture} \draw [red] (0,0) -- (1,1) -- (2,0); \draw [blue] (0,0.5) -- (2,0.5); \end{tikzpicture}

    We have two lines, both start on the left-hand-side. Our goal is to get a new path consisting of the intersections segments on the lower part of the picture, i.e. we would like to see

    (-tikz- diagram)

    \begin{tikzpicture} % this is our goal -- but computed automatically. \draw [black] (0,0) -- (0.5,0.5) -- (1.5,0.5) -- (2,0); \end{tikzpicture}

    In order to let fillbetween compute the target path, we assign names to the input paths, compute the intersections – and recombined them using \pgfcomputeintersectionsegments.

Attention:

Before you want to replicate this example, you may want to read about intersection segments which is a much simpler way to get the same effect!

(-tikz- diagram)

\begin{tikzpicture}[line join=round,x=3cm,y=3cm] \draw [name path=first,red] (0,0) -- (1,1) -- (2,0); \draw [name path=second,blue] (0,0.5) -- (2,0.5); % from 'name path' to softpaths... \tikzgetnamedpath{first} \let\A=\pgfretval \tikzgetnamedpath{second} \let\B=\pgfretval % compute intersections using the PGF intersection lib... \pgfintersectionofpaths{\pgfsetpath\A}{\pgfsetpath\B}% % ... and compute the intersection *segments* for both input % paths... \pgfcomputeintersectionsegments1 \pgfcomputeintersectionsegments2 % ... recombine the intersection segment paths! \pgfgetintersectionsegmentpath{1}{0}% path 1, segment 0 \pgfsetpathandBB\pgfretval% this starts a new path \pgfgetintersectionsegmentpath{2}{1}% path 2, segment 1 % connect, not move. Try to eliminate this line to see the effect \pgfpathreplacefirstmoveto\pgfretval% \pgfaddpathandBB\pgfretval% append \pgfgetintersectionsegmentpath{1}{2}% \pgfpathreplacefirstmoveto\pgfretval \pgfaddpathandBB\pgfretval \pgfsetlinewidth{3} \pgfsetcolor{black} \pgfusepath{stroke} \end{tikzpicture}

Note that this operates on a relatively low level. However, you can easily insert these statements into a \pgfextra in order to embed it into TikZ. This allows access to any TikZ options, including decorate:

(-tikz- diagram)

\begin{tikzpicture}[line join=round,x=3cm,y=3cm] \draw [name path=first,red] (0,0) -- (1,1) -- (2,0); \draw [name path=second,blue] (0,0.5) -- (2,0.5); \draw [ orange, decorate,decoration={ footprints, foot of=bird, stride length=15pt, foot sep=2pt, foot length=6pt}, ] \pgfextra % from 'name path' to softpaths... \tikzgetnamedpath{first} \let\A=\pgfretval \tikzgetnamedpath{second} \let\B=\pgfretval % % compute intersections using the PGF intersection lib... \pgfintersectionofpaths{\pgfsetpath\A}{\pgfsetpath\B}% % % ... and compute the intersection *segments* for both input % paths... \pgfcomputeintersectionsegments1 \pgfcomputeintersectionsegments2 % % ... recombine the intersection segment paths! \pgfgetintersectionsegmentpath{1}{0}% path 1, segment 0 \pgfsetpathandBB\pgfretval% this starts a new path \pgfgetintersectionsegmentpath{2}{1}% path 2, segment 1 \pgfpathreplacefirstmoveto\pgfretval% connect, not move \pgfaddpathandBB\pgfretval% append \pgfgetintersectionsegmentpath{1}{2}% \pgfpathreplacefirstmoveto\pgfretval \pgfaddpathandBB\pgfretval \endpgfextra ; \end{tikzpicture}

Attention:

Before you want to replicate this example, you may want to read about intersection segments which is a much simpler way to get the same effect!

  • \pgfgetintersectionsegmentpath{(math image)1 or 2(math image)}{(math image)index(math image)}

  • Defines \pgfretval to contain the desired path segment as softpath.

    The result has the same quality as a path returned by \pgfgetpath and can be used by means of \pgfsetpath, \pgfsetpathandBB, or \pgfaddpathandBB.

    The value (math image)1 or 2(math image) resembles the argument of a preceding call to \pgfcomputeintersectionsegments: it identifies which of the two paths for which intersections have been computed is to be selected.

    The second argument (math image)index(math image) is a number \(0 \le i < N\) where \(N\) is the total number of computed segments. The total number of computed segments is returned by \pgfcomputeintersectionsegments.

    This macro is part of fillbetween.

  • \tikzgetnamedpath{(math image)string name(math image)}

  • Defines \pgfretval to contain the softpath associated with (math image)string name(math image). The (math image)string name(math image) is supposed to be the value of name path or name path global.

    The resulting value is a softpath, i.e. it has the same quality as those returned by \pgfgetpath.

    This macro is part of fillbetween.

  • \tikznamecurrentpath{(math image)string name(math image)}

  • Takes the current softpath (the one assembled by previous moveto, lineto, or whatever operations), and assigns the name (math image)string name(math image) to it.

    This macro is part of fillbetween.

  • \pgfcomputereversepath{(math image)\softpathmacro(math image)}

  • Takes a softpath (math image)\softpathmacro(math image) and computes its reversed path.

    It stores the resulting softpath into \pgfretval.

    This macro is part of fillbetween.

  • \pgfgetpath{(math image)\softpathmacro(math image)}

  • Stores the current softpath into the macro (math image)\softpathmacro(math image).

    See also \tikzgetnamedpath.

    This macro is part of pgf.

  • \pgfsetpath{(math image)\softpathmacro(math image)}

  • Replaces the current softpath from the macro (math image)\softpathmacro(math image).

    This does not update any bounding boxes. Note that this takes a softpath as it is, no transformation will be applied. The only way to modify the path and its coordinates is a decoration or a canvas transformation.

    This macro is part of pgf.

  • \pgfaddpath{(math image)\softpathmacro(math image)}

  • Appends the softpath from the macro (math image)\softpathmacro(math image) to the current softpath.

    This does not update any bounding boxes. Note that this takes a softpath as it is, no transformation will be applied. The only way to modify the path and its coordinates is a decoration or a canvas transformation.

    This macro is part of pgf.

  • \pgfsetpathandBB{(math image)\softpathmacro(math image)}

  • Replaces the current softpath from the macro (math image)\softpathmacro(math image).

    This updates the picture’s bounding box by the coordinates found inside of (math image)\softpathmacro(math image). Aside from that, the same restrictions as for \pgfsetpath hold here as well.

    This macro is part of fillbetween.

  • \pgfaddpathandBB{(math image)\softpathmacro(math image)}

  • Appends the softpath of macro (math image)\softpathmacro(math image) to the current softpath.

    This updates the picture’s bounding box by the coordinates found inside of (math image)\softpathmacro(math image). Aside from that, the same restrictions as for \pgfsetpath hold here as well.

    This macro is part of fillbetween.

  • \pgfpathreplacefirstmoveto{(math image)\softpathmacro(math image)}

  • Takes a macro containing a softpath on input, replaces its first moveto operation by a lineto operation and returns it as \pgfretval.

    The argument (math image)\softpathmacro(math image) is one which can be retrieved by \pgfgetpath.

    This macro is part of fillbetween.

  • \pgfintersectionofpaths{(math image)first(math image)}{(math image)second(math image)}

  • The pgf basic layer command to compute intersections of two softpaths. In contrast to the name path method provided by TikZ, this command accepts different argument: (math image)first(math image) and (math image)second(math image) are supposed to set paths, i.e. they should contain something like \pgfsetpath{\somesoftpath}.

    Results are stored into variables of the current scope.

    This macro is part of pgf.

  • \tikzpathintersectionsegments[(math image)options with prefix /tikz/segments(math image)]

  • An alias for \tikzset{intersection segments={(math image)options(math image)}}.

  • \pgfpathcomputesoftclippath{(math image)\inputsoftpath(math image)}{(math image)\softclippath(math image)}

  • Does the work for soft clip: it computes the soft-clip path of (math image)\inputsoftpath(math image) when it is clipped against (math image)\softclippath(math image).

    The algorithm has been tested and written for rectangular soft clip paths. It will accept complicated clip paths, and might succeed with some of them. Nevertheless, rectangular soft clip paths are the ones which are supported officially.

    See soft clip for details.

5.7.8Pitfalls and Limitations

The fillbetween backend is quite powerful and successfully computes many use cases around “filling path segments of arbitrary plots” out of the box.

However, it has a couple of limitations which may or may not be overcome by future releases:

  • 1. The first limitation is scalability. The underlying algorithms are relatively inefficient and scale badly if the number of samples is large. Please apply it to “reasonable sample sizes” and plots with a “reasonable number of intersections”. That means: if it takes too long, you may need to reduce the sampling density.

  • 2. The second limitation is accuracy. The fillbetween functionality relies on the intersections library of pgf which, in turn, may fail to find all intersections (although its accuracy and reliability has been improved considerably as part of the work on fillbetween, thanks to Mark Wibrow of the pgf team for his assistance).

    The workaround for this limitation might be to reduce the sampling density – and to file bug reports.

  • 3. Another limitation is generality. The fillbetween library allows to combine smooth and sharp plots, even const plots with jumps, and all out of the box. It will do so successfully as long as you have “plot-like” structures. But it may fail if

    • plots intersect themselves and you try to compute individual segments using split or intersection segments,

    • the plot has circles,

    • the two involved plots have infinitely many intersections (i.e. are on top of each other).

Many of these limitations are present in pgf as well, especially when decorateing paths or when using name intersections.