3

I have the following code for drawing circles whose different radius. As seen in code there are two different pic statement (d1 and d2).

\documentclass[margin=3mm]{standalone}
\usepackage{tikz,pgf}
\begin{document}

\begin{tikzpicture}

%  \foreach \b in {1,2}{
    \tikzset{
        d1/.pic={
            \foreach \r in {1,...,4}{
                \draw[red,thick](\r,0) circle (\r);
            }
        }
    }
    \tikzset{
        d2/.pic={
            \foreach \r in {1,...,4}{
                \draw[black,thick](3*\r,0) circle (\r);
            }
        }
    }
%  }


    \pic at (0,0) {d1};
    \pic at (0,0) {d2};

    \end{tikzpicture}

\end{document}

Output of the code:

enter image description here

Is it possible to one pic statement for d1 and d2 using \foreach? For example:

\documentclass[margin=3mm]{standalone}
\usepackage{tikz,pgf}
\begin{document}

\begin{tikzpicture}
   \pgfmathsetmacro{\k}{1} 
  \foreach \b in {1,2}{
    \tikzset{
        d\b/.pic={

        \ifnum\b=2 \pgfmathsetmacro{\k}{2} \fi
            \foreach \r in {1,...,4}{
                \draw[red,thick](\k*\r,0) circle (\r);
            }
        }
    }  
    }

    \pic at (0,0) {d1};
    \pic at (0,0) {d2};

    \end{tikzpicture}

\end{document}

It seems that b counter in \foreach loop does not pass into the tikzset. How can I solve this problem?

1 Answer 1

5

You could just make the pic depend on an argument that indicates the color.

\documentclass[margin=3mm]{standalone}
\usepackage{tikz}
\begin{document}

\begin{tikzpicture}
\def\ColorList{{"black","red","blue"}}

    \tikzset{
        d/.pic={\pgfmathsetmacro{\mycolor}{\ColorList[#1]}
            \foreach \r in {1,...,4}{
                \draw[\mycolor,thick]({\r*(1+2*#1)},0) circle (\r);
            }
        }
    }

  \foreach \b in {0,1,2}{
    \pic at (0,0) {d=\b};
  } 
\end{tikzpicture}

\end{document}

enter image description here

1
  • 1
    Thank you very much. An interesting approach. Actually, that's the solution that I want.
    – user31034
    Commented Feb 12, 2019 at 17:32

You must log in to answer this question.