1

I am looking for a nice way to draw graphs of functions with constants that I can define outside, something like the below example

\defineconstant{A}{4}
\addplot{A*e^x};

I would like A to have a scope local to the axis/tikzpicture, I understand that I could define commands, but this is not locally scoped.

Stefan Pinnow
  • 29,535
  • It is not clear, what you like to achieve. Is A constant (no a variable)? I will become more clear, if you will provide an example (MWE: Minimal Working Example) which will demonstrate, what you like to achieve. – Zarko Aug 19 '21 at 13:59
  • I want to have a way to make constants that I can define for a plot, I feel like the code there is sort of what I want to achieve and I don't know what else i could add to make it more understandable – finlay morrison Aug 19 '21 at 14:18
  • hm, \def\A{4}? – Zarko Aug 19 '21 at 14:28
  • Something like `\documentclass{standalone} \usepackage {pgfplots} \pgfplotsset {compat=1.17}

    \begin{document} \begin{tikzpicture} \begin{axis} \def\a{1} \def\b{2} \addplot[red,mark=none] (\x,\a\x+\b); \addplot[blue,mark=none] (\x,\b\x+\a); \end{axis} \end{tikzpicture} \end{document}`?

    – Juan Castaño Aug 19 '21 at 14:28
  • \documentclass[tikz,border=5mm]{standalone} \begin{document} \begin{tikzpicture} \tikzset{declare function={A=2;}} \draw[red,smooth] plot[domain=-2:1] (\x,{A*exp(\x)}); \draw (-3,0)--(2,0) node[below]{$x$} (0,-1)--(0,6) node[left]{$y$}; \end{tikzpicture} \end{document} – Black Mild Aug 19 '21 at 14:46

1 Answers1

2

There are several ways to declare "constants", as you could already see from the comments below the question. Here I show three of them which are all local, i.e. you cannot use them outside the first tikzpicture environment. You can test that by trying to use them later again which will result in errors.

They are local, because I define/declare them inside the tikzpicture environment. That makes them local. If you would e.g. move the definitions of \B and \C before \begin{tikzpicture} then they would also work in the second tikzpicture environment. (Of course also A could be made globally available.)

% used PGFPlots v1.18.1
\documentclass[border=5pt]{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}[
    % define/declare constants using PGFs math engine
    /pgf/declare function={
        A = 2;
    }
]
        % define a constant using PGFs "mathematical expressions"
        \pgfmathsetmacro{\B}{0.5}
        % define a constant using a LaTeX command
        \newcommand*{\C}{1}
    \begin{axis}
        \addplot {A*\B*\C};
    \end{axis}
\end{tikzpicture}
\begin{tikzpicture}
    \begin{axis}
% uncommenting the following lines will raise errors,
%        \addplot {A};
%        \addplot {\B};
%        \addplot {\C};
    \end{axis}
\end{tikzpicture}
\end{document}
Stefan Pinnow
  • 29,535