# How to draw this function graph with plot operation(TIKZ，Loop)

I wish to draw a function graph, The analytical formula of the function is:

I can use the following code to draw an image of a specific function

But I want to be concise, how to define a letter n,

Draw the corresponding function image with the change of n

I think it should be realized by loop, but I don’t know how to do it

What needs to be done?

\documentclass{book}
\usepackage{tikz}

\begin{document}

\begin{tikzpicture}
\draw[->,>=stealth] (-4,0)  --  (4,0)   node[below] {$x$};
\draw[->,>=stealth] (0,-0.5)    --  (0,4)   node[right] {$y$};
\fill (0,0)  circle  (  0  )   node[  below   left  ] {  $O$  } ;

\draw[  domain=  -3  :  3  ,samples=  300  ] plot (  \x,  {
abs(\x)
});

\draw[  domain=  -3  :  3  ,samples=  300  ] plot (  \x,  {
abs(\x) + abs((\x) +  1)
});

\draw[  domain=  -3  :  3  ,samples=  300  ] plot (  \x,  {
abs(\x) + abs((\x) +  1)  + abs((\x) +  2)
});

\end{tikzpicture}

\end{document}

• For fun: With Asymptote: unitsize(1cm); import graph; typedef real newreal(real); newreal X(int n){ return new real(real x){ real s=0; for (int i=0; i<= n; ++i){ s=s+abs(x+i); } return s; }; } path g; g=graph(X(2),-3,1,n=300); draw(g); , with PSTricks: \documentclass[pstricks,border=15pt]{standalone} \usepackage{pstricks-add,xfp} \begin{document} \begin{pspicture}[showgrid,algebraic](-5,1)(3,7) \def\n{2} \def\X{0 }% \multido{\iB=0+1}{\fpeval{\n+1}}{ \xdef\X{\X + abs(x+\iB)} } \psplot[plotpoints=300]{-3}{1}{\X} \end{pspicture} \end{document} .
– user213378
Aug 20, 2020 at 8:25

Use math library.

\documentclass[tikz, border=1cm]{standalone}
\usetikzlibrary{math}

\begin{document}
\begin{tikzpicture}
\pgfset{fpu=true, fpu/output format=fixed}
\tikzmath{
function f(\x, \n) {
real \s;
\s = 0;
for \i in {0,...,\n}{
\s = \s + abs(\x + \i);
};
return \s;
};
}
\pgfset{fpu=false}
\draw[->,>=stealth] (-4,0) -- (4,0) node[below] {$x$};
\draw[->,>=stealth] (0,-0.5) -- (0,15) node[right] {$y$};
\fill (0,0) circle (2pt) node[below left] {$o$};
\foreach \i in {1,...,4} {
\draw [domain=-3:1, samples=300] plot (\x, {f(\x, \i)});
}
\end{tikzpicture}
\end{document}


• Thank you very much for your help, this code is great, it looks like a perfect solution But I still don’t understand some codes. I have not touched some corresponding concepts. Later, I will compare the pgfmanual manual and continue to learn TIKZ in depth Aug 21, 2020 at 17:24