A Plot for Euler's Constant

My first PGF Plot for step functions

I firsted tried with foreach, but that would create so much paths. I found them difficult to operate on later, for example, with PGF plots library fillbetween. const plot is a better solution.

\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\usetikzlibrary{patterns}
\usepgfplotslibrary{fillbetween}
\begin{document}
\newcommand\myN{8}
\pgfplotsset{
    axis lines=center,
    legend style={at={(1,1)},anchor=north east,fill=none},
    title style={at={(0.5,1.05)}},
    every axis x label/.style={
        at={(ticklabel* cs:1)},
        anchor=west,
    },
    every axis y label/.style={
        at={(ticklabel* cs:1)},
        anchor=south,
    },
}
\begin{tikzpicture}
\begin{axis}[
    title={sum of hatched region converges to Euler's constant},
    xlabel={$x$},
    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},
]
\addplot[name path=A,domain=1:\myN,samples=501,smooth] {1/x} \closedcycle;
\addlegendentry{$y = \frac{1}{x}$};
\addplot+[domain=1:\myN+1,samples=\myN+1,jump mark left,blue,mark=*,mark options={draw=blue,fill=blue}] {1/x};
\addlegendentry{$y = \frac{1}{\lfloor x \rfloor}$};
\addplot+[name path=B,domain=1:\myN+1,samples=\myN+1,jump mark left,mark=none, draw=none] {1/x} \closedcycle;
\addplot[pattern=north east lines] fill between [of=A and B];
\end{axis}
\end{tikzpicture}
\end{document}
Euler's constant

Euler's constant illustration

SVG generated by dvisvgm

Technical details:

  1. fillbetween is a PGF Plots library instead of a TikZ library.
  2. Axis labels are now at aligned with axis’ arrow tips.
  3. This causes the overlapping of a long title and the y-axis label. We introduced a slight upward shift to separate them.
  4. jump mark left is a special type of const plot mark left without vertical lines. We take verical lines away to avoid error in filling. In the manual, the line containing jump mark left starts with \addplot+.
  5. The colour outside mark options is for the line connecting the points. Inside mark options, draw is for the outer boundary, and fill is for the filling.
  6. Without \closedcycle, the fill between [of=A and B] won’t work as expected.
LaTeX 

No comment

Your email address will not be published. Required fields are marked *.