[Tex/LaTex] Randomized coordinates in TikZ

random numberstikz-pgf

I need to draw a number of `bacteria' in TikZ. Their coordinates and orientation needs to be random within a pre-defined scope.

I have randomized the orientation successfully, but not the location of each bacterium.

Here is what I have:

\documentclass{article}  
\usepackage{pgfplots}  
\pgfplotsset{compat=newest}  
\usetikzlibrary{calc,decorations,decorations.pathreplacing}  
\begin{document}  
    \newcommand{\bacterium}[3]{\scalebox{#2}{\tikz[rotate=#3]{
    \coordinate (A) at (#1);  
    \shadedraw[shading=ball,ball color=yellow!75, white,rounded corners=10](A) rectangle++(1.5,.65);  
    \draw[decorate,decoration={snake,amplitude=1mm}](A)++(0,.75*.5)--++(-1,0);}}}


\begin{tikzpicture}  
    \foreach \x in {1,2,...,10}{
    \bacterium{rand*10,rand*10}{.2}{rand*360}}  
\end{tikzpicture}  
\end{document}

This results in the bacteria orienting randomly but lining up along the x-axis.
enter image description here

Best Answer

The problem is that, inside your \bacterium macro you use a \tikz{} command to draw the bacterium. This command creates its own picture, so that each bacterium has its own coordinate system. In this coordinate system the bacteriumm is placed randomly, but then that picture is cropped to the size of the bacterium, so there is no difference if the bacterium is located at (30,10) or at (0,0), becacuse after the cropping it will look the same. In addition, you wrap that picture inside a \scalebox, which makes the whole picture to be treated as a single character.

The main for loop invokes \bacterium to create that set of pictures, and places them one after the other, as when composing a word from several characters.

As it was said other times at other places, it is not a good idea to nest tikz pictures.

What you need is that all the bacteria share the same coordinate system, i.e. they are all in the same tikz picture. The following code achieves this goal, by replacing your \tikz command by a tikz scope which allows the specification of a scale factor and a rotation factor.

\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}
\usetikzlibrary{calc,decorations,decorations.pathreplacing}
\begin{document}
\newcommand{\bacterium}[3]{
    \begin{scope}[scale=#2, rotate=#3]
    \coordinate (A) at (#1);
    \shadedraw[shading=ball,ball color=yellow!75, white,
              rounded corners=10*#2](A) rectangle++(1.5,.65);
    \draw[decorate,decoration={snake,amplitude=1mm}]
              (A)++(0,.75*.5)--++(-1,0);
\end{scope}
}


\pgfmathsetseed{1}
\begin{tikzpicture}
  \foreach \x in {1,2,...,10}{
    \bacterium{rand*10,rand*10}{.2}{rand*360}}
\end{tikzpicture}
\end{document}

Result

Related Question