I need to draw some plots with vertical lines from the x axis to the function. For example, I defined the gauss(x)
function for the normal distribution and I drew this plot, with a vertical line from (1.96, 0) to (1,96, gauss(1.96)) and the corresponding simmetric line:
\documentclass{book}
\usepackage{tikz}
\usepackage{pgfplots} \pgfplotsset{compat=1.16}
\pgfmathdeclarefunction{gauss}{3}{%
\pgfmathparse{1/(#3*sqrt(2*pi))*exp(-((#1-#2)^2)/(2*#3^2))}
}
\usetikzlibrary{positioning}
\usetikzlibrary{shapes}
\usetikzlibrary{arrows}
\usetikzlibrary{arrows.meta}
\usetikzlibrary{decorations.pathmorphing}
\begin{document}
\begin{tikzpicture}
\begin{axis}[%
domain=-4:4, samples=61, smooth,
clip=false,
enlargelimits=upper
]
% normal distribution PDF
\addplot [thick] {gauss(x,0,1)};
% right vertical line
\pgfmathparse{gauss(+1.96,0,1)};
\pgfmathsetmacro\pgftempa\pgfmathresult;
\node[coordinate] (a) at (axis cs:+1.96,\pgftempa) {};
\draw (axis cs:+1.96,0) -- (a);
% left vertial line
\pgfmathparse{gauss(-1.96,0,1)};
\pgfmathsetmacro\pgftempb\pgfmathresult;
\node[coordinate] (b) at (axis cs:-1.96,\pgftempb) {};
\draw (axis cs:-1.96,0) -- (b);
\end{axis}
\end{tikzpicture}
\end{document}
(code above may contain some math errors as it's a MWE from a longer code, just ignore them)
I know, after searching on this forum, that I can't use gauss(x)
directly after axis cs
, but when I have to draw many lines the code becomes huge, and unreadable. Also, I'd like to avoid using many variables \pgftemp*.
Is there an easier way to evaluate a function which does not require three lines of code? For example, would it be possible to define a new command \evaluatefunction(x)
and write axis cs: 1.96,\evaluatefunction(1.96)
or \evaluatefunction{gauss(1.96,0,1)}
? I already tried this but it does not work:
\newcommand{\evaluatefunction}[1]{%
\pgfmathparse{#1};
\pgfmathsetmacro\pgftempa\pgfmathresult;
}
\node[coordinate] (a) at (axis cs:+1.96,\evaluatefunction{gauss(1.96,0,1)}) {};
Compilation of this code does not end, and I have to stop it, so I can't even get an error log.
Thank you!
\documentclass
command, include any necessary packages and be as small as possible to demonstrate your problem. It is much easier to help you if we can start with some compilable code that illustrates your problem - at the moment we have to guess what packages etc you are using...\pgfmathparse{#1)};
? Should be\pgfmathparse{#1};
?\draw (+1.96,0) -- (1.96,{gauss(+1.96,0,1)});
? Your code does not help in this regard, I am afraid. If you want so see benefits, just look at my code below, where one can just put\draw (1.96,0) -- (1.96,{gauss(1.96,0,1)});
and no mysterious shifts happen.\pgfmathdeclarefunction
is "bad" but it (sort of) was agreed on that the syntax I was familiar with id "better". I guess it has to do with thefpu
library.