0

I wish to create a shaded region between the step function and the curve. The following code gives the below graph.

\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\usetikzlibrary{fillbetween}
\begin{document}
\newcommand\myN{5}
\begin{tikzpicture}
\begin{axis}[
    axis lines=center,
    legend style={at={(1,1)},anchor=north east,fill=none},
    xlabel={$t$},
    ylabel={$y$},
    xmin=0,
    xmax={\the\numexpr\myN+2},
    ymin=0,
    ymax=1.3,
    xtick=\empty,
    ytick=\empty,
    extra x ticks={1, \myN},
    extra x tick labels={$1$, $n$},
    extra y ticks={1},
    title={sum of hatched region converges to Euler's constant}
]
\addplot[name path=A,domain=1:\myN+1,samples=501,smooth] {1/x};
\addlegendentry{$y = \frac{1}{t}$};
\addplot[name path=B,domain=1:\myN+1,samples=\myN+1,const plot,dashed] {1/x};
\addlegendentry{$y = \frac{1}{\lfloor t \rfloor}$};
% \addplot fill between [of=A and B];
\end{axis}
\end{tikzpicture}
\end{document}

tikz graph

I tried introducing a shading bewteen the curve (path A) and the step function (path B) with

\addplot fill between [of=A and B];

but the system complained "Undefined control sequence."

VS code error

1 Answer 1

2

Use \usepgfplotslibrary{fillbetween} instead of \usetikzlibrary{fillbetween}.

Complete MWE:

\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\usepgfplotslibrary{fillbetween}
\begin{document}
\newcommand\myN{5}
\begin{tikzpicture}
\begin{axis}[
    axis lines=center,
    legend style={at={(1,1)},anchor=north east,fill=none},
    xlabel={$t$},
    ylabel={$y$},
    xmin=0,
    xmax={\the\numexpr\myN+2},
    ymin=0,
    ymax=1.3,
    xtick=\empty,
    ytick=\empty,
    extra x ticks={1, \myN},
    extra x tick labels={$1$, $n$},
    extra y ticks={1},
    title={sum of hatched region converges to Euler's constant}
]
\addplot[name path=A,domain=1:\myN+1,samples=501,smooth] {1/x};
\addlegendentry{$y = \frac{1}{t}$};
\addplot[name path=B,domain=1:\myN+1,samples=\myN+1,const plot,dashed] {1/x};
\addlegendentry{$y = \frac{1}{\lfloor t \rfloor}$};
\addplot fill between [of=A and B];
\end{axis}
\end{tikzpicture}
\end{document}

Generated PDF

2
  • 1
    Thanks for answer. I found that out myself while looking into PGF Plots' manual. Jun 17, 2022 at 14:44
  • 1
    @GNUSupporter8964民主女神地下教會 sure, no problem! Feel free to mark the answer as correct :) Jun 17, 2022 at 14:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.