I would like to have multiples circles drawn randomly within specified square area or triangular area. I tried a method explained by tikz: Distribute evenly and randomly circles with fixed starting point of square as (0,0). I modified it for my requirement which has some error. Modified code is
\documentclass[]{article}
\usepackage{tikz}
\usetikzlibrary{backgrounds}
\begin{document}
% Here #1, #2 -- start of rectanle coordinates (x,y)
% #3, #4 -- other end of rectanle coordinates (x,y)
% #5, #6 -- circle radius and count(number) of circles.
\def\xlist{6}
\def\ylist{6}
\newcommand{\fillrandomly}[6]{
\pgfmathsetmacro\diameter{#3*2}
\draw (#1,#2) rectangle (#3,#4);
\foreach \i in {1,...,#6}{
\pgfmathsetmacro\x{rnd*#3}
\pgfmathsetmacro\y{rnd*#4}
\xdef\collision{0}
\foreach \element [count=\i] in \xlist{
\pgfmathtruncatemacro\j{\i-1}
\pgfmathsetmacro\checkdistance{ sqrt( ({\xlist}[\j]-(\x))^2 + ({\ylist}[\j]-(\y))^2 ) }
\ifdim\checkdistance pt<\diameter pt
\xdef\collision{1}
\breakforeach
\fi
}
\ifnum\collision=0
\xdef\xlist{\xlist,\x}
\xdef\ylist{\ylist,\y}
\draw [black, fill=gray, thick] (\x,\y) circle [radius=#5];
\fi
}
}
\pgfmathsetseed{2}
\fillrandomly{0.25}{2}{2}{4}{0.2}{200}
%%%%%%%%
\end{tikzpicture}
\end{figure}
\end{document}
What is wrong in this code? Here is my poor code for generating required image
\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{figure}[htbp]
\centering
% \resizebox{0.98\textwidth}{!}{%
\begin{tikzpicture} [every text node part/.style={align=center}, font=\scriptsize]
\draw [->] (0,0) -- node[anchor=south] {x} (4,0);
\draw [->] (0,0) -- node[anchor = east] {y} (0,4);
\draw[ help lines,line width=0.005pt,step=0.5] (0,0) grid (4,4);
\draw (0.25, 2) rectangle (2,4);
\tikzset{my_circle/.style={circle, inner sep=0pt, minimum size=0.15cm, black,fill=gray, draw=none}};
\node[my_circle] at (0.5,2. 3) {};
\node[my_circle] at (0.8,2.3) {};
\node[my_circle] at (1,2.5) {};
\node[my_circle] at (1.4,3) {};
\node[my_circle] at (1.5,3.5) {};
\node[my_circle] at (1.5,3.8) {};
\node[my_circle] at (1.8,3.7) {};
\node[my_circle] at (1.5,3.5) {};
\node[my_circle] at (1,3) {};
\node[my_circle] at (0.6,3) {};
\node[my_circle] at (0.4,3.5) {};
\node[my_circle] at (1.8,2.6) {};
\node[my_circle] at (1.5,2.2) {};
\node[my_circle] at (0.8,3.8) {};
\end{tikzpicture}
\end{figure}
\end{document}
\diameter{#3*2}should be\diameter{#5*2}, shouldn't? – Sigur Jan 29 '22 at 17:02Undefined control sequence. \fillrandomly{0.25}{2}{2}{4}{0.2}{200}. I am unable to trace it out. – Ubaidulla Jan 29 '22 at 17:34