6

I would like to draw a set of random functions f(x) from point A to point B with a fixed random seed for each function. In other words, I would like to have functions which look the same each time I create the document, depending on their associated random seed.

So far, I have this:

\documentclass[tikz]{standalone}

% Random path from A=(0,0) to B=(1,1) with seed #1 and color #2
\newcommand\randompath[2]{%
\pgfextra{\pgfmathsetseed{#1}}%
\addplot[#2,domain=0:1,samples=5,smooth] { x+rand*(x)*(1-x)};%
}

\begin{document}

\begin{tikzpicture}
  \begin{axis}[xmin=0,xmax=1,ymin=0,ymax=1]
    \randompath{1}{red}   % 1st function
    \randompath{1}{blue}  % 2nd function
    \randompath{1}{green} % 3rd function
  \end{axis}
\end{tikzpicture}

\end{document}

However, the three functions are not identical and change their shape on recreation. Therefore, the \pgfmathsetseed does not seem to work as intended?

How can I achieve it that for a chosen seed number, the drawn \randompath function looks alway the same?

  • Everything that's put in \pgfextra is executed in a separate group at the end of the axis environment (after all the plots have been calculated). Remove the \pgfextra, and you'll get three identical plots. – Jake Jun 15 '15 at 17:13
  • I did not know that. Thank you. – JinZeng Jun 15 '15 at 17:24
8

Everything that's put in \pgfextra is executed in a separate group at the end of the axis environment (after all the plots have been calculated). Remove the \pgfextra, and you'll get three identical plots.

\documentclass[tikz]{standalone}

\usepackage{pgfplots}
% Random path from A=(0,0) to B=(1,1) with seed #1 and color #2
\newcommand\randompath[2]{%
\pgfmathsetseed{#1}%
\addplot[#2,domain=0:1,samples=5,smooth] { x+rand*(x)*(1-x)};%
}

\begin{document}

\begin{tikzpicture}
  \begin{axis}[xmin=0,xmax=1,ymin=0,ymax=1]
    \randompath{1}{red, line width=8pt}   % 1st function
    \randompath{1}{blue, line width=4pt}  % 2nd function
    \randompath{1}{green, line width=1pt} % 3rd function
  \end{axis}
\end{tikzpicture}

\end{document}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.