Reputation: 1453
I'm trying to draw a rectangle wit random points inside using tikz. My attempt is this:
\documentclass[tikz]{standalone}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usetikzlibrary{calc}
\pgfmathsetseed{20}
\tikzset{
particle/.style = {draw,circle,inner sep=0,outer sep=0,minimum size=3}
}
\tikzset{
pics/PE/.style
2 args={
code={
\node[
draw,rectangle,
minimum width=80,minimum height=40] (main) at (0,0) {};
\foreach \i in {1,...,#2}
{
\path let \p1 = (main.south west), \p2 = (main.north east) in
node[particle] at
($ (main.south west) + ({random(\x1,\x2)},{random(\y1,\y2)}) $) {};
}
}
}
}
\begin{document}
\begin{tikzpicture}
\draw pic {PE={1}{30}};
\end{tikzpicture}
\end{document}
...but this doesn't work. It seems I cannot use a coordinate inside a call to the random function. Is that so? Any workaround?
Cheers!!
Upvotes: 1
Views: 1207
Reputation: 1453
For what is worth, I ended up doing it like this (probably not the best solution...)
\newcommand{\PEwidth}{10}
\newcommand{\PEheight}{5}
\tikzset{
pics/PE/.style
2 args={
code={
\draw (0,0) rectangle (\PEwidth,\PEheight);
\foreach \i in {1,...,#2}
{
\pgfmathsetmacro\x{0.1*\PEwidth + 0.8*\PEwidth*rnd}
\pgfmathsetmacro\y{0.1*\PEheight + 0.8*\PEheight*rnd}
\node[particle] at (\x,\y) (-\i) {};
}
}
}
}
Upvotes: 1