4

I want to plot continuous, piece-wise linear functions in tikz using declare function. I can build the functions by hand, but I'd like to define a new command to make this easier. The parameters of the new command should be the y-values of the function at x=0, 1, and 2.

Here is my attempt, followed by the output:

\documentclass{article}
\usepackage{pgfplots,tikz}

\newcommand{\build}[3]{declare function={f(\x)=(\x<=1)((#2-#1)\x+#1)+and(\x>1,\x<=2)((#3-#2)(\x-1)+#2);}}

\pgfplotsset{compat=1.17}

\begin{document}

\begin{tikzpicture}[declare function={f(\x)=(\x<=1)(2\x)+ and(\x>1,\x<=2)(-2\x+4);}] \begin{axis}[samples at={0,1,2}, ymin=0, ymax=2, ytick={1,2}, xmin=0, xmax=2, xtick={1,2}] \addplot{f(x)}; \end{axis} \end{tikzpicture}

\begin{tikzpicture}[\build{0}{2}{0}] \begin{axis}[samples at={0,1,2}, ymin=0, ymax=2, ytick={1,2}, xmin=0, xmax=2, xtick={1,2}] \addplot{f(x)}; \end{axis} \end{tikzpicture}

\end{document}

enter image description here

The first piece-wise function is built by hand, and the second is my attempt to plot the same function using the new command build. My grasp of the subtleties of newcommand is weak, and a few searches haven't led me to an obvious error. How can I fix my new command build to achieve my desired effect?

Jared
  • 641

1 Answers1

5

You only need to convert your macro into a style. Or define a function of several arguments.

\documentclass{article}
\usepackage{pgfplots,tikz}

\tikzset{build/.style n args={3}{declare function={f(\x)=(\x<=1)((#2-#1)\x+#1)+and(\x>1,\x<=2)((#3-#2)(\x-1)+#2);}}} \tikzset{declare function={mypiecewise(\x,\a,\b,\c)=(\x<=1)((\b-\a)\x+\a)+and(\x>1,\x<=2)((\c-\b)(\x-1)+\b);}} \pgfplotsset{compat=1.17}

\begin{document}

\begin{tikzpicture}[declare function={f(\x)=(\x<=1)(2\x)+ and(\x>1,\x<=2)(-2\x+4);}] \begin{axis}[samples at={0,1,2}, ymin=0, ymax=2, ytick={1,2}, xmin=0, xmax=2, xtick={1,2}] \addplot{f(x)}; \end{axis} \end{tikzpicture}

\begin{tikzpicture}[build={0}{2}{0}] \begin{axis}[samples at={0,1,2}, ymin=0, ymax=2, ytick={1,2}, xmin=0, xmax=2, xtick={1,2}] \addplot{f(x)}; \end{axis} \end{tikzpicture}

\begin{tikzpicture} \begin{axis}[samples at={0,1,2}, ymin=0, ymax=2, ytick={1,2}, xmin=0, xmax=2, xtick={1,2}] \addplot{mypiecewise(x,0,2,0)}; \end{axis} \end{tikzpicture} \end{document}

enter image description here